diff options
author | Andres Erbsen <andreser@mit.edu> | 2017-04-06 23:23:16 -0400 |
---|---|---|
committer | Andres Erbsen <andreser@mit.edu> | 2017-04-06 23:23:16 -0400 |
commit | 7461b2c5151146cf397a8b2c4399db4cc1e6d78b (patch) | |
tree | 6846fdffeeab77b9d5713a577e07b5daf024f5b3 | |
parent | be79f23b1b0ba22d0063821d233ed86185b11ca6 (diff) | |
parent | c9fc5a3cdf1f5ea2d104c150c30d1b1a6ac64239 (diff) |
Merge branch 'rename-everything'. Closes #14.
-rw-r--r-- | README.md | 2 | ||||
-rw-r--r-- | _CoqProject | 410 | ||||
-rw-r--r-- | cleanup.md | 139 | ||||
-rw-r--r-- | src/Algebra/Field.v | 32 | ||||
-rw-r--r-- | src/Algebra/Field_test.v | 2 | ||||
-rw-r--r-- | src/Algebra/Group.v | 2 | ||||
-rw-r--r-- | src/Algebra/Hierarchy.v (renamed from src/Algebra.v) | 0 | ||||
-rw-r--r-- | src/Algebra/IntegralDomain.v | 10 | ||||
-rw-r--r-- | src/Algebra/Monoid.v | 2 | ||||
-rw-r--r-- | src/Algebra/Nsatz.v (renamed from src/Tactics/Algebra_syntax/Nsatz.v) | 5 | ||||
-rw-r--r-- | src/Algebra/Ring.v | 4 | ||||
-rw-r--r-- | src/Algebra/ScalarMult.v | 2 | ||||
-rw-r--r-- | src/Arithmetic/BarrettReduction/Generalized.v (renamed from src/ModularArithmetic/BarrettReduction/ZGeneralized.v) | 2 | ||||
-rw-r--r-- | src/Arithmetic/BarrettReduction/HAC.v (renamed from src/ModularArithmetic/BarrettReduction/ZHandbook.v) | 2 | ||||
-rw-r--r-- | src/Arithmetic/BarrettReduction/Wikipedia.v (renamed from src/ModularArithmetic/BarrettReduction/Z.v) | 0 | ||||
-rw-r--r-- | src/Arithmetic/Core.v (renamed from src/NewBaseSystem.v) | 8 | ||||
-rw-r--r-- | src/Arithmetic/Karatsuba.v (renamed from src/Karatsuba.v) | 2 | ||||
-rw-r--r-- | src/Arithmetic/ModularArithmeticPre.v (renamed from src/ModularArithmetic/Pre.v) | 6 | ||||
-rw-r--r-- | src/Arithmetic/ModularArithmeticTheorems.v (renamed from src/ModularArithmetic/ModularArithmeticTheorems.v) | 12 | ||||
-rw-r--r-- | src/Arithmetic/MontgomeryReduction/Definition.v (renamed from src/ModularArithmetic/Montgomery/Z.v) | 0 | ||||
-rw-r--r-- | src/Arithmetic/MontgomeryReduction/Proofs.v (renamed from src/ModularArithmetic/Montgomery/ZProofs.v) | 42 | ||||
-rw-r--r-- | src/Arithmetic/PrimeFieldTheorems.v (renamed from src/ModularArithmetic/PrimeFieldTheorems.v) | 26 | ||||
-rw-r--r-- | src/Arithmetic/Saturated.v (renamed from src/SaturatedBaseSystem.v) | 4 | ||||
-rw-r--r-- | src/Assembly/Bounds.v | 515 | ||||
-rw-r--r-- | src/Assembly/Compile.v | 299 | ||||
-rw-r--r-- | src/Assembly/Conversions.v | 458 | ||||
-rw-r--r-- | src/Assembly/Evaluables.v | 782 | ||||
-rw-r--r-- | src/Assembly/GF25519.v | 313 | ||||
-rw-r--r-- | src/Assembly/HL.v | 212 | ||||
-rw-r--r-- | src/Assembly/LL.v | 180 | ||||
-rw-r--r-- | src/Assembly/Output.ml | 14 | ||||
-rw-r--r-- | src/Assembly/PhoasCommon.v | 42 | ||||
-rw-r--r-- | src/Assembly/Pipeline.v | 140 | ||||
-rw-r--r-- | src/Assembly/Qhasm.v | 81 | ||||
-rw-r--r-- | src/Assembly/QhasmCommon.v | 149 | ||||
-rw-r--r-- | src/Assembly/QhasmEvalCommon.v | 299 | ||||
-rw-r--r-- | src/Assembly/QhasmUtil.v | 91 | ||||
-rw-r--r-- | src/Assembly/State.v | 331 | ||||
-rw-r--r-- | src/Assembly/StringConversion.v | 367 | ||||
-rw-r--r-- | src/Assembly/WordizeUtil.v | 996 | ||||
-rw-r--r-- | src/BaseSystem.v | 212 | ||||
-rw-r--r-- | src/BaseSystemProofs.v | 710 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Core.v | 127 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/BitwiseOr.v | 26 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/Decode.v | 114 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/LoadImmediate.v | 26 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/Multiply.v | 96 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/RippleCarryAddSub.v | 38 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/SelectConditional.v | 26 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/ShiftLeftRight.v | 42 | ||||
-rw-r--r-- | src/BoundedArithmetic/Double/Repeated/Proofs/ShiftRightDoubleWordImmediate.v | 30 | ||||
-rw-r--r-- | src/BoundedArithmetic/Eta.v | 70 | ||||
-rw-r--r-- | src/BoundedArithmetic/StripCF.v | 74 | ||||
-rw-r--r-- | src/BoundedArithmetic/X86ToZLike.v | 73 | ||||
-rw-r--r-- | src/BoundedArithmetic/X86ToZLikeProofs.v | 190 | ||||
-rw-r--r-- | src/Compilers/BoundByCast.v (renamed from src/Reflection/BoundByCast.v) | 16 | ||||
-rw-r--r-- | src/Compilers/BoundByCastInterp.v (renamed from src/Reflection/BoundByCastInterp.v) | 34 | ||||
-rw-r--r-- | src/Compilers/BoundByCastWf.v (renamed from src/Reflection/BoundByCastWf.v) | 16 | ||||
-rw-r--r-- | src/Compilers/CommonSubexpressionElimination.v (renamed from src/Reflection/CommonSubexpressionElimination.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Conversion.v (renamed from src/Reflection/Conversion.v) | 4 | ||||
-rw-r--r-- | src/Compilers/CountLets.v (renamed from src/Reflection/CountLets.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Equality.v (renamed from src/Reflection/Equality.v) | 2 | ||||
-rw-r--r-- | src/Compilers/Eta.v (renamed from src/Reflection/Eta.v) | 4 | ||||
-rw-r--r-- | src/Compilers/EtaInterp.v (renamed from src/Reflection/EtaInterp.v) | 6 | ||||
-rw-r--r-- | src/Compilers/EtaWf.v (renamed from src/Reflection/EtaWf.v) | 12 | ||||
-rw-r--r-- | src/Compilers/ExprInversion.v (renamed from src/Reflection/ExprInversion.v) | 4 | ||||
-rw-r--r-- | src/Compilers/FilterLive.v (renamed from src/Reflection/FilterLive.v) | 8 | ||||
-rw-r--r-- | src/Compilers/FoldTypes.v (renamed from src/Reflection/FoldTypes.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Inline.v (renamed from src/Reflection/Inline.v) | 4 | ||||
-rw-r--r-- | src/Compilers/InlineCast.v (renamed from src/Reflection/InlineCast.v) | 8 | ||||
-rw-r--r-- | src/Compilers/InlineCastInterp.v (renamed from src/Reflection/InlineCastInterp.v) | 22 | ||||
-rw-r--r-- | src/Compilers/InlineCastWf.v (renamed from src/Reflection/InlineCastWf.v) | 20 | ||||
-rw-r--r-- | src/Compilers/InlineInterp.v (renamed from src/Reflection/InlineInterp.v) | 12 | ||||
-rw-r--r-- | src/Compilers/InlineWf.v (renamed from src/Reflection/InlineWf.v) | 14 | ||||
-rw-r--r-- | src/Compilers/InputSyntax.v (renamed from src/Reflection/InputSyntax.v) | 8 | ||||
-rw-r--r-- | src/Compilers/InterpByIso.v (renamed from src/Reflection/InterpByIso.v) | 6 | ||||
-rw-r--r-- | src/Compilers/InterpByIsoProofs.v (renamed from src/Reflection/InterpByIsoProofs.v) | 12 | ||||
-rw-r--r-- | src/Compilers/InterpProofs.v (renamed from src/Reflection/InterpProofs.v) | 8 | ||||
-rw-r--r-- | src/Compilers/InterpWf.v (renamed from src/Reflection/InterpWf.v) | 6 | ||||
-rw-r--r-- | src/Compilers/InterpWfRel.v (renamed from src/Reflection/InterpWfRel.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Linearize.v (renamed from src/Reflection/Linearize.v) | 4 | ||||
-rw-r--r-- | src/Compilers/LinearizeInterp.v (renamed from src/Reflection/LinearizeInterp.v) | 12 | ||||
-rw-r--r-- | src/Compilers/LinearizeWf.v (renamed from src/Reflection/LinearizeWf.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Map.v (renamed from src/Reflection/Map.v) | 2 | ||||
-rw-r--r-- | src/Compilers/MapCast.v (renamed from src/Reflection/MapCast.v) | 6 | ||||
-rw-r--r-- | src/Compilers/MapCastByDeBruijn.v (renamed from src/Reflection/MapCastByDeBruijn.v) | 16 | ||||
-rw-r--r-- | src/Compilers/MapCastByDeBruijnInterp.v (renamed from src/Reflection/MapCastByDeBruijnInterp.v) | 30 | ||||
-rw-r--r-- | src/Compilers/MapCastByDeBruijnWf.v (renamed from src/Reflection/MapCastByDeBruijnWf.v) | 26 | ||||
-rw-r--r-- | src/Compilers/MapCastInterp.v (renamed from src/Reflection/MapCastInterp.v) | 16 | ||||
-rw-r--r-- | src/Compilers/MapCastWf.v (renamed from src/Reflection/MapCastWf.v) | 14 | ||||
-rw-r--r-- | src/Compilers/MultiSizeTest.v (renamed from src/Reflection/MultiSizeTest.v) | 2 | ||||
-rw-r--r-- | src/Compilers/MultiSizeTest2.v (renamed from src/Reflection/MultiSizeTest2.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Named/Compile.v (renamed from src/Reflection/Named/Compile.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Named/CompileInterp.v (renamed from src/Reflection/Named/CompileInterp.v) | 18 | ||||
-rw-r--r-- | src/Compilers/Named/CompileProperties.v (renamed from src/Reflection/Named/CompileProperties.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Named/CompileWf.v (renamed from src/Reflection/Named/CompileWf.v) | 20 | ||||
-rw-r--r-- | src/Compilers/Named/ContextDefinitions.v (renamed from src/Reflection/Named/ContextDefinitions.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Named/ContextOn.v (renamed from src/Reflection/Named/ContextOn.v) | 2 | ||||
-rw-r--r-- | src/Compilers/Named/ContextProperties.v (renamed from src/Reflection/Named/ContextProperties.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Named/ContextProperties/NameUtil.v (renamed from src/Reflection/Named/ContextProperties/NameUtil.v) | 16 | ||||
-rw-r--r-- | src/Compilers/Named/ContextProperties/SmartMap.v (renamed from src/Reflection/Named/ContextProperties/SmartMap.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Named/ContextProperties/Tactics.v (renamed from src/Reflection/Named/ContextProperties/Tactics.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Named/DeadCodeElimination.v (renamed from src/Reflection/Named/DeadCodeElimination.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Named/EstablishLiveness.v (renamed from src/Reflection/Named/EstablishLiveness.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Named/FMapContext.v (renamed from src/Reflection/Named/FMapContext.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Named/IdContext.v (renamed from src/Reflection/Named/IdContext.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Named/InterpretToPHOAS.v (renamed from src/Reflection/Named/InterpretToPHOAS.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Named/InterpretToPHOASInterp.v (renamed from src/Reflection/Named/InterpretToPHOASInterp.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Named/InterpretToPHOASWf.v (renamed from src/Reflection/Named/InterpretToPHOASWf.v) | 16 | ||||
-rw-r--r-- | src/Compilers/Named/MapCast.v (renamed from src/Reflection/Named/MapCast.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Named/MapCastInterp.v (renamed from src/Reflection/Named/MapCastInterp.v) | 16 | ||||
-rw-r--r-- | src/Compilers/Named/MapCastWf.v (renamed from src/Reflection/Named/MapCastWf.v) | 18 | ||||
-rw-r--r-- | src/Compilers/Named/NameUtil.v (renamed from src/Reflection/Named/NameUtil.v) | 2 | ||||
-rw-r--r-- | src/Compilers/Named/NameUtilProperties.v (renamed from src/Reflection/Named/NameUtilProperties.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Named/PositiveContext.v (renamed from src/Reflection/Named/PositiveContext.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Named/PositiveContext/Defaults.v (renamed from src/Reflection/Named/PositiveContext/Defaults.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Named/PositiveContext/DefaultsProperties.v (renamed from src/Reflection/Named/PositiveContext/DefaultsProperties.v) | 10 | ||||
-rw-r--r-- | src/Compilers/Named/RegisterAssign.v (renamed from src/Reflection/Named/RegisterAssign.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Named/SmartMap.v (renamed from src/Reflection/Named/SmartMap.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Named/Syntax.v (renamed from src/Reflection/Named/Syntax.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Named/Wf.v (renamed from src/Reflection/Named/Wf.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Named/WfInterp.v (renamed from src/Reflection/Named/WfInterp.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Reify.v (renamed from src/Reflection/Reify.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Relations.v (renamed from src/Reflection/Relations.v) | 6 | ||||
-rw-r--r-- | src/Compilers/RenameBinders.v (renamed from src/Reflection/RenameBinders.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Rewriter.v (renamed from src/Reflection/Rewriter.v) | 2 | ||||
-rw-r--r-- | src/Compilers/RewriterInterp.v (renamed from src/Reflection/RewriterInterp.v) | 4 | ||||
-rw-r--r-- | src/Compilers/RewriterWf.v (renamed from src/Reflection/RewriterWf.v) | 8 | ||||
-rw-r--r-- | src/Compilers/SmartBound.v (renamed from src/Reflection/SmartBound.v) | 10 | ||||
-rw-r--r-- | src/Compilers/SmartBoundInterp.v (renamed from src/Reflection/SmartBoundInterp.v) | 34 | ||||
-rw-r--r-- | src/Compilers/SmartBoundWf.v (renamed from src/Reflection/SmartBoundWf.v) | 18 | ||||
-rw-r--r-- | src/Compilers/SmartCast.v (renamed from src/Reflection/SmartCast.v) | 4 | ||||
-rw-r--r-- | src/Compilers/SmartCastInterp.v (renamed from src/Reflection/SmartCastInterp.v) | 8 | ||||
-rw-r--r-- | src/Compilers/SmartCastWf.v (renamed from src/Reflection/SmartCastWf.v) | 10 | ||||
-rw-r--r-- | src/Compilers/SmartMap.v (renamed from src/Reflection/SmartMap.v) | 2 | ||||
-rw-r--r-- | src/Compilers/Syntax.v (renamed from src/Reflection/Syntax.v) | 0 | ||||
-rw-r--r-- | src/Compilers/TestCase.v (renamed from src/Reflection/TestCase.v) | 27 | ||||
-rw-r--r-- | src/Compilers/Tuple.v (renamed from src/Reflection/Tuple.v) | 2 | ||||
-rw-r--r-- | src/Compilers/TypeInversion.v (renamed from src/Reflection/TypeInversion.v) | 2 | ||||
-rw-r--r-- | src/Compilers/TypeUtil.v (renamed from src/Reflection/TypeUtil.v) | 2 | ||||
-rw-r--r-- | src/Compilers/Wf.v (renamed from src/Reflection/Wf.v) | 2 | ||||
-rw-r--r-- | src/Compilers/WfInversion.v (renamed from src/Reflection/WfInversion.v) | 6 | ||||
-rw-r--r-- | src/Compilers/WfProofs.v (renamed from src/Reflection/WfProofs.v) | 10 | ||||
-rw-r--r-- | src/Compilers/WfReflective.v (renamed from src/Reflection/WfReflective.v) | 8 | ||||
-rw-r--r-- | src/Compilers/WfReflectiveGen.v (renamed from src/Reflection/WfReflectiveGen.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Z/ArithmeticSimplifier.v (renamed from src/Reflection/Z/ArithmeticSimplifier.v) | 9 | ||||
-rw-r--r-- | src/Compilers/Z/ArithmeticSimplifierInterp.v (renamed from src/Reflection/Z/ArithmeticSimplifierInterp.v) | 18 | ||||
-rw-r--r-- | src/Compilers/Z/ArithmeticSimplifierUtil.v (renamed from src/Reflection/Z/ArithmeticSimplifierUtil.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Z/ArithmeticSimplifierWf.v (renamed from src/Reflection/Z/ArithmeticSimplifierWf.v) | 20 | ||||
-rw-r--r-- | src/Compilers/Z/BinaryNotationConstants.v (renamed from src/Reflection/Z/BinaryNotationConstants.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/Interpretation.v (renamed from src/Reflection/Z/Bounds/Interpretation.v) | 11 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/InterpretationLemmas.v (renamed from src/Reflection/Z/Bounds/InterpretationLemmas.v) | 27 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/MapCastByDeBruijn.v (renamed from src/Reflection/Z/Bounds/MapCastByDeBruijn.v) | 10 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/MapCastByDeBruijnInterp.v (renamed from src/Reflection/Z/Bounds/MapCastByDeBruijnInterp.v) | 20 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/MapCastByDeBruijnWf.v (renamed from src/Reflection/Z/Bounds/MapCastByDeBruijnWf.v) | 20 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/Pipeline.v (renamed from src/Reflection/Z/Bounds/Pipeline.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/Pipeline/Definition.v (renamed from src/Reflection/Z/Bounds/Pipeline/Definition.v) | 44 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/Pipeline/Glue.v (renamed from src/Reflection/Z/Bounds/Pipeline/Glue.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/Pipeline/OutputType.v (renamed from src/Reflection/Z/Bounds/Pipeline/OutputType.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/Pipeline/ReflectiveTactics.v (renamed from src/Reflection/Z/Bounds/Pipeline/ReflectiveTactics.v) | 62 | ||||
-rw-r--r-- | src/Compilers/Z/Bounds/Relax.v (renamed from src/Reflection/Z/Bounds/Relax.v) | 16 | ||||
-rw-r--r-- | src/Compilers/Z/CNotations.v (renamed from src/Reflection/Z/CNotations.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Z/FoldTypes.v (renamed from src/Reflection/Z/FoldTypes.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Z/HexNotationConstants.v (renamed from src/Reflection/Z/HexNotationConstants.v) | 4 | ||||
-rw-r--r-- | src/Compilers/Z/Inline.v | 7 | ||||
-rw-r--r-- | src/Compilers/Z/InlineInterp.v (renamed from src/Reflection/Z/InlineInterp.v) | 10 | ||||
-rw-r--r-- | src/Compilers/Z/InlineWf.v | 11 | ||||
-rw-r--r-- | src/Compilers/Z/JavaNotations.v (renamed from src/Reflection/Z/JavaNotations.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Z/MapCastByDeBruijn.v (renamed from src/Reflection/Z/MapCastByDeBruijn.v) | 8 | ||||
-rw-r--r-- | src/Compilers/Z/MapCastByDeBruijnInterp.v (renamed from src/Reflection/Z/MapCastByDeBruijnInterp.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Z/MapCastByDeBruijnWf.v (renamed from src/Reflection/Z/MapCastByDeBruijnWf.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Z/OpInversion.v (renamed from src/Reflection/Z/OpInversion.v) | 6 | ||||
-rw-r--r-- | src/Compilers/Z/Reify.v | 50 | ||||
-rw-r--r-- | src/Compilers/Z/Syntax.v (renamed from src/Reflection/Z/Syntax.v) | 14 | ||||
-rw-r--r-- | src/Compilers/Z/Syntax/Equality.v (renamed from src/Reflection/Z/Syntax/Equality.v) | 16 | ||||
-rw-r--r-- | src/Compilers/Z/Syntax/Util.v (renamed from src/Reflection/Z/Syntax/Util.v) | 15 | ||||
-rw-r--r-- | src/Curves/Edwards/AffineProofs.v (renamed from src/CompleteEdwardsCurve/CompleteEdwardsCurveTheorems.v) | 6 | ||||
-rw-r--r-- | src/Curves/Edwards/Montgomery.v (renamed from src/CompleteEdwardsCurve/EdwardsMontgomery.v) | 14 | ||||
-rw-r--r-- | src/Curves/Edwards/Pre.v (renamed from src/CompleteEdwardsCurve/Pre.v) | 4 | ||||
-rw-r--r-- | src/Curves/Edwards/XYZT.v (renamed from src/CompleteEdwardsCurve/ExtendedCoordinates.v) | 12 | ||||
-rw-r--r-- | src/Curves/Montgomery/Affine.v (renamed from src/MontgomeryCurve.v) | 4 | ||||
-rw-r--r-- | src/Curves/Montgomery/AffineProofs.v (renamed from src/MontgomeryCurveTheorems.v) | 19 | ||||
-rw-r--r-- | src/Curves/Montgomery/XZ.v (renamed from src/MontgomeryX.v) | 9 | ||||
-rw-r--r-- | src/Curves/Montgomery/XZProofs.v (renamed from src/MontgomeryXProofs.v) | 11 | ||||
-rw-r--r-- | src/Curves/Weierstrass/Affine.v (renamed from src/WeierstrassCurve/Definitions.v) | 4 | ||||
-rw-r--r-- | src/Curves/Weierstrass/AffineProofs.v (renamed from src/WeierstrassCurve/WeierstrassCurveTheorems.v) | 10 | ||||
-rw-r--r-- | src/Curves/Weierstrass/Pre.v (renamed from src/WeierstrassCurve/Pre.v) | 4 | ||||
-rw-r--r-- | src/Curves/Weierstrass/Projective.v (renamed from src/WeierstrassCurve/Projective.v) | 2 | ||||
-rw-r--r-- | src/Encoding/EncodingTheorems.v | 14 | ||||
-rw-r--r-- | src/Encoding/ModularWordEncodingPre.v | 45 | ||||
-rw-r--r-- | src/Encoding/ModularWordEncodingTheorems.v | 46 | ||||
-rw-r--r-- | src/Experiments/Ed25519_imports.hs | 5 | ||||
-rw-r--r-- | src/Experiments/ExtrHaskellNats.v | 111 | ||||
-rw-r--r-- | src/Experiments/GenericFieldPow.v | 350 | ||||
-rw-r--r-- | src/Experiments/c.sh | 19 | ||||
-rw-r--r-- | src/LegacyArithmetic/ArchitectureToZLike.v (renamed from src/BoundedArithmetic/ArchitectureToZLike.v) | 6 | ||||
-rw-r--r-- | src/LegacyArithmetic/ArchitectureToZLikeProofs.v (renamed from src/BoundedArithmetic/ArchitectureToZLikeProofs.v) | 14 | ||||
-rw-r--r-- | src/LegacyArithmetic/BarretReduction.v (renamed from src/ModularArithmetic/BarrettReduction/ZBounded.v) | 4 | ||||
-rw-r--r-- | src/LegacyArithmetic/BaseSystem.v | 39 | ||||
-rw-r--r-- | src/LegacyArithmetic/BaseSystemProofs.v | 133 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Core.v (renamed from src/BoundedArithmetic/Double/Core.v) | 10 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/BitwiseOr.v (renamed from src/BoundedArithmetic/Double/Proofs/BitwiseOr.v) | 6 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/Decode.v (renamed from src/BoundedArithmetic/Double/Proofs/Decode.v) | 35 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/LoadImmediate.v (renamed from src/BoundedArithmetic/Double/Proofs/LoadImmediate.v) | 8 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/Multiply.v (renamed from src/BoundedArithmetic/Double/Proofs/Multiply.v) | 12 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/RippleCarryAddSub.v (renamed from src/BoundedArithmetic/Double/Proofs/RippleCarryAddSub.v) | 8 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/SelectConditional.v (renamed from src/BoundedArithmetic/Double/Proofs/SelectConditional.v) | 6 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/ShiftLeft.v (renamed from src/BoundedArithmetic/Double/Proofs/ShiftLeft.v) | 8 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/ShiftLeftRightTactic.v (renamed from src/BoundedArithmetic/Double/Proofs/ShiftLeftRightTactic.v) | 2 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/ShiftRight.v (renamed from src/BoundedArithmetic/Double/Proofs/ShiftRight.v) | 8 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v (renamed from src/BoundedArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v) | 8 | ||||
-rw-r--r-- | src/LegacyArithmetic/Double/Proofs/SpreadLeftImmediate.v (renamed from src/BoundedArithmetic/Double/Proofs/SpreadLeftImmediate.v) | 8 | ||||
-rw-r--r-- | src/LegacyArithmetic/Interface.v (renamed from src/BoundedArithmetic/Interface.v) | 0 | ||||
-rw-r--r-- | src/LegacyArithmetic/InterfaceProofs.v (renamed from src/BoundedArithmetic/InterfaceProofs.v) | 2 | ||||
-rw-r--r-- | src/LegacyArithmetic/MontgomeryReduction.v (renamed from src/ModularArithmetic/Montgomery/ZBounded.v) | 14 | ||||
-rw-r--r-- | src/LegacyArithmetic/Pow2Base.v | 19 | ||||
-rw-r--r-- | src/LegacyArithmetic/Pow2BaseProofs.v | 555 | ||||
-rw-r--r-- | src/LegacyArithmetic/README.md | 3 | ||||
-rw-r--r-- | src/LegacyArithmetic/VerdiTactics.v (renamed from src/Tactics/VerdiTactics.v) | 122 | ||||
-rw-r--r-- | src/LegacyArithmetic/ZBounded.v (renamed from src/ModularArithmetic/ZBounded.v) | 0 | ||||
-rw-r--r-- | src/LegacyArithmetic/ZBoundedZ.v (renamed from src/ModularArithmetic/ZBoundedZ.v) | 2 | ||||
-rw-r--r-- | src/ModularArithmetic/Conversion.v | 318 | ||||
-rw-r--r-- | src/ModularArithmetic/ExtPow2BaseMulProofs.v | 34 | ||||
-rw-r--r-- | src/ModularArithmetic/ExtendedBaseVector.v | 200 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystem.v | 124 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystemList.v | 90 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystemListProofs.v | 539 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystemListZOperations.v | 60 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystemListZOperationsProofs.v | 29 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystemOpt.v | 1094 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystemProofs.v | 1145 | ||||
-rw-r--r-- | src/ModularArithmetic/ModularBaseSystemWord.v | 23 | ||||
-rw-r--r-- | src/ModularArithmetic/Pow2Base.v | 89 | ||||
-rw-r--r-- | src/ModularArithmetic/Pow2BaseProofs.v | 1557 | ||||
-rw-r--r-- | src/ModularArithmetic/PseudoMersenneBaseParamProofs.v | 99 | ||||
-rw-r--r-- | src/ModularArithmetic/PseudoMersenneBaseParams.v | 24 | ||||
-rw-r--r-- | src/Primitives/EdDSARepChange.v (renamed from src/EdDSARepChange.v) | 6 | ||||
-rw-r--r-- | src/Primitives/MxDHRepChange.v (renamed from src/MxDHRepChange.v) | 15 | ||||
-rw-r--r-- | src/Reflection/Z/Inline.v | 7 | ||||
-rw-r--r-- | src/Reflection/Z/InlineWf.v | 11 | ||||
-rw-r--r-- | src/Reflection/Z/Reify.v | 59 | ||||
-rw-r--r-- | src/Spec/CompleteEdwardsCurve.v | 4 | ||||
-rw-r--r-- | src/Spec/Ed25519.v | 5 | ||||
-rw-r--r-- | src/Spec/EdDSA.v | 4 | ||||
-rw-r--r-- | src/Spec/Encoding.v | 8 | ||||
-rw-r--r-- | src/Spec/ModularArithmetic.v | 8 | ||||
-rw-r--r-- | src/Spec/ModularWordEncoding.v | 40 | ||||
-rw-r--r-- | src/Spec/MontgomeryCurve.v | 4 | ||||
-rw-r--r-- | src/Spec/MxDH.v | 4 | ||||
-rw-r--r-- | src/Spec/Test/X25519.v (renamed from src/Test/Curve25519SpecTestVectors.v) | 0 | ||||
-rw-r--r-- | src/Spec/WeierstrassCurve.v | 4 | ||||
-rw-r--r-- | src/Specific/ArithmeticSynthesisTest.v (renamed from src/Specific/NewBaseSystemTest.v) | 4 | ||||
-rw-r--r-- | src/Specific/FancyMachine256/Barrett.v | 4 | ||||
-rw-r--r-- | src/Specific/FancyMachine256/Core.v | 30 | ||||
-rw-r--r-- | src/Specific/FancyMachine256/Montgomery.v | 6 | ||||
-rw-r--r-- | src/Specific/GF1305.v | 404 | ||||
-rw-r--r-- | src/Specific/GF25519.v | 785 | ||||
-rw-r--r-- | src/Specific/IntegrationTestMul.v | 9 | ||||
-rw-r--r-- | src/Specific/IntegrationTestSub.v | 9 | ||||
-rw-r--r-- | src/Specific/SC25519.v | 171 | ||||
-rw-r--r-- | src/SpecificGen/2213_32.json | 7 | ||||
-rw-r--r-- | src/SpecificGen/2519_32.json | 7 | ||||
-rw-r--r-- | src/SpecificGen/25519_32.json | 7 | ||||
-rw-r--r-- | src/SpecificGen/25519_64.json | 7 | ||||
-rw-r--r-- | src/SpecificGen/41417_32.json | 7 | ||||
-rw-r--r-- | src/SpecificGen/5211_32.json | 7 | ||||
-rw-r--r-- | src/SpecificGen/GFtemplate3mod4 | 773 | ||||
-rw-r--r-- | src/SpecificGen/GFtemplate5mod8 | 782 | ||||
-rw-r--r-- | src/SpecificGen/README.md | 5 | ||||
-rwxr-xr-x | src/SpecificGen/copy_bounds.sh | 29 | ||||
-rw-r--r-- | src/SpecificGen/fill_template.py | 39 | ||||
-rw-r--r-- | src/Testbit.v | 81 | ||||
-rw-r--r-- | src/Util/AdditionChainExponentiation.v | 6 | ||||
-rw-r--r-- | src/Util/CaseUtil.v | 18 | ||||
-rw-r--r-- | src/Util/IterAssocOp.v | 8 | ||||
-rw-r--r-- | src/Util/ListUtil.v | 42 | ||||
-rw-r--r-- | src/Util/NumTheoryUtil.v | 4 | ||||
-rw-r--r-- | src/Util/ZUtil.v | 1 | ||||
-rw-r--r-- | synthesis-parameters.txt | 53 |
279 files changed, 2018 insertions, 17770 deletions
@@ -1,6 +1,6 @@ [![Build Status](https://api.travis-ci.org/mit-plv/fiat-crypto.png?branch=master)](https://travis-ci.org/mit-plv/fiat-crypto) -Fiat-Crypto: Synthesizing Correct-by-Construction Assembly for Cryptographic Primitives +Fiat-Crypto: Synthesizing Correct-by-Construction Code for Cryptographic Primitives ----- NOTE: The github.com repo is only intermittently synced with diff --git a/_CoqProject b/_CoqProject index 7c9bb012c..be303fe3f 100644 --- a/_CoqProject +++ b/_CoqProject @@ -2,255 +2,211 @@ -R Bedrock Bedrock Bedrock/Nomega.v Bedrock/Word.v -src/Algebra.v -src/BaseSystem.v -src/BaseSystemProofs.v -src/EdDSARepChange.v -src/Karatsuba.v -src/MontgomeryCurve.v -src/MontgomeryCurveTheorems.v -src/MontgomeryX.v -src/MontgomeryXProofs.v -src/MxDHRepChange.v -src/NewBaseSystem.v -src/SaturatedBaseSystem.v -src/Testbit.v src/Algebra/Field.v src/Algebra/Field_test.v src/Algebra/Group.v +src/Algebra/Hierarchy.v src/Algebra/IntegralDomain.v src/Algebra/Monoid.v +src/Algebra/Nsatz.v src/Algebra/Ring.v src/Algebra/ScalarMult.v -src/Assembly/Bounds.v -src/Assembly/Compile.v -src/Assembly/Conversions.v -src/Assembly/Evaluables.v -src/Assembly/GF25519.v -src/Assembly/HL.v -src/Assembly/LL.v -src/Assembly/PhoasCommon.v -src/Assembly/Pipeline.v -src/Assembly/Qhasm.v -src/Assembly/QhasmCommon.v -src/Assembly/QhasmEvalCommon.v -src/Assembly/QhasmUtil.v -src/Assembly/State.v -src/Assembly/StringConversion.v -src/Assembly/WordizeUtil.v -src/BoundedArithmetic/ArchitectureToZLike.v -src/BoundedArithmetic/ArchitectureToZLikeProofs.v -src/BoundedArithmetic/Eta.v -src/BoundedArithmetic/Interface.v -src/BoundedArithmetic/InterfaceProofs.v -src/BoundedArithmetic/StripCF.v -src/BoundedArithmetic/X86ToZLike.v -src/BoundedArithmetic/X86ToZLikeProofs.v -src/BoundedArithmetic/Double/Core.v -src/BoundedArithmetic/Double/Proofs/BitwiseOr.v -src/BoundedArithmetic/Double/Proofs/Decode.v -src/BoundedArithmetic/Double/Proofs/LoadImmediate.v -src/BoundedArithmetic/Double/Proofs/Multiply.v -src/BoundedArithmetic/Double/Proofs/RippleCarryAddSub.v -src/BoundedArithmetic/Double/Proofs/SelectConditional.v -src/BoundedArithmetic/Double/Proofs/ShiftLeft.v -src/BoundedArithmetic/Double/Proofs/ShiftLeftRightTactic.v -src/BoundedArithmetic/Double/Proofs/ShiftRight.v -src/BoundedArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v -src/BoundedArithmetic/Double/Proofs/SpreadLeftImmediate.v -src/BoundedArithmetic/Double/Repeated/Core.v -src/BoundedArithmetic/Double/Repeated/Proofs/BitwiseOr.v -src/BoundedArithmetic/Double/Repeated/Proofs/Decode.v -src/BoundedArithmetic/Double/Repeated/Proofs/LoadImmediate.v -src/BoundedArithmetic/Double/Repeated/Proofs/Multiply.v -src/BoundedArithmetic/Double/Repeated/Proofs/RippleCarryAddSub.v -src/BoundedArithmetic/Double/Repeated/Proofs/SelectConditional.v -src/BoundedArithmetic/Double/Repeated/Proofs/ShiftLeftRight.v -src/BoundedArithmetic/Double/Repeated/Proofs/ShiftRightDoubleWordImmediate.v -src/CompleteEdwardsCurve/CompleteEdwardsCurveTheorems.v -src/CompleteEdwardsCurve/EdwardsMontgomery.v -src/CompleteEdwardsCurve/ExtendedCoordinates.v -src/CompleteEdwardsCurve/Pre.v -src/Encoding/EncodingTheorems.v -src/Encoding/ModularWordEncodingPre.v -src/Encoding/ModularWordEncodingTheorems.v -src/Experiments/ExtrHaskellNats.v -src/Experiments/GenericFieldPow.v -src/ModularArithmetic/Conversion.v -src/ModularArithmetic/ExtPow2BaseMulProofs.v -src/ModularArithmetic/ExtendedBaseVector.v -src/ModularArithmetic/ModularArithmeticTheorems.v -src/ModularArithmetic/ModularBaseSystem.v -src/ModularArithmetic/ModularBaseSystemList.v -src/ModularArithmetic/ModularBaseSystemListProofs.v -src/ModularArithmetic/ModularBaseSystemListZOperations.v -src/ModularArithmetic/ModularBaseSystemListZOperationsProofs.v -src/ModularArithmetic/ModularBaseSystemOpt.v -src/ModularArithmetic/ModularBaseSystemProofs.v -src/ModularArithmetic/ModularBaseSystemWord.v -src/ModularArithmetic/Pow2Base.v -src/ModularArithmetic/Pow2BaseProofs.v -src/ModularArithmetic/Pre.v -src/ModularArithmetic/PrimeFieldTheorems.v -src/ModularArithmetic/PseudoMersenneBaseParamProofs.v -src/ModularArithmetic/PseudoMersenneBaseParams.v -src/ModularArithmetic/ZBounded.v -src/ModularArithmetic/ZBoundedZ.v -src/ModularArithmetic/BarrettReduction/Z.v -src/ModularArithmetic/BarrettReduction/ZBounded.v -src/ModularArithmetic/BarrettReduction/ZGeneralized.v -src/ModularArithmetic/BarrettReduction/ZHandbook.v -src/ModularArithmetic/Montgomery/Z.v -src/ModularArithmetic/Montgomery/ZBounded.v -src/ModularArithmetic/Montgomery/ZProofs.v -src/Reflection/BoundByCast.v -src/Reflection/BoundByCastInterp.v -src/Reflection/BoundByCastWf.v -src/Reflection/CommonSubexpressionElimination.v -src/Reflection/Conversion.v -src/Reflection/CountLets.v -src/Reflection/Equality.v -src/Reflection/Eta.v -src/Reflection/EtaInterp.v -src/Reflection/EtaWf.v -src/Reflection/ExprInversion.v -src/Reflection/FilterLive.v -src/Reflection/FoldTypes.v -src/Reflection/Inline.v -src/Reflection/InlineCast.v -src/Reflection/InlineCastInterp.v -src/Reflection/InlineCastWf.v -src/Reflection/InlineInterp.v -src/Reflection/InlineWf.v -src/Reflection/InputSyntax.v -src/Reflection/InterpByIso.v -src/Reflection/InterpByIsoProofs.v -src/Reflection/InterpProofs.v -src/Reflection/InterpWf.v -src/Reflection/InterpWfRel.v -src/Reflection/Linearize.v -src/Reflection/LinearizeInterp.v -src/Reflection/LinearizeWf.v -src/Reflection/Map.v -src/Reflection/MapCast.v -src/Reflection/MapCastByDeBruijn.v -src/Reflection/MapCastByDeBruijnInterp.v -src/Reflection/MapCastByDeBruijnWf.v -src/Reflection/MapCastInterp.v -src/Reflection/MapCastWf.v -src/Reflection/MultiSizeTest.v -src/Reflection/MultiSizeTest2.v -src/Reflection/Reify.v -src/Reflection/Relations.v -src/Reflection/RenameBinders.v -src/Reflection/Rewriter.v -src/Reflection/RewriterInterp.v -src/Reflection/RewriterWf.v -src/Reflection/SmartBound.v -src/Reflection/SmartBoundInterp.v -src/Reflection/SmartBoundWf.v -src/Reflection/SmartCast.v -src/Reflection/SmartCastInterp.v -src/Reflection/SmartCastWf.v -src/Reflection/SmartMap.v -src/Reflection/Syntax.v -src/Reflection/TestCase.v -src/Reflection/Tuple.v -src/Reflection/TypeInversion.v -src/Reflection/TypeUtil.v -src/Reflection/Wf.v -src/Reflection/WfInversion.v -src/Reflection/WfProofs.v -src/Reflection/WfReflective.v -src/Reflection/WfReflectiveGen.v -src/Reflection/Named/Compile.v -src/Reflection/Named/CompileInterp.v -src/Reflection/Named/CompileProperties.v -src/Reflection/Named/CompileWf.v -src/Reflection/Named/ContextDefinitions.v -src/Reflection/Named/ContextOn.v -src/Reflection/Named/ContextProperties.v -src/Reflection/Named/DeadCodeElimination.v -src/Reflection/Named/EstablishLiveness.v -src/Reflection/Named/FMapContext.v -src/Reflection/Named/IdContext.v -src/Reflection/Named/InterpretToPHOAS.v -src/Reflection/Named/InterpretToPHOASInterp.v -src/Reflection/Named/InterpretToPHOASWf.v -src/Reflection/Named/MapCast.v -src/Reflection/Named/MapCastInterp.v -src/Reflection/Named/MapCastWf.v -src/Reflection/Named/NameUtil.v -src/Reflection/Named/NameUtilProperties.v -src/Reflection/Named/PositiveContext.v -src/Reflection/Named/RegisterAssign.v -src/Reflection/Named/SmartMap.v -src/Reflection/Named/Syntax.v -src/Reflection/Named/Wf.v -src/Reflection/Named/WfInterp.v -src/Reflection/Named/ContextProperties/NameUtil.v -src/Reflection/Named/ContextProperties/SmartMap.v -src/Reflection/Named/ContextProperties/Tactics.v -src/Reflection/Named/PositiveContext/Defaults.v -src/Reflection/Named/PositiveContext/DefaultsProperties.v -src/Reflection/Z/ArithmeticSimplifier.v -src/Reflection/Z/ArithmeticSimplifierInterp.v -src/Reflection/Z/ArithmeticSimplifierUtil.v -src/Reflection/Z/ArithmeticSimplifierWf.v -src/Reflection/Z/BinaryNotationConstants.v -src/Reflection/Z/CNotations.v -src/Reflection/Z/FoldTypes.v -src/Reflection/Z/HexNotationConstants.v -src/Reflection/Z/Inline.v -src/Reflection/Z/InlineInterp.v -src/Reflection/Z/InlineWf.v -src/Reflection/Z/JavaNotations.v -src/Reflection/Z/MapCastByDeBruijn.v -src/Reflection/Z/MapCastByDeBruijnInterp.v -src/Reflection/Z/MapCastByDeBruijnWf.v -src/Reflection/Z/OpInversion.v -src/Reflection/Z/Reify.v -src/Reflection/Z/Syntax.v -src/Reflection/Z/Bounds/Interpretation.v -src/Reflection/Z/Bounds/InterpretationLemmas.v -src/Reflection/Z/Bounds/MapCastByDeBruijn.v -src/Reflection/Z/Bounds/MapCastByDeBruijnInterp.v -src/Reflection/Z/Bounds/MapCastByDeBruijnWf.v -src/Reflection/Z/Bounds/Pipeline.v -src/Reflection/Z/Bounds/Relax.v -src/Reflection/Z/Bounds/Pipeline/Definition.v -src/Reflection/Z/Bounds/Pipeline/Glue.v -src/Reflection/Z/Bounds/Pipeline/OutputType.v -src/Reflection/Z/Bounds/Pipeline/ReflectiveTactics.v -src/Reflection/Z/Syntax/Equality.v -src/Reflection/Z/Syntax/Util.v +src/Arithmetic/Core.v +src/Arithmetic/Karatsuba.v +src/Arithmetic/ModularArithmeticPre.v +src/Arithmetic/ModularArithmeticTheorems.v +src/Arithmetic/PrimeFieldTheorems.v +src/Arithmetic/Saturated.v +src/Arithmetic/BarrettReduction/Generalized.v +src/Arithmetic/BarrettReduction/HAC.v +src/Arithmetic/BarrettReduction/Wikipedia.v +src/Arithmetic/MontgomeryReduction/Definition.v +src/Arithmetic/MontgomeryReduction/Proofs.v +src/Compilers/BoundByCast.v +src/Compilers/BoundByCastInterp.v +src/Compilers/BoundByCastWf.v +src/Compilers/CommonSubexpressionElimination.v +src/Compilers/Conversion.v +src/Compilers/CountLets.v +src/Compilers/Equality.v +src/Compilers/Eta.v +src/Compilers/EtaInterp.v +src/Compilers/EtaWf.v +src/Compilers/ExprInversion.v +src/Compilers/FilterLive.v +src/Compilers/FoldTypes.v +src/Compilers/Inline.v +src/Compilers/InlineCast.v +src/Compilers/InlineCastInterp.v +src/Compilers/InlineCastWf.v +src/Compilers/InlineInterp.v +src/Compilers/InlineWf.v +src/Compilers/InputSyntax.v +src/Compilers/InterpByIso.v +src/Compilers/InterpByIsoProofs.v +src/Compilers/InterpProofs.v +src/Compilers/InterpWf.v +src/Compilers/InterpWfRel.v +src/Compilers/Linearize.v +src/Compilers/LinearizeInterp.v +src/Compilers/LinearizeWf.v +src/Compilers/Map.v +src/Compilers/MapCast.v +src/Compilers/MapCastByDeBruijn.v +src/Compilers/MapCastByDeBruijnInterp.v +src/Compilers/MapCastByDeBruijnWf.v +src/Compilers/MapCastInterp.v +src/Compilers/MapCastWf.v +src/Compilers/MultiSizeTest.v +src/Compilers/MultiSizeTest2.v +src/Compilers/Reify.v +src/Compilers/Relations.v +src/Compilers/RenameBinders.v +src/Compilers/Rewriter.v +src/Compilers/RewriterInterp.v +src/Compilers/RewriterWf.v +src/Compilers/SmartBound.v +src/Compilers/SmartBoundInterp.v +src/Compilers/SmartBoundWf.v +src/Compilers/SmartCast.v +src/Compilers/SmartCastInterp.v +src/Compilers/SmartCastWf.v +src/Compilers/SmartMap.v +src/Compilers/Syntax.v +src/Compilers/TestCase.v +src/Compilers/TestCase.v +src/Compilers/TestCase.v +src/Compilers/Tuple.v +src/Compilers/TypeInversion.v +src/Compilers/TypeUtil.v +src/Compilers/Wf.v +src/Compilers/WfInversion.v +src/Compilers/WfProofs.v +src/Compilers/WfReflective.v +src/Compilers/WfReflectiveGen.v +src/Compilers/Named/Compile.v +src/Compilers/Named/CompileInterp.v +src/Compilers/Named/CompileProperties.v +src/Compilers/Named/CompileWf.v +src/Compilers/Named/ContextDefinitions.v +src/Compilers/Named/ContextOn.v +src/Compilers/Named/ContextProperties.v +src/Compilers/Named/DeadCodeElimination.v +src/Compilers/Named/EstablishLiveness.v +src/Compilers/Named/FMapContext.v +src/Compilers/Named/IdContext.v +src/Compilers/Named/InterpretToPHOAS.v +src/Compilers/Named/InterpretToPHOASInterp.v +src/Compilers/Named/InterpretToPHOASWf.v +src/Compilers/Named/MapCast.v +src/Compilers/Named/MapCastInterp.v +src/Compilers/Named/MapCastWf.v +src/Compilers/Named/NameUtil.v +src/Compilers/Named/NameUtilProperties.v +src/Compilers/Named/PositiveContext.v +src/Compilers/Named/RegisterAssign.v +src/Compilers/Named/SmartMap.v +src/Compilers/Named/Syntax.v +src/Compilers/Named/Wf.v +src/Compilers/Named/WfInterp.v +src/Compilers/Named/ContextProperties/NameUtil.v +src/Compilers/Named/ContextProperties/SmartMap.v +src/Compilers/Named/ContextProperties/Tactics.v +src/Compilers/Named/PositiveContext/Defaults.v +src/Compilers/Named/PositiveContext/DefaultsProperties.v +src/Compilers/Z/ArithmeticSimplifier.v +src/Compilers/Z/ArithmeticSimplifierInterp.v +src/Compilers/Z/ArithmeticSimplifierUtil.v +src/Compilers/Z/ArithmeticSimplifierWf.v +src/Compilers/Z/BinaryNotationConstants.v +src/Compilers/Z/CNotations.v +src/Compilers/Z/FoldTypes.v +src/Compilers/Z/HexNotationConstants.v +src/Compilers/Z/Inline.v +src/Compilers/Z/InlineInterp.v +src/Compilers/Z/InlineWf.v +src/Compilers/Z/JavaNotations.v +src/Compilers/Z/MapCastByDeBruijn.v +src/Compilers/Z/MapCastByDeBruijnInterp.v +src/Compilers/Z/MapCastByDeBruijnWf.v +src/Compilers/Z/OpInversion.v +src/Compilers/Z/Reify.v +src/Compilers/Z/Syntax.v +src/Compilers/Z/Bounds/Interpretation.v +src/Compilers/Z/Bounds/InterpretationLemmas.v +src/Compilers/Z/Bounds/MapCastByDeBruijn.v +src/Compilers/Z/Bounds/MapCastByDeBruijnInterp.v +src/Compilers/Z/Bounds/MapCastByDeBruijnWf.v +src/Compilers/Z/Bounds/Pipeline.v +src/Compilers/Z/Bounds/Relax.v +src/Compilers/Z/Bounds/Pipeline/Definition.v +src/Compilers/Z/Bounds/Pipeline/Glue.v +src/Compilers/Z/Bounds/Pipeline/OutputType.v +src/Compilers/Z/Bounds/Pipeline/ReflectiveTactics.v +src/Compilers/Z/Syntax/Equality.v +src/Compilers/Z/Syntax/Util.v +src/Curves/Edwards/AffineProofs.v +src/Curves/Edwards/Montgomery.v +src/Curves/Edwards/Pre.v +src/Curves/Edwards/XYZT.v +src/Curves/Montgomery/Affine.v +src/Curves/Montgomery/AffineProofs.v +src/Curves/Montgomery/XZ.v +src/Curves/Montgomery/XZProofs.v +src/Curves/Weierstrass/Affine.v +src/Curves/Weierstrass/AffineProofs.v +src/Curves/Weierstrass/Pre.v +src/Curves/Weierstrass/Projective.v +src/LegacyArithmetic/ArchitectureToZLike.v +src/LegacyArithmetic/ArchitectureToZLikeProofs.v +src/LegacyArithmetic/BarretReduction.v +src/LegacyArithmetic/BarretReduction.v +src/LegacyArithmetic/BarretReduction.v +src/LegacyArithmetic/BaseSystem.v +src/LegacyArithmetic/BaseSystemProofs.v +src/LegacyArithmetic/Interface.v +src/LegacyArithmetic/InterfaceProofs.v +src/LegacyArithmetic/MontgomeryReduction.v +src/LegacyArithmetic/MontgomeryReduction.v +src/LegacyArithmetic/MontgomeryReduction.v +src/LegacyArithmetic/Pow2Base.v +src/LegacyArithmetic/Pow2BaseProofs.v +src/LegacyArithmetic/VerdiTactics.v +src/LegacyArithmetic/ZBounded.v +src/LegacyArithmetic/ZBoundedZ.v +src/LegacyArithmetic/Double/Core.v +src/LegacyArithmetic/Double/Proofs/BitwiseOr.v +src/LegacyArithmetic/Double/Proofs/Decode.v +src/LegacyArithmetic/Double/Proofs/LoadImmediate.v +src/LegacyArithmetic/Double/Proofs/Multiply.v +src/LegacyArithmetic/Double/Proofs/RippleCarryAddSub.v +src/LegacyArithmetic/Double/Proofs/SelectConditional.v +src/LegacyArithmetic/Double/Proofs/ShiftLeft.v +src/LegacyArithmetic/Double/Proofs/ShiftLeftRightTactic.v +src/LegacyArithmetic/Double/Proofs/ShiftRight.v +src/LegacyArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v +src/LegacyArithmetic/Double/Proofs/SpreadLeftImmediate.v +src/Primitives/EdDSARepChange.v +src/Primitives/MxDHRepChange.v src/Spec/CompleteEdwardsCurve.v src/Spec/Ed25519.v src/Spec/EdDSA.v -src/Spec/Encoding.v src/Spec/ModularArithmetic.v -src/Spec/ModularWordEncoding.v src/Spec/MontgomeryCurve.v src/Spec/MxDH.v src/Spec/WeierstrassCurve.v -src/Specific/GF1305.v -src/Specific/GF25519.v +src/Spec/Test/X25519.v +src/Specific/ArithmeticSynthesisTest.v src/Specific/IntegrationTestMul.v src/Specific/IntegrationTestSub.v -src/Specific/NewBaseSystemTest.v -src/Specific/SC25519.v src/Specific/FancyMachine256/Barrett.v src/Specific/FancyMachine256/Core.v src/Specific/FancyMachine256/Montgomery.v -src/Tactics/VerdiTactics.v -src/Tactics/Algebra_syntax/Nsatz.v -src/Test/Curve25519SpecTestVectors.v src/Util/AdditionChainExponentiation.v src/Util/AutoRewrite.v src/Util/Bool.v src/Util/BoundedWord.v src/Util/CPSUtil.v -src/Util/CaseUtil.v src/Util/ChangeInAll.v src/Util/Curry.v src/Util/Decidable.v @@ -328,7 +284,3 @@ src/Util/Tactics/TransparentAssert.v src/Util/Tactics/UnifyAbstractReflexivity.v src/Util/Tactics/UniquePose.v src/Util/Tactics/VM.v -src/WeierstrassCurve/Definitions.v -src/WeierstrassCurve/Pre.v -src/WeierstrassCurve/Projective.v -src/WeierstrassCurve/WeierstrassCurveTheorems.v diff --git a/cleanup.md b/cleanup.md deleted file mode 100644 index b26db1cab..000000000 --- a/cleanup.md +++ /dev/null @@ -1,139 +0,0 @@ -# Fiat-Crypto Cleanup - -The primary objectives here are to reduce the substantial amount of code-bloat -that fiat-crypto has accrued, and to use the lessons we've learned so far to -rewrite some parts of the library in ways that will cause us less future pain. -These changes will both make our own lives easier and make the library more -approachable to others. - -## Overview - -- Field Arithmetic Implementation (Base System): Rewrite using a new, less awkward representation (in progress). -- Elliptic Curves : Use dependently-typed division and enhance super-`nsatz` -- Spec : Remove the stuff that does not belong in spec. -- Algebra/Prime Field libraries : Possibly introduce more bundling. -- Experiments/Ed25519 : Move the "spaghetti code" to the various parts of the library where it belongs. -- Util : Keep pretty much as-is, even if many lemmas are not used after rewrites. -- Compilery Bits : Reorganize and spend some time thinking about design. -- PointEncoding : Significant refactor, make interfaces line up and remove duplicated or redundant code. -- Specific/SpecificGen : Make a more general and nicely-presented catalog of examples for people to look at and be impressed by. - -## Field Arithmetic Implementation - -Originally, we represented field-element bignums using two lists, one -representing the constant weights (e.g. `[1, 2^26, 2^51,...] or [26, 25, -26,...]) and one with the variable runtime values. The new representation -couples the weights and the runtime values, (e.g `[(1, x0), (2^51, x1), (2^51, -x2), (2^26, x1)]`). - -This approach has several advantages, but the most important of these is that -the basic arithmetic operations have gotten much simpler. Here is the old -version of `mul`: - -``` - (* mul' is multiplication with the SECOND ARGUMENT REVERSED and OUTPUT REVERSED *) - Fixpoint mul_bi' (i:nat) (vsr:digits) := - match vsr with - | v::vsr' => v * crosscoef i (length vsr') :: mul_bi' i vsr' - | nil => nil - end. - Definition mul_bi (i:nat) (vs:digits) : digits := - zeros i ++ rev (mul_bi' i (rev vs)). - - (* mul' is multiplication with the FIRST ARGUMENT REVERSED *) - Fixpoint mul' (usr vs:digits) : digits := - match usr with - | u::usr' => - mul_each u (mul_bi (length usr') vs) .+ mul' usr' vs - | _ => nil - end. - Definition mul us := mul' (rev us). -``` - -This version doesn't even include a few hundred lines of proof needed to prove -that `mul` is correct or 150 lines of extra work in ModularBaseSystemOpt.v to -mark runtime operations. Here is the new `mul` and its proof: - -``` - Definition mul (p q:list limb) : list limb := - List.flat_map (fun t => List.map (fun t' => (fst t * fst t', (snd t * snd t')%RT)) q) p. - - Lemma eval_map_mul a x q : eval (List.map (fun t => (a * fst t, x * snd t)) q) = a * x * eval q. - Proof. induction q; simpl List.map; autorewrite with push_eval cancel_pair; nsatz. Qed. - - Lemma eval_mul p q : eval (mul p q) = eval p * eval q. - Proof. induction p; simpl mul; autorewrite with push_eval cancel_pair; try nsatz. Qed. -``` - -The "RT" notation marks runtime operations, so there's no need for an extra step. - -Besides shaving some orders of magnitude off of implementation effort, size, -and compile time, we also no longer need to carry around preconditions that -discuss the correspondence between the weights list and the runtime list (for -instance, that they have the same length). - -## Elliptic Curves - -1. Division should be modified to use a dependent type for the denominator, - which carries a proof that the denominator is nonzero. This removes some -ugliness (for instance, with proving homomorphisms, where it is necessary to -show that both divisions do similar things for all possible inputs. Division by -zero is undefined, so if zero is a possible input, this is challenging.) Also, -simply making it impossible to divide by zero more accurately matches how we -think of division. -2. Improve super-`nsatz` as described in Andres and Jason's Coq enhancements - proposal. - -## Spec - -There's a bunch of clutter scattered across the files that either doesn't -belong in spec or could be expressed better. If someone went through all the -files and thought carefully about them, it would be time well spent. - -Additionally, the things in Encoding.v and ModularWordEncoding.v will likely go -away during the PointEncoding cleanup. - -## Algebra/Prime Field Libraries - -Mostly leave as-is, these are great examples of parts of fiat-crypto that are -currently nice, probably because they are fairly well-defined sections that -were designed all at once with the big picture in mind, instead of being -incrementally assembled and revised. We might want to consider bundling some of -the algebraic structures. - -## Experiments/Ed25519.v - -This file was assembled as we scrambled to meet the PLDI deadline and contains -mostly "glue" that makes different interfaces across fiat-crypto actually line -up with each other. We should have someone go through it and relocate that sort -of code to where it actually belongs, and/or make the necessary changes to -interfaces. - -## Util - -We should keep the Util files (especially the big ones like ZUtil and ListUtil) -mostly as-is, although once the old BaseSystem goes away most of the lemmas -won't be used by fiat-crypto. If compile time becomes a problem, we might want -to factor out the unused lemmas and store them separately, but we should not -get rid of anything that could be a candidate for Coq's standard library. - -## Compilery Bits - -We should reorganize the compilery files (meaning bounds-checking, PHOAS, etc.) -to be more comprehensible to people who are not Jason. We should also remove -unnecessary code (are we ever going to use the code under the Assembly -directory?) and do another "think hard about whether these pieces are designed -well" session. - -## PointEncoding - -These files are a mix of very very old code and code that was thrown in to make -things work right before the PLDI deadline. It just needs to have redundant -code removed and proof structures improved. - - -## Specific/SpecificGen - -As we are transitioning from this being a research prototype to it being a Real -Thing People Might Look At, we might want to consider making a more presentable -and cohesive catalog of examples than we currently have. diff --git a/src/Algebra/Field.v b/src/Algebra/Field.v index e71b24018..7270f6018 100644 --- a/src/Algebra/Field.v +++ b/src/Algebra/Field.v @@ -2,7 +2,7 @@ Require Import Crypto.Util.Relations Crypto.Util.Notations. Require Import Crypto.Util.Tactics.UniquePose. Require Import Crypto.Util.Tactics.DebugPrint. Require Import Coq.Classes.RelationClasses Coq.Classes.Morphisms. -Require Import Crypto.Algebra Crypto.Algebra.Ring Crypto.Algebra.IntegralDomain. +Require Import Crypto.Algebra.Hierarchy Crypto.Algebra.Ring Crypto.Algebra.IntegralDomain. Require Coq.setoid_ring.Field_theory. Section Field. @@ -215,14 +215,14 @@ End Homomorphism_rev. Ltac guess_field := match goal with - | |- ?eq _ _ => constr:(_:Algebra.field (eq:=eq)) - | |- not (?eq _ _) => constr:(_:Algebra.field (eq:=eq)) - | [H: ?eq _ _ |- _ ] => constr:(_:Algebra.field (eq:=eq)) - | [H: not (?eq _ _) |- _] => constr:(_:Algebra.field (eq:=eq)) + | |- ?eq _ _ => constr:(_:Hierarchy.field (eq:=eq)) + | |- not (?eq _ _) => constr:(_:Hierarchy.field (eq:=eq)) + | [H: ?eq _ _ |- _ ] => constr:(_:Hierarchy.field (eq:=eq)) + | [H: not (?eq _ _) |- _] => constr:(_:Hierarchy.field (eq:=eq)) end. Ltac goal_to_field_equality fld := - let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in + let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in match goal with | [ |- eq _ _] => idtac | [ |- not (eq ?x ?y) ] => apply not_exfalso; intro; goal_to_field_equality fld @@ -234,10 +234,10 @@ Ltac goal_to_field_equality fld := end. Ltac inequalities_to_inverse_equations fld := - let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in - let zero := match type of fld with Algebra.field(zero:=?zero) => zero end in - let div := match type of fld with Algebra.field(div:=?div) => div end in - let sub := match type of fld with Algebra.field(sub:=?sub) => sub end in + let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in + let zero := match type of fld with Hierarchy.field(zero:=?zero) => zero end in + let div := match type of fld with Hierarchy.field(div:=?div) => div end in + let sub := match type of fld with Hierarchy.field(sub:=?sub) => sub end in repeat match goal with | [H: not (eq _ _) |- _ ] => lazymatch type of H with @@ -258,8 +258,8 @@ Ltac unique_pose_implication pf := end. Ltac inverses_to_conditional_equations fld := - let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in - let inv := match type of fld with Algebra.field(inv:=?inv) => inv end in + let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in + let inv := match type of fld with Hierarchy.field(inv:=?inv) => inv end in repeat match goal with | |- context[inv ?d] => unique_pose_implication constr:(right_multiplicative_inverse(H:=fld) d) @@ -268,15 +268,15 @@ Ltac inverses_to_conditional_equations fld := end. Ltac clear_hypotheses_with_nonzero_requirements fld := - let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in - let zero := match type of fld with Algebra.field(zero:=?zero) => zero end in + let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in + let zero := match type of fld with Hierarchy.field(zero:=?zero) => zero end in repeat match goal with [H: not (eq _ zero) -> _ |- _ ] => clear H end. Ltac forward_nonzero fld solver_tac := - let eq := match type of fld with Algebra.field(eq:=?eq) => eq end in - let zero := match type of fld with Algebra.field(zero:=?zero) => zero end in + let eq := match type of fld with Hierarchy.field(eq:=?eq) => eq end in + let zero := match type of fld with Hierarchy.field(zero:=?zero) => zero end in repeat match goal with | [H: not (eq ?x zero) -> _ |- _ ] => let H' := fresh in diff --git a/src/Algebra/Field_test.v b/src/Algebra/Field_test.v index 0743729c2..59ca72c6b 100644 --- a/src/Algebra/Field_test.v +++ b/src/Algebra/Field_test.v @@ -4,7 +4,7 @@ Require Import Crypto.Algebra.Ring Crypto.Algebra.Field. Module _fsatz_test. Section _test. Context {F eq zero one opp add sub mul inv div} - {fld:@Algebra.field F eq zero one opp add sub mul inv div} + {fld:@Hierarchy.field F eq zero one opp add sub mul inv div} {eq_dec:DecidableRel eq}. Local Infix "=" := eq. Local Notation "a <> b" := (not (a = b)). Local Infix "=" := eq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. diff --git a/src/Algebra/Group.v b/src/Algebra/Group.v index 64e378281..8ce3e2a91 100644 --- a/src/Algebra/Group.v +++ b/src/Algebra/Group.v @@ -1,5 +1,5 @@ Require Import Coq.Classes.Morphisms Crypto.Util.Relations (*Crypto.Util.Tactics*). -Require Import Crypto.Algebra Crypto.Algebra.Monoid Crypto.Algebra.ScalarMult. +Require Import Crypto.Algebra.Hierarchy Crypto.Algebra.Monoid Crypto.Algebra.ScalarMult. Section BasicProperties. Context {T eq op id inv} `{@group T eq op id inv}. diff --git a/src/Algebra.v b/src/Algebra/Hierarchy.v index 342e9feaa..342e9feaa 100644 --- a/src/Algebra.v +++ b/src/Algebra/Hierarchy.v diff --git a/src/Algebra/IntegralDomain.v b/src/Algebra/IntegralDomain.v index 4ab50c6e3..c52b4ce87 100644 --- a/src/Algebra/IntegralDomain.v +++ b/src/Algebra/IntegralDomain.v @@ -1,7 +1,7 @@ Require Coq.setoid_ring.Integral_domain. -Require Crypto.Tactics.Algebra_syntax.Nsatz. +Require Crypto.Algebra.Nsatz. Require Import Crypto.Util.Factorize. -Require Import Crypto.Algebra Crypto.Algebra.Ring. +Require Import Crypto.Algebra.Hierarchy Crypto.Algebra.Ring. Require Import Crypto.Util.Tactics.RewriteHyp. Require Import Crypto.Util.Tactics.BreakMatch. @@ -23,8 +23,8 @@ Module IntegralDomain. Section ReflectiveNsatzSideConditionProver. Import BinInt BinNat BinPos. Context {R eq zero one opp add sub mul} - {ring:@Algebra.ring R eq zero one opp add sub mul} - {zpzf:@Algebra.is_zero_product_zero_factor R eq zero mul}. + {ring:@Hierarchy.ring R eq zero one opp add sub mul} + {zpzf:@Hierarchy.is_zero_product_zero_factor R eq zero mul}. Local Infix "=" := eq. Local Notation "a <> b" := (not (a = b)). Local Infix "=" := eq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. Local Infix "+" := add. Local Infix "-" := sub. Local Infix "*" := mul. @@ -198,4 +198,4 @@ Ltac dropRingSyntax := Ncring.opp_notation Ncring.eq_notation ] in *. -Ltac nsatz := Algebra_syntax.Nsatz.nsatz; dropRingSyntax. +Ltac nsatz := Algebra.Nsatz.nsatz; dropRingSyntax. diff --git a/src/Algebra/Monoid.v b/src/Algebra/Monoid.v index bd15290c7..470e8df40 100644 --- a/src/Algebra/Monoid.v +++ b/src/Algebra/Monoid.v @@ -1,6 +1,6 @@ Require Import Coq.Classes.Morphisms. Require Import Crypto.Util.Tactics.RewriteHyp. -Require Import Crypto.Algebra. +Require Import Crypto.Algebra.Hierarchy. Section Monoid. Context {T eq op id} {monoid:@monoid T eq op id}. diff --git a/src/Tactics/Algebra_syntax/Nsatz.v b/src/Algebra/Nsatz.v index e219bc579..2a65e7d82 100644 --- a/src/Tactics/Algebra_syntax/Nsatz.v +++ b/src/Algebra/Nsatz.v @@ -1,4 +1,7 @@ -(*** Tactics for manipulating polynomial equations *) +(* This is a rewrite of the Ltac parts of standard library nsatz. We should + periodically check whether we still need it -- once enough bugs get fixed + in mailine, we hope to drop this implementation *) + Require Coq.nsatz.Nsatz. Require Import Coq.Lists.List. diff --git a/src/Algebra/Ring.v b/src/Algebra/Ring.v index cff27bdb3..406706988 100644 --- a/src/Algebra/Ring.v +++ b/src/Algebra/Ring.v @@ -4,7 +4,7 @@ Require Import Coq.Classes.Morphisms. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.OnSubterms. Require Import Crypto.Util.Tactics.Revert. -Require Import Crypto.Algebra Crypto.Algebra.Group Crypto.Algebra.Monoid. +Require Import Crypto.Algebra.Hierarchy Crypto.Algebra.Group Crypto.Algebra.Monoid. Require Coq.ZArith.ZArith Coq.PArith.PArith. @@ -420,7 +420,7 @@ End of_Z. Definition char_ge {R eq zero one opp add} {sub:R->R->R} {mul:R->R->R} C := - @Algebra.char_ge R eq zero (fun p => (@of_Z R zero one opp add) (BinInt.Z.pos p)) C. + @Hierarchy.char_ge R eq zero (fun p => (@of_Z R zero one opp add) (BinInt.Z.pos p)) C. Existing Class char_ge. (*** Tactics for ring equations *) diff --git a/src/Algebra/ScalarMult.v b/src/Algebra/ScalarMult.v index 5c17a6bb5..f52fc93ee 100644 --- a/src/Algebra/ScalarMult.v +++ b/src/Algebra/ScalarMult.v @@ -1,5 +1,5 @@ Require Import Coq.Classes.Morphisms. -Require Import Crypto.Algebra Crypto.Algebra.Monoid. +Require Import Crypto.Algebra.Hierarchy Crypto.Algebra.Monoid. Module Import ModuloCoq8485. Import NPeano Nat. diff --git a/src/ModularArithmetic/BarrettReduction/ZGeneralized.v b/src/Arithmetic/BarrettReduction/Generalized.v index 596c8e5f9..76058463c 100644 --- a/src/ModularArithmetic/BarrettReduction/ZGeneralized.v +++ b/src/Arithmetic/BarrettReduction/Generalized.v @@ -9,7 +9,7 @@ base ([b]), exponent ([k]), and the [offset] than those given in the HAC. *) Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.Util.ZUtil Crypto.Util.Tactics.BreakMatch Crypto.Algebra. +Require Import Crypto.Util.ZUtil Crypto.Util.Tactics.BreakMatch. Local Open Scope Z_scope. diff --git a/src/ModularArithmetic/BarrettReduction/ZHandbook.v b/src/Arithmetic/BarrettReduction/HAC.v index 8962a997f..70661ee96 100644 --- a/src/ModularArithmetic/BarrettReduction/ZHandbook.v +++ b/src/Arithmetic/BarrettReduction/HAC.v @@ -9,7 +9,7 @@ have to carry around extra precision), but requires more stringint conditions on the base ([b]), exponent ([k]), and the [offset]. *) Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.Util.ZUtil Crypto.Util.Tactics.BreakMatch Crypto.Algebra. +Require Import Crypto.Util.ZUtil Crypto.Util.Tactics.BreakMatch. Local Open Scope Z_scope. diff --git a/src/ModularArithmetic/BarrettReduction/Z.v b/src/Arithmetic/BarrettReduction/Wikipedia.v index 69ce10c4b..69ce10c4b 100644 --- a/src/ModularArithmetic/BarrettReduction/Z.v +++ b/src/Arithmetic/BarrettReduction/Wikipedia.v diff --git a/src/NewBaseSystem.v b/src/Arithmetic/Core.v index 4dec23846..2613765d0 100644 --- a/src/NewBaseSystem.v +++ b/src/Arithmetic/Core.v @@ -244,12 +244,11 @@ Require Import Coq.ZArith.ZArith Coq.micromega.Psatz Coq.omega.Omega. Require Import Coq.ZArith.BinIntDef. Local Open Scope Z_scope. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Tactics.Algebra_syntax.Nsatz. +Require Import Crypto.Algebra.Nsatz. Require Import Crypto.Util.Decidable Crypto.Util.LetIn. Require Import Crypto.Util.ZUtil Crypto.Util.ListUtil Crypto.Util.Sigma. Require Import Crypto.Util.CPSUtil Crypto.Util.Prod. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. +Require Import Crypto.Arithmetic.PrimeFieldTheorems. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.UniquePose. Require Import Crypto.Util.Tactics.VM. @@ -582,7 +581,8 @@ Module B. Proof using Type*. induction i; cbv [id]; simpl place_cps; break_match; autorewrite with cancel_pair; - try find_apply_lem_hyp Z_div_exact_full_2; nsatz || auto. + try match goal with [H:_|-_] => apply Z_div_exact_full_2 in H end; + nsatz || auto. Qed. Definition from_associational_cps n (p:list limb) diff --git a/src/Karatsuba.v b/src/Arithmetic/Karatsuba.v index 8e88d64c3..0f20bb238 100644 --- a/src/Karatsuba.v +++ b/src/Arithmetic/Karatsuba.v @@ -1,5 +1,5 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.Tactics.Algebra_syntax.Nsatz. +Require Import Crypto.Algebra.Nsatz. Require Import Crypto.Util.ZUtil. Local Open Scope Z_scope. diff --git a/src/ModularArithmetic/Pre.v b/src/Arithmetic/ModularArithmeticPre.v index 7320b16bf..b27ffd16d 100644 --- a/src/ModularArithmetic/Pre.v +++ b/src/Arithmetic/ModularArithmeticPre.v @@ -1,10 +1,8 @@ Require Import Coq.ZArith.BinInt Coq.NArith.BinNat Coq.Numbers.BinNums Coq.ZArith.Zdiv Coq.ZArith.Znumtheory. Require Import Coq.Logic.Eqdep_dec. Require Import Coq.Logic.EqdepFacts. -Require Import Crypto.Tactics.VerdiTactics. Require Import Coq.omega.Omega. Require Import Crypto.Util.NumTheoryUtil. -Require Import Crypto.Tactics.VerdiTactics. Require Export Crypto.Util.FixCoqMistakes. Lemma Z_mod_mod x m : x mod m = (x mod m) mod m. @@ -19,7 +17,7 @@ Lemma exist_reduced_eq: forall (m : Z) (a b : Z), a = b -> forall pfa pfb, exist (fun z : Z => z = z mod m) b pfb. Proof. intuition; simpl in *; try congruence. - subst_max. + subst. f_equal. eapply UIP_dec, Z.eq_dec. Qed. @@ -138,4 +136,4 @@ Next Obligation. replace (Z.succ (m - 2)) with (m-1) by omega. rewrite (Zmod_small 1) by omega. apply (fermat_little m Hm a Ha). -Qed. +Qed.
\ No newline at end of file diff --git a/src/ModularArithmetic/ModularArithmeticTheorems.v b/src/Arithmetic/ModularArithmeticTheorems.v index 9cd211943..990aa9dc8 100644 --- a/src/ModularArithmetic/ModularArithmeticTheorems.v +++ b/src/Arithmetic/ModularArithmeticTheorems.v @@ -1,12 +1,12 @@ Require Import Coq.omega.Omega. Require Import Crypto.Spec.ModularArithmetic. -Require Import Crypto.ModularArithmetic.Pre. +Require Import Crypto.Arithmetic.ModularArithmeticPre. Require Import Coq.ZArith.BinInt Coq.ZArith.Zdiv Coq.ZArith.Znumtheory Coq.NArith.NArith. (* import Zdiv before Znumtheory *) Require Import Coq.Classes.Morphisms Coq.Setoids.Setoid. Require Export Coq.setoid_ring.Ring_theory Coq.setoid_ring.Ring_tac. -Require Import Crypto.Algebra Crypto.Algebra.Ring Crypto.Algebra.Field. +Require Import Crypto.Algebra.Hierarchy Crypto.Algebra.Ring Crypto.Algebra.Field. Require Import Crypto.Util.Decidable Crypto.Util.ZUtil. Require Export Crypto.Util.FixCoqMistakes. @@ -22,7 +22,7 @@ Module F. Global Instance eq_dec {m} : DecidableRel (@eq (F m)). pose proof dec_eq_Z. exact _. Defined. Global Instance commutative_ring_modulo m - : @Algebra.commutative_ring (F m) Logic.eq 0%F 1%F F.opp F.add F.sub F.mul. + : @Algebra.Hierarchy.commutative_ring (F m) Logic.eq 0%F 1%F F.opp F.add F.sub F.mul. Proof. repeat (split || intro); unwrap_F; autorewrite with zsimplify; solve [ exact _ | auto with zarith | congruence]. @@ -211,13 +211,13 @@ Module F. Proof using Type. destruct (pow_spec x) as [HO HS]; intros. destruct n; auto; unfold id. - rewrite Pre.N_pos_1plus at 1. + rewrite ModularArithmeticPre.N_pos_1plus at 1. rewrite HS. simpl. induction p using Pos.peano_ind. - - simpl. rewrite HO. apply Algebra.right_identity. + - simpl. rewrite HO. apply Algebra.Hierarchy.right_identity. - rewrite (@pow_pos_succ (F m) (@F.mul m) eq _ _ associative x). - rewrite <-IHp, Pos.pred_N_succ, Pre.N_pos_1plus, HS. + rewrite <-IHp, Pos.pred_N_succ, ModularArithmeticPre.N_pos_1plus, HS. trivial. Qed. diff --git a/src/ModularArithmetic/Montgomery/Z.v b/src/Arithmetic/MontgomeryReduction/Definition.v index 78d3c037f..78d3c037f 100644 --- a/src/ModularArithmetic/Montgomery/Z.v +++ b/src/Arithmetic/MontgomeryReduction/Definition.v diff --git a/src/ModularArithmetic/Montgomery/ZProofs.v b/src/Arithmetic/MontgomeryReduction/Proofs.v index 2d8f6155d..d5de00213 100644 --- a/src/ModularArithmetic/Montgomery/ZProofs.v +++ b/src/Arithmetic/MontgomeryReduction/Proofs.v @@ -3,7 +3,7 @@ Reduction, and Montgomery Multiplication on [Z]. We follow Wikipedia. *) Require Import Coq.ZArith.ZArith Coq.micromega.Psatz Coq.Structures.Equalities. -Require Import Crypto.ModularArithmetic.Montgomery.Z. +Require Import Crypto.Arithmetic.MontgomeryReduction.Definition. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.SimplifyRepeatedIfs. @@ -34,13 +34,13 @@ Section montgomery. Lemma to_from_montgomery_naive x : to_montgomery_naive (from_montgomery_naive x) ≡ x. Proof using R'_good. - unfold Z.to_montgomery_naive, Z.from_montgomery_naive. + unfold to_montgomery_naive, from_montgomery_naive. rewrite <- Z.mul_assoc, R'_good'. autorewrite with zsimplify; reflexivity. Qed. Lemma from_to_montgomery_naive x : from_montgomery_naive (to_montgomery_naive x) ≡ x. Proof using R'_good. - unfold Z.to_montgomery_naive, Z.from_montgomery_naive. + unfold to_montgomery_naive, from_montgomery_naive. rewrite <- Z.mul_assoc, R'_good. autorewrite with zsimplify; reflexivity. Qed. @@ -52,19 +52,19 @@ Section montgomery. Local Infix "*" := (mul_naive R') : montgomery_scope. Lemma add_correct_naive x y : from_montgomery_naive (x + y) = from_montgomery_naive x + from_montgomery_naive y. - Proof using Type. unfold Z.from_montgomery_naive, add; lia. Qed. + Proof using Type. unfold from_montgomery_naive, add; lia. Qed. Lemma add_correct_naive_to x y : to_montgomery_naive (x + y) = (to_montgomery_naive x + to_montgomery_naive y)%montgomery. - Proof using Type. unfold Z.to_montgomery_naive, add; autorewrite with push_Zmul; reflexivity. Qed. + Proof using Type. unfold to_montgomery_naive, add; autorewrite with push_Zmul; reflexivity. Qed. Lemma sub_correct_naive x y : from_montgomery_naive (x - y) = from_montgomery_naive x - from_montgomery_naive y. - Proof using Type. unfold Z.from_montgomery_naive, sub; lia. Qed. + Proof using Type. unfold from_montgomery_naive, sub; lia. Qed. Lemma sub_correct_naive_to x y : to_montgomery_naive (x - y) = (to_montgomery_naive x - to_montgomery_naive y)%montgomery. - Proof using Type. unfold Z.to_montgomery_naive, sub; autorewrite with push_Zmul; reflexivity. Qed. + Proof using Type. unfold to_montgomery_naive, sub; autorewrite with push_Zmul; reflexivity. Qed. Theorem mul_correct_naive x y : from_montgomery_naive (x * y) = from_montgomery_naive x * from_montgomery_naive y. - Proof using Type. unfold Z.from_montgomery_naive, mul_naive; lia. Qed. + Proof using Type. unfold from_montgomery_naive, mul_naive; lia. Qed. Theorem mul_correct_naive_to x y : to_montgomery_naive (x * y) ≡ (to_montgomery_naive x * to_montgomery_naive y)%montgomery. Proof using R'_good. - unfold Z.to_montgomery_naive, mul_naive. + unfold to_montgomery_naive, mul_naive. rewrite <- !Z.mul_assoc, R'_good. autorewrite with zsimplify; apply (f_equal2 Z.modulo); lia. Qed. @@ -98,7 +98,7 @@ Section montgomery. Lemma prereduce_correct : prereduce T ≡ T * R'. Proof using N'_good N'_in_range N_reasonable R'_good. transitivity ((T + m * N) * R'). - { unfold Z.prereduce. + { unfold prereduce. autorewrite with zstrip_div; push_Zmod. rewrite N'_good'_alt. autorewrite with zsimplify pull_Zmod. @@ -131,7 +131,7 @@ Section montgomery. : 0 <= N -> 0 <= T <= R * B -> 0 <= prereduce T < B + N. - Proof using N_reasonable m_small. unfold Z.prereduce; auto with zarith nia. Qed. + Proof using N_reasonable m_small. unfold prereduce; auto with zarith nia. Qed. End generic. Section N_very_small. @@ -170,7 +170,7 @@ Section montgomery. -> 0 <= reduce N R N' T < R. Proof using N_reasonable N_small_enough m_small. intro H; pose proof (prereduce_in_range_small_enough H). - unfold reduce, Z.prereduce in *; break_match; Z.ltb_to_lt; nia. + unfold reduce, prereduce in *; break_match; Z.ltb_to_lt; nia. Qed. Lemma partial_reduce_in_range_R @@ -178,7 +178,7 @@ Section montgomery. -> 0 <= partial_reduce N R N' T < R. Proof using N_reasonable N_small_enough m_small. intro H; pose proof (prereduce_in_range_small_enough H). - unfold partial_reduce, Z.prereduce in *; break_match; Z.ltb_to_lt; nia. + unfold partial_reduce, prereduce in *; break_match; Z.ltb_to_lt; nia. Qed. Lemma reduce_via_partial_in_range_R @@ -186,7 +186,7 @@ Section montgomery. -> 0 <= reduce_via_partial N R N' T < R. Proof using N_reasonable N_small_enough m_small. intro H; pose proof (prereduce_in_range_small_enough H). - unfold reduce_via_partial, partial_reduce, Z.prereduce in *; break_match; Z.ltb_to_lt; nia. + unfold reduce_via_partial, partial_reduce, prereduce in *; break_match; Z.ltb_to_lt; nia. Qed. End N_small_enough. @@ -201,7 +201,7 @@ Section montgomery. -> 0 <= reduce N R N' T < N. Proof using N_reasonable m_small. intro H; pose proof (prereduce_in_range H). - unfold reduce, Z.prereduce in *; break_match; Z.ltb_to_lt; nia. + unfold reduce, prereduce in *; break_match; Z.ltb_to_lt; nia. Qed. Lemma partial_reduce_in_range @@ -209,7 +209,7 @@ Section montgomery. -> Z.min 0 (R - N) <= partial_reduce N R N' T < 2 * N. Proof using N_reasonable m_small. intro H; pose proof (prereduce_in_range H). - unfold partial_reduce, Z.prereduce in *; break_match; Z.ltb_to_lt; + unfold partial_reduce, prereduce in *; break_match; Z.ltb_to_lt; apply Z.min_case_strong; nia. Qed. @@ -235,7 +235,7 @@ Section montgomery. assert (T + m * N < R * R -> (T + m * N) / R < R) by auto with zarith. assert (H' : (T + m * N) mod (R * R) = if R * R <=? T + m * N then T + m * N - R * R else T + m * N) by (break_match; Z.ltb_to_lt; autorewrite with zsimplify; lia). - unfold partial_reduce, partial_reduce_alt, Z.prereduce. + unfold partial_reduce, partial_reduce_alt, prereduce. rewrite H'; clear H'. simplify_repeated_ifs. set (m' := m) in *. @@ -253,7 +253,7 @@ Section montgomery. Local Notation from_montgomery := (from_montgomery N R N'). Lemma to_from_montgomery a : to_montgomery (from_montgomery a) ≡ a. Proof using N'_good N'_in_range N_reasonable R'_good. - unfold Z.to_montgomery, Z.from_montgomery. + unfold to_montgomery, from_montgomery. transitivity ((a * 1) * 1); [ | apply f_equal2; lia ]. rewrite <- !R'_good, !reduce_correct. unfold Z.equiv_modulo; push_Zmod; pull_Zmod. @@ -261,7 +261,7 @@ Section montgomery. Qed. Lemma from_to_montgomery a : from_montgomery (to_montgomery a) ≡ a. Proof using N'_good N'_in_range N_reasonable R'_good. - unfold Z.to_montgomery, Z.from_montgomery. + unfold to_montgomery, from_montgomery. rewrite !reduce_correct. transitivity (a * ((R * (R * R' mod N) * R') mod N)). { unfold Z.equiv_modulo; push_Zmod; pull_Zmod. @@ -274,12 +274,12 @@ Section montgomery. Theorem mul_correct x y : from_montgomery (x * y) ≡ from_montgomery x * from_montgomery y. Proof using N'_good N'_in_range N_reasonable R'_good. - unfold Z.from_montgomery, mul. + unfold from_montgomery, mul. rewrite !reduce_correct; apply f_equal2; lia. Qed. Theorem mul_correct_to x y : to_montgomery (x * y) ≡ (to_montgomery x * to_montgomery y)%montgomery. Proof using N'_good N'_in_range N_reasonable R'_good. - unfold Z.to_montgomery, mul. + unfold to_montgomery, mul. rewrite !reduce_correct. transitivity (x * y * R * 1 * 1 * 1); [ rewrite <- R'_good at 1 diff --git a/src/ModularArithmetic/PrimeFieldTheorems.v b/src/Arithmetic/PrimeFieldTheorems.v index eba1af740..c253752c5 100644 --- a/src/ModularArithmetic/PrimeFieldTheorems.v +++ b/src/Arithmetic/PrimeFieldTheorems.v @@ -1,10 +1,10 @@ -Require Export Crypto.Spec.ModularArithmetic Crypto.ModularArithmetic.ModularArithmeticTheorems. +Require Export Crypto.Spec.ModularArithmetic. +Require Export Crypto.Arithmetic.ModularArithmeticTheorems. Require Export Coq.setoid_ring.Ring_theory Coq.setoid_ring.Field_theory Coq.setoid_ring.Field_tac. Require Import Coq.nsatz.Nsatz. -Require Import Crypto.ModularArithmetic.Pre. +Require Import Crypto.Arithmetic.ModularArithmeticPre. Require Import Crypto.Util.NumTheoryUtil. -Require Import Crypto.Tactics.VerdiTactics. Require Import Coq.Classes.Morphisms Coq.Setoids.Setoid. Require Import Coq.ZArith.BinInt Coq.NArith.BinNat Coq.ZArith.ZArith Coq.ZArith.Znumtheory Coq.NArith.NArith. (* import Zdiv before Znumtheory *) Require Import Coq.Logic.Eqdep_dec. @@ -12,7 +12,7 @@ Require Import Crypto.Util.NumTheoryUtil Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.SpecializeBy. Require Import Crypto.Util.Decidable. Require Export Crypto.Util.FixCoqMistakes. -Require Crypto.Algebra Crypto.Algebra.Field. +Require Crypto.Algebra.Hierarchy Crypto.Algebra.Field. Existing Class prime. Local Open Scope F_scope. @@ -27,7 +27,7 @@ Module F. Lemma inv_0 : F.inv 0%F = F.of_Z q 0. Proof using Type. destruct inv_spec; auto. Qed. Lemma inv_nonzero (x:F q) : (x <> 0 -> F.inv x * x%F = 1)%F. Proof using Type*. destruct inv_spec; auto. Qed. - Global Instance field_modulo : @Algebra.field (F q) Logic.eq 0%F 1%F F.opp F.add F.sub F.mul F.inv F.div. + Global Instance field_modulo : @Algebra.Hierarchy.field (F q) Logic.eq 0%F 1%F F.opp F.add F.sub F.mul F.inv F.div. Proof using Type*. repeat match goal with | _ => solve [ solve_proper @@ -107,7 +107,7 @@ Module F. | |- _ => progress rewrite <-?Z2N.inj_0, <-?Z2N.inj_add by zero_bounds | |- _ => rewrite <-@euler_criterion by auto | |- ?x ^ (?f _) = ?a <-> ?x ^ (?f _) = ?a => do 3 f_equiv; [ ] - | |- _ => rewrite !Zmod_odd in *; repeat break_if; omega + | |- _ => rewrite !Zmod_odd in *; repeat (break_match; break_match_hyps); omega | |- _ => rewrite Z.rem_mul_r in * by omega | |- (exists x, _) <-> ?B => assert B by field; solve [intuition eauto] | |- (?x ^ Z.to_N ?a = 1) <-> _ => @@ -214,16 +214,16 @@ Module F. repeat match goal with | |- _ => progress subst | |- _ => progress rewrite ?F.pow_0_l - | |- _ => break_if - | |- (exists x, _) <-> ?B => assert B by field; solve [intuition eauto] | |- (_ <> _)%N => rewrite <-Z2N.inj_0, Z2N.inj_iff by zero_bounds | |- (?a <> 0)%Z => assert (0 < a) by zero_bounds; omega | |- _ => congruence end. + break_match; + match goal with |- _ <-> ?G => assert G by field end; intuition eauto. } { rewrite eq_b4_a2_iff by auto. rewrite !@F.pow_2_r in *. - break_if. + break_match. intuition (f_equal; eauto). split; intro A. { destruct (Field.only_two_square_roots_choice _ x (x * x) A eq_refl) as [B | B]; @@ -258,11 +258,11 @@ Module F. Definition div x y := mul (inv y) x. Lemma ring : - @Algebra.ring H eq zero one opp add sub mul + @Algebra.Hierarchy.ring H eq zero one opp add sub mul /\ @Ring.is_homomorphism (F q) Logic.eq F.one F.add F.mul H eq one add mul phi /\ @Ring.is_homomorphism H eq one add mul (F q) Logic.eq F.one F.add F.mul phi'. Proof using phi'_add phi'_iff phi'_mul phi'_one phi'_opp phi'_phi phi'_sub phi'_zero. eapply @Ring.ring_by_isomorphism; assumption || exact _. Qed. - Local Instance _iso_ring : Algebra.ring := proj1 ring. + Local Instance _iso_ring : Algebra.Hierarchy.ring := proj1 ring. Local Instance _iso_hom1 : Ring.is_homomorphism := proj1 (proj2 ring). Local Instance _iso_hom2 : Ring.is_homomorphism := proj2 (proj2 ring). @@ -279,12 +279,12 @@ Module F. Let div_proof : forall a b : H, phi' (mul (inv b) a) = phi' a / phi' b. Proof. intros. - rewrite phi'_mul, inv_proof, Algebra.field_div_definition, Algebra.commutative. + rewrite phi'_mul, inv_proof, Algebra.Hierarchy.field_div_definition, Algebra.Hierarchy.commutative. reflexivity. Qed. Lemma field_and_iso : - @Algebra.field H eq zero one opp add sub mul inv div + @Algebra.Hierarchy.field H eq zero one opp add sub mul inv div /\ @Ring.is_homomorphism (F q) Logic.eq F.one F.add F.mul H eq one add mul phi /\ @Ring.is_homomorphism H eq one add mul (F q) Logic.eq F.one F.add F.mul phi'. Proof using Type*. eapply @Field.field_and_homomorphism_from_redundant_representation; diff --git a/src/SaturatedBaseSystem.v b/src/Arithmetic/Saturated.v index cddb9797d..cb37fb1f9 100644 --- a/src/SaturatedBaseSystem.v +++ b/src/Arithmetic/Saturated.v @@ -3,8 +3,8 @@ Require Import Coq.ZArith.ZArith. Require Import Coq.Lists.List. Local Open Scope Z_scope. -Require Import Crypto.Tactics.Algebra_syntax.Nsatz. -Require Import Crypto.NewBaseSystem. +Require Import Crypto.Algebra.Nsatz. +Require Import Crypto.Arithmetic.Core. Require Import Crypto.Util.LetIn Crypto.Util.CPSUtil. Require Import Crypto.Util.Tuple Crypto.Util.ListUtil. Require Import Crypto.Util.Tactics.BreakMatch. diff --git a/src/Assembly/Bounds.v b/src/Assembly/Bounds.v deleted file mode 100644 index 3064f840c..000000000 --- a/src/Assembly/Bounds.v +++ /dev/null @@ -1,515 +0,0 @@ -Require Export Bedrock.Word Bedrock.Nomega. -Require Import NArith PArith Ndigits Nnat NPow NPeano Ndec Ndigits. -Require Import Compare_dec Omega. -Require Import FunctionalExtensionality ProofIrrelevance. -Require Import Crypto.Assembly.QhasmUtil Crypto.Assembly.QhasmEvalCommon Crypto.Assembly.WordizeUtil. - -Import EvalUtil. - -Hint Rewrite wordToN_nat Nat2N.inj_add N2Nat.inj_add - Nat2N.inj_mul N2Nat.inj_mul Npow2_nat : N. - -Open Scope nword_scope. - -Section Bounds. - Lemma wordize_plus': forall {n} (x y: word n) (b: N), - (&x < b)%N - -> (&y < (Npow2 n - b))%N - -> (b <= Npow2 n)%N - -> (&x + &y)%N = & (x ^+ y). - Proof. - intros. - unfold wplus, wordBin. - rewrite wordToN_NToWord; intuition. - apply (N.lt_le_trans _ (b + &y)%N _). - - - apply N.add_lt_le_mono; try assumption. - apply N.eq_le_incl; reflexivity. - - - replace (Npow2 n) with (b + Npow2 n - b)%N by nomega; - replace (b + Npow2 n - b)%N with (b + (Npow2 n - b))%N by ( - replace (b + (Npow2 n - b))%N with ((Npow2 n - b) + b)%N by nomega; - rewrite (N.sub_add b (Npow2 n)) by assumption; - nomega). - - apply N.add_le_mono_l; try nomega. - apply N.lt_le_incl; assumption. - Qed. - - Lemma wordize_mult': forall {n} (x y: word n) (b: N), - (1 < n)%nat -> (0 < b)%N - -> (&x < b)%N - -> (&y < (Npow2 n) / b)%N - -> (&x * &y)%N = & (x ^* y). - Proof. - intros; unfold wmult, wordBin. - rewrite wordToN_NToWord; intuition. - apply (N.lt_le_trans _ (b * ((Npow2 n) / b))%N _). - - - apply N.mul_lt_mono; assumption. - - - apply N.mul_div_le; nomega. - Qed. - - Lemma constant_bound_N : forall {n} (k: word n), - (& k < & k + 1)%N. - Proof. intros; nomega. Qed. - - Lemma constant_bound_nat : forall (n k: nat), - (N.of_nat k < Npow2 n)%N - -> (& (@natToWord n k) < (N.of_nat k) + 1)%N. - Proof. - intros. - rewrite wordToN_nat. - rewrite wordToNat_natToWord_idempotent; - try assumption; nomega. - Qed. - - Lemma let_bound : forall {n} (x: word n) (f: word n -> word n) xb fb, - (& x < xb)%N - -> (forall x', & x' < xb -> & (f x') < fb)%N - -> ((let k := x in &(f k)) < fb)%N. - Proof. intros; eauto. Qed. - - Definition Nlt_dec (x y: N): {(x < y)%N} + {(x >= y)%N}. - refine ( - let c := N.compare x y in - match c as c' return c = c' -> _ with - | Lt => fun _ => left _ - | _ => fun _ => right _ - end eq_refl); - abstract ( - unfold c, N.ge, N.lt in *; intuition; subst; - match goal with - | [H0: ?x = _, H1: ?x = _ |- _] => - rewrite H0 in H1; inversion H1 - end). - Defined. - - Lemma wplus_bound : forall {n} (w1 w2 : word n) b1 b2, - (&w1 < b1)%N - -> (&w2 < b2)%N - -> (&(w1 ^+ w2) < b1 + b2)%N. - Proof. - intros. - - destruct (Nlt_dec (b1 + b2)%N (Npow2 n)) as [g|g]. - - - rewrite <- wordize_plus' with (b := b1); - try apply N.add_lt_mono; - try assumption. - - + apply (N.lt_le_trans _ b2 _); try assumption. - apply N.lt_le_incl. - apply N.lt_add_lt_sub_l. - assumption. - - + apply N.lt_le_incl; nomega. - - - apply (N.lt_le_trans _ (Npow2 n) _). - - + apply word_size_bound. - - + unfold N.le, N.ge in *. - intro Hg. - contradict g. - rewrite N.compare_antisym. - rewrite Hg. - simpl; intuition. - Qed. - - Theorem wmult_bound : forall {n} (w1 w2 : word n) b1 b2, - (1 < n)%nat - -> (&w1 < b1)%N - -> (&w2 < b2)%N - -> (&(w1 ^* w2) < b1 * b2)%N. - Proof. - intros. - destruct (Nlt_dec (b1 * b2)%N (Npow2 n)) as [g|g]. - - - rewrite <- wordize_mult' with (b := b1); - try apply N.mul_lt_mono; - try assumption; - try nomega. - - apply (N.lt_le_trans _ b2 _); try assumption. - apply N.div_le_lower_bound. - - + induction (& w1); nomega. - - + apply N.lt_le_incl. - assumption. - - - apply (N.lt_le_trans _ (Npow2 n) _). - - + apply word_size_bound. - - + unfold N.le, N.ge in *. - intro Hg. - contradict g. - rewrite N.compare_antisym. - rewrite Hg. - simpl; intuition. - Qed. - - Lemma wminus_bound: forall {n} (x y: word n) low0 high0 low1 high1, - (low0 <= wordToN x)%N -> (wordToN x <= high0)%N - -> (low1 <= wordToN y)%N -> (wordToN y <= high1)%N - -> (&x >= &y)%N -> (& (x ^- y) <= high0 - low1)%N. - Proof. - intros. - - destruct (Nge_dec 0%N (&y)). { - unfold wminus, wneg. - replace (& y) with 0%N in * by nomega. - replace low1 with 0%N by (symmetry; apply N.le_0_r; assumption). - replace (Npow2 n - 0)%N with (& (wzero n) + Npow2 n)%N - by (rewrite wordToN_zero; nomega). - rewrite <- Npow2_ignore. - rewrite wplus_comm. - rewrite wplus_unit. - replace (high0 - 0)%N with high0 by nomega; assumption. - } - - assert (& x - & y < Npow2 n)%N. { - transitivity (wordToN x); - try apply word_size_bound; - apply N.sub_lt; - [apply N.ge_le|]; assumption. - } - - assert (& x - & y + & y < Npow2 n)%N. { - replace (& x - & y + & y)%N - with (wordToN x) by nomega; - apply word_size_bound. - } - - assert (x = NToWord n (wordToN x - wordToN y) ^+ y) as Hv. { - apply NToWord_equal. - rewrite <- wordize_plus; rewrite wordToN_NToWord; try assumption. - nomega. - } - - rewrite Hv. - unfold wminus. - rewrite <- wplus_assoc. - rewrite wminus_inv. - rewrite wplus_comm. - rewrite wplus_unit. - rewrite wordToN_NToWord; try assumption. - - transitivity (high0 - & y)%N; - [apply N.sub_le_mono_r | apply N.sub_le_mono_l]; - assumption. - Qed. - - Lemma shiftr_bound : forall {n} (w : word n) b bits, - (&w < b)%N - -> (&(shiftr w bits) < N.succ (N.shiftr_nat b bits))%N. - Proof. - intros. - apply (N.le_lt_trans _ (N.shiftr_nat b bits) _). - - - unfold shiftr, extend, high. - destruct (le_dec bits n); try omega. - - + rewrite wordToN_convS. - rewrite wordToN_zext. - rewrite wordToN_split2. - rewrite wordToN_convS. - rewrite <- Nshiftr_equiv_nat. - repeat rewrite N.shiftr_div_pow2. - apply N.div_le_mono. - - * induction bits; try nomega. - rewrite Nat2N.inj_succ. - rewrite N.pow_succ_r'. - assert (bits <= n)%nat as Hc by omega. - apply IHbits in Hc. - intro Hc'; contradict Hc. - apply (N.mul_cancel_l _ _ 2); - try rewrite Hc'; - try assumption; - nomega. - - * apply N.lt_le_incl. - assumption. - - + rewrite wordToN_nat. - unfold wzero. - rewrite wordToNat_natToWord_idempotent; simpl; - try apply N_ge_0; - try apply Npow2_gt0. - - - nomega. - - Qed. - - Lemma shiftr_bound' : forall {n} (w : word n) b bits, - (&w <= b)%N - -> (&(shiftr w bits) <= N.shiftr_nat b bits)%N. - Proof. - intros. - transitivity (N.shiftr_nat b bits). - - - unfold shiftr, extend, high. - destruct (le_dec bits n); try omega. - - + rewrite wordToN_convS. - rewrite wordToN_zext. - rewrite wordToN_split2. - rewrite wordToN_convS. - rewrite <- Nshiftr_equiv_nat. - repeat rewrite N.shiftr_div_pow2. - apply N.div_le_mono; [|assumption]. - - induction bits; try nomega. - rewrite Nat2N.inj_succ. - rewrite N.pow_succ_r'. - assert (bits <= n)%nat as Hc by omega. - apply IHbits in Hc. - intro Hc'; contradict Hc. - apply (N.mul_cancel_l _ _ 2); - try rewrite Hc'; - try assumption; - nomega. - - + rewrite wordToN_nat. - unfold wzero. - rewrite wordToNat_natToWord_idempotent; simpl; - try apply N_ge_0; - try apply Npow2_gt0. - - - apply N.eq_le_incl; reflexivity. - Qed. - - Lemma mask_bound : forall {n} (w : word n) m, - (&(mask m w) < Npow2 m)%N. - Proof. - intros. - unfold mask in *; destruct (le_dec m n); simpl; - try apply extend_bound. - - pose proof (word_size_bound w) as H. - apply (N.le_lt_trans _ (Npow2 n) _). - - - unfold N.le, N.lt in *; rewrite H; intro H0; inversion H0. - - - clear H. - replace m with ((m - n) + n) by nomega. - replace (Npow2 n) with (1 * (Npow2 n))%N - by (rewrite N.mul_comm; nomega). - rewrite Npow2_split. - apply N.mul_lt_mono_pos_r; try apply Npow2_gt0. - assert (0 < m - n)%nat by omega. - induction (m - n); try inversion H; try abstract ( - simpl; replace 2 with (S 1) by omega; - apply N.lt_1_2); subst. - - assert (0 < n1)%nat as Z by omega; apply IHn1 in Z. - apply (N.le_lt_trans _ (Npow2 n1) _). - - + apply N.lt_le_incl; assumption. - - + rewrite Npow2_succ. - replace' (Npow2 n1) with (1 * Npow2 n1)%N at 1 by (apply N.mul_1_l). - apply N.mul_lt_mono_pos_r; try abstract (vm_compute; reflexivity). - apply (N.lt_le_trans _ 1 _); try abstract (vm_compute; reflexivity). - apply N.lt_le_incl; assumption. - Qed. - - Lemma mask_update_bound : forall {n} (w : word n) b m, - (1 < n)%nat - -> (&w < b)%N - -> (&(mask m w) < (N.min b (Npow2 m)))%N. - Proof. - intros. - assert (& w mod Npow2 m < b)%N. { - destruct (Nge_dec (&w) (Npow2 m)). - - - apply (N.lt_le_trans _ (Npow2 m) _). - - + pose proof (N.mod_bound_pos (&w) (Npow2 m) - (N_ge_0 _) (Npow2_gt0 _)) as H1. - destruct H1. - assumption. - - + transitivity (&w); try abstract (apply ge_to_le; assumption). - apply N.lt_le_incl; assumption. - - - rewrite N.mod_small; assumption. - } - - unfold mask, N.min, extend, low; - destruct (le_dec m n), - (N.compare b (Npow2 m)); simpl; - repeat first [ - rewrite wordToN_convS | - rewrite wordToN_zext | - rewrite wordToN_wones | - rewrite wordToN_split1 | - rewrite N.land_ones | - rewrite <- Npow2_N ]; - try assumption. - - - pose proof (N.mod_bound_pos (&w) (Npow2 m) (N_ge_0 _) (Npow2_gt0 _)) as Z. - destruct Z. - assumption. - - - apply (N.lt_le_trans _ (Npow2 n) _); - try apply word_size_bound. - apply Npow2_ordered. - omega. - Qed. - - Lemma plus_overflow_bound: forall x y a b, - (x < a)%N - -> (y < b - a)%N - -> (x + y < b)%N. - Proof. intros; nomega. Qed. - -End Bounds. - -(** Constant Tactics **) - -Ltac assert_nat_constant t := - timeout 1 (match (eval vm_compute in t) with - | O => idtac - | S ?n => assert_nat_constant n - | _ => fail - end). - -Ltac assert_pos_constant t := - timeout 1 (match (eval vm_compute in t) with - | xH => idtac - | xI ?p => assert_pos_constant p - | xO ?p => assert_pos_constant p - | _ => fail - end). - -Ltac assert_bin_constant t := - timeout 1 (match (eval vm_compute in t) with - | N.pos ?p => assert_pos_constant p - | N0 => idtac - | _ => fail - end). - -Ltac assert_word_constant t := - timeout 1 (match (eval vm_compute in t) with - | WO => idtac - | WS _ ?w => assert_word_constant w - | _ => fail - end). - -(** Bounding Tactics **) - -Ltac multi_apply0 A L := pose proof (L A). - -Ltac multi_apply1 A L := - match goal with - | [ H: (wordToN A < ?b)%N |- _] => pose proof (L A b H) - end. - -Ltac multi_apply2 A B L := - match goal with - | [ H1: (wordToN A < ?b1)%N, H2: (wordToN B < ?b2)%N |- _] => pose proof (L A B b1 b2 H1 H2) - end. - -Ltac multi_recurse n T := - match goal with - | [ H: (wordToN T < _)%N |- _] => idtac - | _ => - is_var T; - let T' := (eval cbv delta [T] in T) in multi_recurse n T'; - match goal with - | [ H : T' < ?x |- _ ] => - pose proof (H : T < x) - end - - | _ => - match T with - | ?W1 ^+ ?W2 => - multi_recurse n W1; multi_recurse n W2; - multi_apply2 W1 W2 (@wplus_bound n) - - | ?W1 ^* ?W2 => - multi_recurse n W1; multi_recurse n W2; - multi_apply2 W1 W2 (@wmult_bound n) - - | mask ?m ?w => - multi_recurse n w; - multi_apply1 w (fun b => @mask_update_bound n w b) - - | mask ?m ?w => - multi_recurse n w; - pose proof (@mask_bound n w m) - - | shiftr ?w ?bits => - multi_recurse n w; - match goal with - | [ H: (w < ?b)%N |- _] => - pose proof (@shiftr_bound n w b bits H) - end - - | NToWord _ ?k => pose proof (@constant_bound_N n k) - | natToWord _ ?k => pose proof (@constant_bound_nat n k) - | _ => pose proof (@word_size_bound n T) - end - end. - -Lemma unwrap_let: forall {n} (y: word n) (f: word n -> word n) (b: N), - (&(let x := y in f x) < b)%N <-> let x := y in (&(f x) < b)%N. -Proof. intuition. Qed. - -Ltac bound_compute := - repeat (try assumption; match goal with - | [|- let A := ?B in _] => - match (type of B) with - | word ?n => multi_recurse n B; intro - end - - | [|- ((let A := _ in _) < _)%N] => - apply unwrap_let - - | [ H: (wordToN ?W < ?b0)%N |- (wordToN ?W < ?b1)%N ] => - try eassumption; eapply (N.lt_le_trans _ b0 _); try eassumption - - | [|- (@wordToN ?n ?W < ?b)%N ] => - multi_recurse n W - - | [|- (?x + ?y < ?b)%N ] => - eapply plus_overflow_bound - - | [|- (?a <= ?b)%N ] => - is_evar b; apply N.eq_le_incl; reflexivity - - | [|- (?a <= ?b)%N ] => - is_evar a; apply N.eq_le_incl; reflexivity - - | [|- (?a <= ?b)%N ] => - assert_bin_constant a; - assert_bin_constant b; - vm_compute; - try reflexivity; - try abstract (let H := fresh in intro H; inversion H) - - | [|- (?x < ?b)%N ] => - assert_bin_constant x; - assert_bin_constant b; - vm_compute; reflexivity - - (* cleanup generated nat goals *) - | [|- (?a <= ?b)%nat ] => omega - | [|- (?a < ?b)%nat ] => omega - end). - -(* for x : word n *) -Ltac find_bound_on x := - match (type of x) with - | word ?n => - match x with - | let A := ?b in ?c => find_bound_on b; set (A := b) - | _ => multi_recurse n x - end - | _ => idtac - end. diff --git a/src/Assembly/Compile.v b/src/Assembly/Compile.v deleted file mode 100644 index e9300ff0f..000000000 --- a/src/Assembly/Compile.v +++ /dev/null @@ -1,299 +0,0 @@ -Require Import Coq.Logic.Eqdep. -Require Import Coq.Arith.Compare_dec Coq.Bool.Sumbool. -Require Import Coq.Numbers.Natural.Peano.NPeano Coq.omega.Omega. - -Require Import Crypto.Assembly.PhoasCommon. -Require Import Crypto.Assembly.HL. -Require Import Crypto.Assembly.LL. -Require Import Crypto.Assembly.QhasmEvalCommon. -Require Import Crypto.Assembly.QhasmCommon. -Require Import Crypto.Assembly.Qhasm. - -Local Arguments LetIn.Let_In _ _ _ _ / . - -Module CompileHL. - Section Compilation. - Context {T: Type}. - - Fixpoint compile {T t} (e:@HL.expr T (@LL.arg T T) t) : @LL.expr T T t := - match e with - | HL.Const _ n => LL.Return (LL.Const n) - - | HL.Var _ arg => LL.Return arg - - | HL.Binop t1 t2 t3 op e1 e2 => - LL.under_lets (compile e1) (fun arg1 => - LL.under_lets (compile e2) (fun arg2 => - LL.LetBinop op arg1 arg2 (fun v => - LL.Return v))) - - | HL.Let _ ex _ eC => - LL.under_lets (compile ex) (fun arg => - compile (eC arg)) - - | HL.Pair t1 e1 t2 e2 => - LL.under_lets (compile e1) (fun arg1 => - LL.under_lets (compile e2) (fun arg2 => - LL.Return (LL.Pair arg1 arg2))) - - | HL.MatchPair _ _ ep _ eC => - LL.under_lets (compile ep) (fun arg => - let (a1, a2) := LL.match_arg_Prod arg in - compile (eC a1 a2)) - end. - - Definition Compile {T t} (e:@HL.Expr T t) : @LL.expr T T t := - compile (e (@LL.arg T T)). - End Compilation. - - Section Correctness. - Context {T: Type}. - - Lemma compile_correct {_: Evaluable T} {t} e1 e2 G (wf:HL.wf G e1 e2) : - List.Forall (fun v => let 'existT _ (x, a) := v in LL.interp_arg a = x) G -> - LL.interp (compile e2) = HL.interp e1 :> interp_type t. - Proof using Type. - induction wf; - repeat match goal with - | [HIn:In ?x ?l, HForall:Forall _ ?l |- _ ] => - (pose proof (proj1 (Forall_forall _ _) HForall _ HIn); clear HIn) - | [ H : LL.match_arg_Prod _ = (_, _) |- _ ] => - apply LL.match_arg_Prod_correct in H - | [ H : LL.Pair _ _ = LL.Pair _ _ |- _ ] => - apply LL.Pair_eq in H - | [ H : (_, _) = (_, _) |- _ ] => inversion H; clear H - | _ => progress intros - | _ => progress simpl in * - | _ => progress subst - | _ => progress specialize_by assumption - | _ => progress break_match - | _ => rewrite !LL.interp_under_lets - | _ => rewrite !LL.interp_arg_uninterp_arg - | _ => progress erewrite_hyp !* - | _ => apply Forall_cons - | _ => solve [intuition (congruence || eauto)] - end. - Qed. - End Correctness. -End CompileHL. - -Module CompileLL. - Import LL Qhasm. - Import QhasmUtil ListNotations. - - Section Compile. - Context {n: nat} {w: Width n}. - - Definition WArg t': Type := @LL.arg (word n) (word n) t'. - Definition WExpr t': Type := @LL.expr (word n) (word n) t'. - - Section Mappings. - Definition indexize (x: nat) : Index n. - intros; destruct (le_dec n 0). - - - exists 0; abstract intuition auto with zarith. - - exists (x mod n)%nat. - abstract (pose proof (Nat.mod_bound_pos x n); - omega). - Defined. - - Definition getMapping (x: WArg TT) := - match x with - | Const v => constM n (@constant n w v) - | Var v => regM n (@reg n w (wordToNat v)) - end. - - Definition getReg (x: Mapping n): option (Reg n) := - match x with | regM r => Some r | _ => None end. - - Definition getConst (x: Mapping n): option (QhasmCommon.Const n) := - match x with | constM c => Some c | _ => None end. - - Definition makeA (output input: Mapping n): list Assignment := - match (output, input) with - | (regM r, constM c) => [AConstInt r c] - | (regM r0, regM r1) => [ARegReg r0 r1] - | _ => [] - end. - - Definition makeOp {t1 t2 t3} (op: binop t1 t2 t3) (tmp out: Reg n) (in1 in2: Mapping n): - option (Reg n * list Assignment * Operation) := - let mov := - if (EvalUtil.mapping_dec (regM _ out) in1) - then [] - else makeA (regM _ out) in1 in - - match op with - | OPadd => - match in2 with - | regM r1 => Some (out, mov, IOpReg IAdd out r1) - | constM c => Some (out, mov, IOpConst IAdd out c) - | _ => None - end - - | OPsub => - match in2 with - | regM r1 => Some (out, mov, IOpReg ISub out r1) - | constM c => Some (out, mov, IOpConst ISub out c) - | _ => None - end - - | OPmul => - match in2 with - | regM r1 => Some (out, mov, DOp Mult out r1 None) - | constM c => Some (out, mov ++ (makeA (regM _ tmp) in2), DOp Mult out tmp None) - | _ => None - end - - | OPand => - match in2 with - | regM r1 => Some (out, mov, IOpReg IAnd out r1) - | constM c => Some (out, mov, IOpConst IAnd out c) - | _ => None - end - - | OPshiftr => - match in2 with - | constM (constant _ _ w) => - Some (out, mov, ROp Shr out (indexize (wordToNat w))) - | _ => None - end - end. - - End Mappings. - - Section TypeDec. - Fixpoint type_eqb (t0 t1: type): bool := - match (t0, t1) with - | (TT, TT) => true - | (Prod t0a t0b, Prod t1a t1b) => andb (type_eqb t0a t1a) (type_eqb t0b t1b) - | _ => false - end. - - Lemma type_eqb_spec: forall t0 t1, type_eqb t0 t1 = true <-> t0 = t1. - Proof using Type. - intros; split. - - - revert t1; induction t0 as [|t0a IHt0a t0b IHt0b]. - - + induction t1; intro H; simpl in H; inversion H; reflexivity. - - + induction t1; intro H; simpl in H; inversion H. - apply andb_true_iff in H; destruct H as [Ha Hb]. - - apply IHt0a in Ha; apply IHt0b in Hb; subst. - reflexivity. - - - intro H; subst. - induction t1; simpl; [reflexivity|]; apply andb_true_iff; intuition. - Qed. - - Definition type_dec (t0 t1: type): {t0 = t1} + {t0 <> t1}. - refine (match (type_eqb t0 t1) as b return _ = b -> _ with - | true => fun e => left _ - | false => fun e => right _ - end eq_refl); - [ abstract (apply type_eqb_spec in e; assumption) - | abstract (intro H; apply type_eqb_spec in H; - rewrite e in H; contradict H; intro C; inversion C) ]. - Defined. - End TypeDec. - - Fixpoint vars {t} (a: WArg t): list nat := - match t as t' return WArg t' -> list nat with - | TT => fun a' => - match a' with - | Var v' => [wordToNat v'] - | _ => @nil nat - end - | Prod t0 t1 => fun a' => - match a' with - | Pair _ _ a0 a1 => (vars a0) ++ (vars a1) - | _ => I (* dummy *) - end - end a. - - Definition getOutputSlot (nextReg: nat) - (op: binop TT TT TT) (x: WArg TT) (y: WArg TT) : option nat := - match (makeOp op (reg w nextReg) (reg w (S nextReg)) (getMapping x) (getMapping y)) with - | Some (reg _ _ r, _ , _) => Some r - | _ => None - end. - - Section ExprF. - Context (Out: Type) - (update: Reg n -> WArg TT -> binop TT TT TT -> WArg TT -> WArg TT -> Out -> option Out) - (get: forall t', WArg t' -> option Out). - - Definition opToTT {t1 t2 t3} (op: binop t1 t2 t3): option (binop TT TT TT) := - match op with - | OPadd => Some OPadd - | OPsub => Some OPsub - | OPmul => Some OPmul - | OPand => Some OPand - | OPshiftr => Some OPshiftr - end. - - Definition argToTT {t} (a: WArg t): option (WArg TT) := - match t as t' return WArg t' -> _ with - | TT => fun a' => Some a' - | _ => fun a' => None - end a. - - Fixpoint zeros (t: type): WArg t := - match t with - | TT => Const (@wzero n) - | Prod t0 t1 => Pair (zeros t0) (zeros t1) - end. - - Fixpoint exprF {t} (nextRegName: nat) (p: WExpr t) {struct p}: option Out := - match p with - | LetBinop t1 t2 t3 op x y t' eC => - omap (opToTT op) (fun op' => - omap (argToTT x) (fun x' => - omap (argToTT y) (fun y' => - omap (getOutputSlot nextRegName op' x' y') (fun r => - let var := - match t3 as t3' return WArg t3' with - | TT => Var (natToWord _ r) - | _ => zeros _ - end in - - omap (exprF (S (S nextRegName)) (eC var)) (fun out => - omap (argToTT var) (fun var' => - update (reg w nextRegName) var' op' x' y' out)))))) - | Return _ a => get _ a - end. - End ExprF. - - Definition getProg := - @exprF Program - (fun rt var op x y out => - omap (getReg (getMapping var)) (fun rv => - match (makeOp op rt rv (getMapping x) (getMapping y)) with - | Some (reg _ _ r, a, op') => - Some ((map QAssign a) ++ ((QOp op') :: out)) - | _ => None - end)) - (fun t' a => Some []). - - Definition getOuts := - @exprF (list nat) - (fun rt var op x y out => Some out) - (fun t' a => Some (vars a)). - - Fixpoint fillInputs t inputs (prog: NAry inputs Z (WExpr t)) {struct inputs}: WExpr t := - match inputs as inputs' return NAry inputs' Z (WExpr t) -> NAry O Z (WExpr t) with - | O => fun p => p - | S inputs'' => fun p => @fillInputs _ _ (p (Z.of_nat inputs)) - end prog. - Global Arguments fillInputs {t inputs} _. - - Definition compile {t inputs} (p: NAry inputs Z (WExpr t)): option (Program * list nat) := - let p' := fillInputs p in - - omap (getOuts _ (S inputs) p') (fun outs => - omap (getProg _ (S inputs) p') (fun prog => - Some (prog, outs))). - End Compile. -End CompileLL. diff --git a/src/Assembly/Conversions.v b/src/Assembly/Conversions.v deleted file mode 100644 index f677b6d58..000000000 --- a/src/Assembly/Conversions.v +++ /dev/null @@ -1,458 +0,0 @@ -Require Import Crypto.Assembly.PhoasCommon. - -Require Export Crypto.Assembly.QhasmUtil. -Require Export Crypto.Assembly.QhasmEvalCommon. -Require Export Crypto.Assembly.WordizeUtil. -Require Export Crypto.Assembly.Evaluables. -Require Export Crypto.Assembly.HL. -Require Export Crypto.Assembly.LL. - -Require Export FunctionalExtensionality. - -Require Import Bedrock.Nomega. - -Require Import Coq.ZArith.ZArith_dec. -Require Import Coq.ZArith.Znat. - -Require Import Coq.NArith.Nnat Coq.NArith.Ndigits. - -Require Import Coq.Bool.Sumbool. -Require Import Coq.Program.Basics. - -Local Arguments LetIn.Let_In _ _ _ _ / . - -Definition typeMap {A B t} (f: A -> B) (x: @interp_type A t): @interp_type B t. -Proof. - induction t; [refine (f x)|]. - destruct x as [x1 x2]. - refine (IHt1 x1, IHt2 x2). -Defined. - -Module HLConversions. - Import HL. - - Fixpoint convertExpr {A B: Type} {EB: Evaluable B} {t v} (a: expr (T := A) (var := v) t): expr (T := B) (var := v) t := - match a with - | Const E x => Const (@toT B EB (@fromT A E x)) - | Var t x => @Var B _ t x - | Binop t1 t2 t3 o e1 e2 => - @Binop B _ t1 t2 t3 o (convertExpr e1) (convertExpr e2) - | Let tx e tC f => - Let (convertExpr e) (fun x => convertExpr (f x)) - | Pair t1 e1 t2 e2 => Pair (convertExpr e1) (convertExpr e2) - | MatchPair t1 t2 e tC f => MatchPair (convertExpr e) (fun x y => - convertExpr (f x y)) - end. -End HLConversions. - -Module LLConversions. - Import LL. - - Section VarConv. - Context {A B: Type} {EA: Evaluable A} {EB: Evaluable B}. - - Definition convertVar {t} (a: interp_type (T := A) t): interp_type (T := B) t. - Proof. - induction t as [| t3 IHt1 t4 IHt2]. - - - refine (@toT B EB (@fromT A EA _)); assumption. - - - destruct a as [a1 a2]; constructor; - [exact (IHt1 a1) | exact (IHt2 a2)]. - Defined. - End VarConv. - - Section ArgConv. - Context {A B: Type} {EA: Evaluable A} {EB: Evaluable B}. - - Fixpoint convertArg {V} t {struct t}: @arg A V t -> @arg B V t := - match t as t' return @arg A V t' -> @arg B V t' with - | TT => fun x => - match x with - | Const c => Const (convertVar (t := TT) c) - | Var v => Var v - end - | Prod t0 t1 => fun x => - match (match_arg_Prod x) with - | (a, b) => Pair ((convertArg t0) a) ((convertArg t1) b) - end - end. - End ArgConv. - - Section ExprConv. - Context {A B: Type} {EA: Evaluable A} {EB: Evaluable B}. - - Fixpoint convertExpr {t V} (a: @expr A V t): @expr B V t := - match a with - | LetBinop _ _ out op a b _ eC => - LetBinop (T := B) op (convertArg _ a) (convertArg _ b) (fun x: (arg out) => - convertExpr (eC (convertArg _ x))) - - | Return _ a => Return (convertArg _ a) - end. - End ExprConv. - - Section Defaults. - Context {t: type} {n: nat}. - - Definition Word := word n. - Definition Bounded := option (@BoundedWord n). - Definition RWV := option (RangeWithValue). - - Transparent Word Bounded RWV. - - Instance RWVEvaluable' : Evaluable RWV := @RWVEvaluable n. - Instance ZEvaluable' : Evaluable Z := ZEvaluable. - - Existing Instance ZEvaluable'. - Existing Instance WordEvaluable. - Existing Instance BoundedEvaluable. - Existing Instance RWVEvaluable'. - - Definition ZToWord a := @convertExpr Z Word _ _ t a. - Definition ZToBounded a := @convertExpr Z Bounded _ _ t a. - Definition ZToRWV a := @convertExpr Z RWV _ _ t a. - - Definition varZToWord a := @convertVar Z Word _ _ t a. - Definition varZToBounded a := @convertVar Z Bounded _ _ t a. - Definition varZToRWV a := @convertVar Z RWV _ _ t a. - - Definition varWordToZ a := @convertVar Word Z _ _ t a. - Definition varBoundedToZ a := @convertVar Bounded Z _ _ t a. - Definition varRWVToZ a := @convertVar RWV Z _ _ t a. - - Definition zinterp E := @interp Z _ t E. - Definition wordInterp E := @interp' Word _ _ t (fun x => NToWord n (Z.to_N x)) E. - Definition boundedInterp E := @interp Bounded _ t E. - Definition rwvInterp E := @interp RWV _ t E. - - Section Operations. - Context {tx ty tz: type}. - - Definition opZ (op: binop tx ty tz) - (x: @interp_type Z tx) (y: @interp_type Z ty): @interp_type Z tz := - @interp_binop Z _ _ _ _ op x y. - - Definition opBounded (op: binop tx ty tz) - (x: @interp_type Bounded tx) (y: @interp_type Bounded ty): @interp_type Bounded tz := - @interp_binop Bounded _ _ _ _ op x y. - - - Definition opWord (op: binop tx ty tz) - (x: @interp_type Word tx) (y: @interp_type Word ty): @interp_type Word tz := - @interp_binop Word _ _ _ _ op x y. - - Definition opRWV (op: binop tx ty tz) - (x: @interp_type RWV tx) (y: @interp_type RWV ty): @interp_type RWV tz := - @interp_binop RWV _ _ _ _ op x y. - End Operations. - - Definition rangeOf := fun x => - Some (rwv 0%N (Z.to_N x) (Z.to_N x)). - - Definition ZtoB := fun x => omap (rangeOf x) (bwFromRWV (n := n)). - End Defaults. - - Section Correctness. - Context {n: nat}. - - Definition W := (word n). - Definition B := (@Bounded n). - Definition R := (option RangeWithValue). - - Instance RE : Evaluable R := @RWVEvaluable n. - Instance ZE : Evaluable Z := ZEvaluable. - Instance WE : Evaluable W := @WordEvaluable n. - Instance BE : Evaluable B := @BoundedEvaluable n. - - Transparent ZE RE WE BE W B R. - - Existing Instance ZE. - Existing Instance RE. - Existing Instance WE. - Existing Instance BE. - - Ltac kill_dec := - repeat match goal with - | [|- context[Nge_dec ?a ?b] ] => destruct (Nge_dec a b) - | [H : context[Nge_dec ?a ?b] |- _ ] => destruct (Nge_dec a b) - end. - - Section BoundsChecking. - Context {T: Type} {E: Evaluable T} {f : T -> B}. - - Definition getBounds {t} (e : @expr T T t): @interp_type B t := - interp' f (@convertExpr T B _ _ t _ e). - - Fixpoint bcheck' {t} (x: @interp_type B t) := - match t as t' return (interp_type t') -> bool with - | TT => fun x' => - match x' with - | Some _ => true - | None => false - end - | Prod t0 t1 => fun x' => - match x' with - | (x0, x1) => andb (bcheck' x0) (bcheck' x1) - end - end x. - - Definition bcheck {t} (e : expr t): bool := bcheck' (getBounds e). - End BoundsChecking. - - Section UtilityLemmas. - Context {A B} {EA: Evaluable A} {EB: Evaluable B}. - - Lemma convertArg_interp' : forall {t V} f (x: @arg A V t), - (interp_arg' (fun z => toT (fromT (f z))) (@convertArg A B EA EB _ t x)) - = @convertVar A B EA EB t (interp_arg' f x). - Proof using Type. - intros. - induction x as [| |t0 t1 i0 i1]; simpl; [reflexivity|reflexivity|]. - induction EA, EB; simpl; f_equal; assumption. - Qed. - - Lemma convertArg_var: forall {A B EA EB t} V (x: @interp_type A t), - @convertArg A B EA EB V t (uninterp_arg x) = uninterp_arg (var := V) (@convertVar A B EA EB t x). - Proof using Type. - induction t as [|t0 IHt_0 t1 IHt_1]; simpl; intros; [reflexivity|]. - induction x as [a b]; simpl; f_equal; - induction t0 as [|t0a IHt0_0 t0b IHt0_1], - t1 as [|t1a IHt1_0]; simpl in *; - try rewrite IHt_0; - try rewrite IHt_1; - reflexivity. - Qed. - - Lemma ZToBounded_binop_correct : forall {tx ty tz} (op: binop tx ty tz) (x: @arg Z Z tx) (y: @arg Z Z ty) e f, - bcheck (t := tz) (f := f) (LetBinop op x y e) = true - -> opZ op (interp_arg x) (interp_arg y) = - varBoundedToZ (n := n) (opBounded op - (interp_arg' f (convertArg _ x)) - (interp_arg' f (convertArg _ y))). - Proof. - Admitted. - - Lemma ZToWord_binop_correct : forall {tx ty tz} (op: binop tx ty tz) (x: arg tx) (y: arg ty) e f, - bcheck (t := tz) (f := f) (LetBinop op x y e) = true - -> opZ op (interp_arg x) (interp_arg y) = - varWordToZ (opWord (n := n) op (varZToWord (interp_arg x)) (varZToWord (interp_arg y))). - Proof. - Admitted. - - Lemma roundTrip_0 : @toT Correctness.B BE (@fromT Z ZE 0%Z) <> None. - Proof using Type. - intros; unfold toT, fromT, BE, ZE, BoundedEvaluable, ZEvaluable, bwFromRWV; - simpl; try break_match; simpl; try abstract (intro Z; inversion Z); - pose proof (Npow2_gt0 n); simpl in *; nomega. - Qed. - - Lemma double_conv_var: forall t x, - @convertVar R Z _ _ t (@convertVar B R _ _ t x) = - @convertVar B Z _ _ t x. - Proof. - intros. - Admitted. - - Lemma double_conv_arg: forall V t a, - @convertArg R B _ _ V t (@convertArg Z R _ _ V t a) = - @convertArg Z B _ _ V t a. - Proof. - intros. - Admitted. - End UtilityLemmas. - - - Section Spec. - Ltac kill_just n := - match goal with - | [|- context[just ?x] ] => - let Hvalue := fresh in let Hvalue' := fresh in - let Hlow := fresh in let Hlow' := fresh in - let Hhigh := fresh in let Hhigh' := fresh in - let Hnone := fresh in let Hnone' := fresh in - - let B := fresh in - - pose proof (just_value_spec (n := n) x) as Hvalue; - pose proof (just_low_spec (n := n) x) as Hlow; - pose proof (just_high_spec (n := n) x) as Hhigh; - pose proof (just_None_spec (n := n) x) as Hnone; - - destruct (just x); - - try pose proof (Hlow _ eq_refl) as Hlow'; - try pose proof (Hvalue _ eq_refl) as Hvalue'; - try pose proof (Hhigh _ eq_refl) as Hhigh'; - try pose proof (Hnone eq_refl) as Hnone'; - - clear Hlow Hhigh Hvalue Hnone - end. - - Lemma RangeInterp_bounded_spec: forall {t} (E: @expr Z Z t), - bcheck (f := ZtoB) E = true - -> typeMap (fun x => NToWord n (Z.to_N x)) (zinterp E) = wordInterp (ZToWord _ E). - Proof. - intros t E S. - unfold zinterp, ZToWord, wordInterp. - - induction E as [tx ty tz op x y z|]; simpl; try reflexivity. - - - repeat rewrite convertArg_var in *. - repeat rewrite convertArg_interp in *. - - rewrite H; clear H; repeat f_equal. - - + pose proof (ZToWord_binop_correct op x y) as C; - unfold opZ, opWord, varWordToZ, varZToWord in C; - simpl in C. - - assert (N.pred (Npow2 n) >= 0)%N. { - apply N.le_ge. - rewrite <- (N.pred_succ 0). - apply N.le_pred_le_succ. - rewrite N.succ_pred; [| apply N.neq_0_lt_0; apply Npow2_gt0]. - apply N.le_succ_l. - apply Npow2_gt0. - } - - admit. (* - induction op; rewrite (C (fun _ => Return (Const 0%Z))); clear C; - unfold bcheck, getBounds, boundedInterp, bwFromRWV in *; simpl in *; - kill_dec; simpl in *; kill_dec; first [reflexivity|nomega]. *) - - + unfold bcheck, getBounds in *. - replace (interp_binop op (interp_arg x) (interp_arg y)) - with (varBoundedToZ (n := n) (opBounded op - (interp_arg' ZtoB (convertArg _ x)) - (interp_arg' ZtoB (convertArg _ y)))). - - * rewrite <- S; f_equal; clear S. - simpl; repeat f_equal. - unfold varBoundedToZ, opBounded. - repeat rewrite convertArg_var. - Arguments convertArg _ _ _ _ _ _ _ : clear implicits. - admit. - - * pose proof (ZToBounded_binop_correct op x y) as C; - unfold opZ, opWord, varZToBounded, - varBoundedToZ in *; - simpl in C. - - Local Opaque toT fromT. - - induction op; erewrite (C (fun _ => Return (Const 0%Z))); clear C; try reflexivity; - unfold bcheck, getBounds; simpl; - pose proof roundTrip_0 as H; - induction (toT (fromT _)); first [reflexivity|contradict H; reflexivity]. - - Local Transparent toT fromT. - - - simpl in S. - induction a as [| |t0 t1 a0 IHa0 a1 IHa1]; simpl in *; try reflexivity. - admit. - - (* - + f_equal. - unfold bcheck, getBounds, boundedInterp in S; simpl in S. - kill_dec; simpl; [reflexivity|simpl in S; inversion S]. - - + f_equal. - unfold bcheck, getBounds, boundedInterp, boundVarInterp in S; simpl in S; - kill_dec; simpl; try reflexivity; try nomega. - inversion S. - admit. - admit. - - + unfold bcheck in S; simpl in S; - apply andb_true_iff in S; destruct S as [S0 S1]; - rewrite IHa0, IHa1; [reflexivity| |]; - unfold bcheck, getBounds; simpl; assumption. *) - Admitted. - End Spec. - - Section RWVSpec. - Section Defs. - Context {V} {f : V -> R}. - - Definition getRanges {t} (e : @expr R V t): @interp_type (option (Range N)) t := - typeMap (option_map rwvToRange) (interp' f e). - - Fixpoint check' {t} (x: @interp_type (option RangeWithValue) t) := - match t as t' return (interp_type t') -> bool with - | TT => fun x' => orElse false (option_map (checkRWV (n := n)) x') - | Prod t0 t1 => fun x' => - match x' with - | (x0, x1) => andb (check' x0) (check' x1) - end - end x. - - Definition check {t} (e : @expr R V t): bool := check' (interp' f e). - End Defs. - - Ltac kill_dec := - repeat match goal with - | [|- context[Nge_dec ?a ?b] ] => destruct (Nge_dec a b) - | [H : context[Nge_dec ?a ?b] |- _ ] => destruct (Nge_dec a b) - end. - - Lemma check_spec' : forall {rangeF wordF} (op: @validBinaryWordOp n rangeF wordF) x y, - @convertVar B R _ _ TT ( - omap (interp_arg' ZtoB (convertArg TT x)) (fun X => - omap (interp_arg' ZtoB (convertArg TT y)) (fun Y => - bapp op X Y))) = - omap (interp_arg' rangeOf x) (fun X => - omap (interp_arg' rangeOf y) (fun Y => - rwv_app (n := n) op X Y)). - Proof. - Admitted. - - Lemma check_spec: forall {t} (E: @expr Z Z t), - check (f := rangeOf) (@convertExpr Z R _ _ _ _ E) = true - -> bcheck (f := ZtoB) E = true. - Proof. - intros t E H. - induction E as [tx ty tz op x y z eC IH| t a]. - - - unfold bcheck, getBounds, check in *. - - simpl; apply IH; clear IH; rewrite <- H; clear H. - simpl; rewrite convertArg_var; repeat f_equal. - - unfold interp_binop, RE, WE, BE, ZE, - BoundedEvaluable, RWVEvaluable, ZEvaluable, - eadd, emul, esub, eshiftr, eand. - - admit. - - (*induction op; rewrite check_spec'; reflexivity. *) - - - unfold bcheck, getBounds, check in *. - - induction a as [a|a|t0 t1 a0 IHa0 a1 IHa1]. - - + admit. - - - + unfold rangeOf in *. - simpl in *; kill_dec; try reflexivity; try inversion H. - admit. - - + simpl in *; rewrite IHa0, IHa1; simpl; [reflexivity | | ]; - apply andb_true_iff in H; destruct H as [H1 H2]; - assumption. - Admitted. - - Lemma RangeInterp_spec: forall {t} (E: @expr Z Z t), - check (f := rangeOf) (@convertExpr Z R _ _ _ _ E) = true - -> typeMap (fun x => NToWord n (Z.to_N x)) (zinterp E) - = wordInterp (ZToWord _ E). - Proof using Type. - intros. - apply RangeInterp_bounded_spec. - apply check_spec. - assumption. - Qed. - End RWVSpec. - End Correctness. -End LLConversions. diff --git a/src/Assembly/Evaluables.v b/src/Assembly/Evaluables.v deleted file mode 100644 index 433915da3..000000000 --- a/src/Assembly/Evaluables.v +++ /dev/null @@ -1,782 +0,0 @@ -Require Import Bedrock.Word Bedrock.Nomega. -Require Import Coq.Numbers.Natural.Peano.NPeano Coq.NArith.NArith Coq.PArith.PArith Coq.NArith.Ndigits Coq.ZArith.ZArith Coq.ZArith.Znat Coq.ZArith.ZArith_dec Coq.NArith.Ndec. -Require Import Coq.Lists.List Coq.Program.Basics Crypto.Util.Bool Crypto.Tactics.Algebra_syntax.Nsatz Coq.Bool.Sumbool Coq.Init.Datatypes. -Require Import Crypto.ModularArithmetic.ModularBaseSystemOpt. -Require Import Crypto.Assembly.QhasmUtil Crypto.Assembly.WordizeUtil Crypto.Assembly.Bounds. -Require Import Coq.Logic.ProofIrrelevance. - -Import ListNotations. - -Section BaseTypes. - Inductive Range T := | range: forall (low high: T), Range T. - - Record RangeWithValue := rwv { - rwv_low: N; - rwv_value: N; - rwv_high: N - }. - - Record BoundedWord {n} := bounded { - bw_low: N; - bw_value: word n; - bw_high: N; - - ge_low: (bw_low <= wordToN bw_value)%N; - le_high: (wordToN bw_value <= bw_high)%N; - high_bound: (bw_high < Npow2 n)%N - }. -End BaseTypes. - -Section Evaluability. - Class Evaluable T := evaluator { - ezero: T; - - (* Conversions *) - toT: option RangeWithValue -> T; - fromT: T -> option RangeWithValue; - - (* Operations *) - eadd: T -> T -> T; - esub: T -> T -> T; - emul: T -> T -> T; - eshiftr: T -> T -> T; - eand: T -> T -> T; - - (* Comparisons *) - eltb: T -> T -> bool; - eeqb: T -> T -> bool - }. -End Evaluability. - -Section Z. - Context {n: nat}. - - Instance ZEvaluable : Evaluable Z := { - ezero := 0%Z; - - (* Conversions *) - toT := fun x => Z.of_N (orElse 0%N (option_map rwv_value x)); - fromT := fun x => Some (rwv (Z.to_N x) (Z.to_N x) (Z.to_N x)); - - (* Operations *) - eadd := Z.add; - esub := Z.sub; - emul := Z.mul; - eshiftr := Z.shiftr; - eand := Z.land; - - (* Comparisons *) - eltb := Z.ltb; - eeqb := Z.eqb - }. - - Instance ConstEvaluable : Evaluable Z := { - ezero := 0%Z; - - (* Conversions *) - toT := fun x => Z.of_N (orElse 0%N (option_map rwv_value x)); - fromT := fun x => - if (Nge_dec (N.pred (Npow2 n)) (Z.to_N x)) - then Some (rwv (Z.to_N x) (Z.to_N x) (Z.to_N x)) - else None; - - (* Operations *) - eadd := Z.add; - esub := Z.sub; - emul := Z.mul; - eshiftr := Z.shiftr; - eand := Z.land; - - (* Comparisons *) - eltb := Z.ltb; - eeqb := Z.eqb - }. - - Instance InputEvaluable : Evaluable Z := { - ezero := 0%Z; - - (* Conversions *) - toT := fun x => Z.of_N (orElse 0%N (option_map rwv_value x)); - fromT := fun x => Some (rwv 0%N (Z.to_N x) (Z.to_N x)); - - (* Operations *) - eadd := Z.add; - esub := Z.sub; - emul := Z.mul; - eshiftr := Z.shiftr; - eand := Z.land; - - (* Comparisons *) - eltb := Z.ltb; - eeqb := Z.eqb - }. -End Z. - -Section Word. - Context {n: nat}. - - Instance WordEvaluable : Evaluable (word n) := { - ezero := wzero n; - - (* Conversions *) - toT := fun x => @NToWord n (orElse 0%N (option_map rwv_value x)); - fromT := fun x => let v := @wordToN n x in (Some (rwv v v v)); - - (* Operations *) - eadd := @wplus n; - esub := @wminus n; - emul := @wmult n; - eshiftr := fun x y => @shiftr n x (wordToNat y); - eand := @wand n; - - (* Comparisons *) - eltb := fun x y => N.ltb (wordToN x) (wordToN y); - eeqb := fun x y => proj1_sig (bool_of_sumbool (@weq n x y)) - }. -End Word. - -Section RangeUpdate. - Context {n: nat}. - - Definition validBinaryWordOp - (rangeF: Range N -> Range N -> option (Range N)) - (wordF: word n -> word n -> word n): Prop := - forall (low0 high0 low1 high1: N) (x y: word n), - (low0 <= wordToN x)%N -> (wordToN x <= high0)%N -> (high0 < Npow2 n)%N - -> (low1 <= wordToN y)%N -> (wordToN y <= high1)%N -> (high1 < Npow2 n)%N - -> match rangeF (range N low0 high0) (range N low1 high1) with - | Some (range low2 high2) => - (low2 <= @wordToN n (wordF x y))%N - /\ (@wordToN n (wordF x y) <= high2)%N - /\ (high2 < Npow2 n)%N - | _ => True - end. - - Section BoundedSub. - Lemma NToWord_Npow2: wzero n = NToWord n (Npow2 n). - Proof using Type. - induction n as [|n0]. - - + repeat rewrite shatter_word_0; reflexivity. - - + unfold wzero in *; simpl in *. - rewrite IHn0; simpl. - induction (Npow2 n0); simpl; reflexivity. - Qed. - - Lemma bWSub_lem: forall (x0 x1: word n) (low0 high1: N), - (low0 <= wordToN x0)%N -> (wordToN x1 <= high1)%N -> - (low0 - high1 <= & (x0 ^- x1))%N. - Proof using Type. - intros. - - destruct (Nge_dec (wordToN x1) 1)%N as [e|e]. - destruct (Nge_dec (wordToN x1) (wordToN x0)). - - - unfold wminus, wneg. - assert (low0 <= high1)%N. { - transitivity (wordToN x0); [assumption|]. - transitivity (wordToN x1); [apply N.ge_le|]; assumption. - } - - replace (low0 - high1)%N with 0%N; [apply N_ge_0|]. - symmetry. - apply N.sub_0_le. - assumption. - - - transitivity (wordToN x0 - wordToN x1)%N. - - + transitivity (wordToN x0 - high1)%N; - [apply N.sub_le_mono_r | apply N.sub_le_mono_l]; - assumption. - - + assert (& x0 - & x1 < Npow2 n)%N. { - transitivity (wordToN x0); - try apply word_size_bound; - apply N.sub_lt. - - + apply N.lt_le_incl; assumption. - - + nomega. - } - - assert (& x0 - & x1 + & x1 < Npow2 n)%N. { - replace (wordToN x0 - wordToN x1 + wordToN x1)%N - with (wordToN x0) by nomega. - apply word_size_bound. - } - - assert (x0 = NToWord n (wordToN x0 - wordToN x1) ^+ x1) as Hv. { - apply NToWord_equal. - rewrite <- wordize_plus; rewrite wordToN_NToWord; - try assumption. - nomega. - } - - apply N.eq_le_incl. - rewrite Hv. - unfold wminus. - rewrite <- wplus_assoc. - rewrite wminus_inv. - rewrite (wplus_comm (NToWord n (wordToN x0 - wordToN x1)) (wzero n)). - rewrite wplus_unit. - rewrite <- wordize_plus; [nomega|]. - rewrite wordToN_NToWord; assumption. - - - unfold wminus, wneg. - assert (wordToN x1 = 0)%N as e' by nomega. - rewrite e'. - replace (Npow2 n - 0)%N with (Npow2 n) by nomega. - rewrite <- NToWord_Npow2. - - erewrite <- wordize_plus; - try rewrite wordToN_zero; - replace (wordToN x0 + 0)%N with (wordToN x0)%N by nomega; - try apply word_size_bound. - - transitivity low0; try assumption. - apply N.le_sub_le_add_r. - apply N.le_add_r. - Qed. - End BoundedSub. - - Section LandOnes. - Definition getBits (x: N) := N.succ (N.log2 x). - - Lemma land_intro_ones: forall x, x = N.land x (N.ones (getBits x)). - Proof using Type. - intros. - rewrite N.land_ones_low; [reflexivity|]. - unfold getBits; nomega. - Qed. - - Lemma land_lt_Npow2: forall x k, (N.land x (N.ones k) < 2 ^ k)%N. - Proof using Type. - intros. - rewrite N.land_ones. - apply N.mod_lt. - rewrite <- (N2Nat.id k). - rewrite <- Npow2_N. - apply N.neq_0_lt_0. - apply Npow2_gt0. - Qed. - - Lemma land_prop_bound_l: forall a b, (N.land a b < Npow2 (N.to_nat (getBits a)))%N. - Proof using Type. - intros; rewrite Npow2_N. - rewrite (land_intro_ones a). - rewrite <- N.land_comm. - rewrite N.land_assoc. - rewrite N2Nat.id. - apply (N.lt_le_trans _ (2 ^ (getBits a))%N _); [apply land_lt_Npow2|]. - rewrite <- (N2Nat.id (getBits a)). - rewrite <- (N2Nat.id (getBits (N.land _ _))). - repeat rewrite <- Npow2_N. - rewrite N2Nat.id. - apply Npow2_ordered. - apply to_nat_le. - apply N.eq_le_incl; f_equal. - apply land_intro_ones. - Qed. - - Lemma land_prop_bound_r: forall a b, (N.land a b < Npow2 (N.to_nat (getBits b)))%N. - Proof using Type. - intros; rewrite N.land_comm; apply land_prop_bound_l. - Qed. - End LandOnes. - - Lemma range_add_valid : - validBinaryWordOp - (fun range0 range1 => - match (range0, range1) with - | (range low0 high0, range low1 high1) => - if (overflows n (high0 + high1)) - then None - else Some (range N (low0 + low1) (high0 + high1)) - end)%N - (@wplus n). - Proof using Type. - unfold validBinaryWordOp; intros. - - destruct (overflows n (high0 + high1))%N; repeat split; try assumption. - - - rewrite <- wordize_plus. - - + apply N.add_le_mono; assumption. - - + apply (N.le_lt_trans _ (high0 + high1)%N _); [|assumption]. - apply N.add_le_mono; assumption. - - - transitivity (wordToN x + wordToN y)%N; [apply plus_le|]. - apply N.add_le_mono; assumption. - Qed. - - Lemma range_sub_valid : - validBinaryWordOp - (fun range0 range1 => - match (range0, range1) with - | (range low0 high0, range low1 high1) => - if (Nge_dec low0 high1) - then Some (range N (low0 - high1)%N - (if (Nge_dec high0 (Npow2 n)) then N.pred (Npow2 n) else - if (Nge_dec high1 (Npow2 n)) then N.pred (Npow2 n) else - high0 - low1)%N) - else None - end) - (@wminus n). - Proof using Type. - unfold validBinaryWordOp; intros. - - Ltac kill_preds := - repeat match goal with - | [|- (N.pred _ < _)%N] => - rewrite <- (N.pred_succ (Npow2 n)); - apply -> N.pred_lt_mono; instantiate; - rewrite N.pred_succ; - [ apply N.lt_succ_diag_r - | apply N.neq_0_lt_0; apply Npow2_gt0] - | [|- (wordToN _ <= N.pred _)%N] => apply N.lt_le_pred - end. - - destruct (Nge_dec high0 (Npow2 n)), - (Nge_dec high1 (Npow2 n)), - (Nge_dec low0 high1); - repeat split; kill_preds; - repeat match goal with - | [|- (wordToN _ < Npow2 _)%N] => apply word_size_bound - | [|- (?x - _ < Npow2)%N] => transitivity x; [nomega|] - | [|- (_ - ?x <= wordToN _)%N] => apply bWSub_lem - | [|- (wordToN _ <= _ - _)%N] => eapply wminus_bound - | [|- (0 <= _)%N] => apply N_ge_0 - end; try eassumption. - - - apply N.le_ge. - transitivity high1; [assumption|]. - transitivity low0; [|assumption]. - apply N.ge_le; assumption. - - - apply (N.le_lt_trans _ high0 _); [|assumption]. - replace high0 with (high0 - 0)%N by nomega. - replace' (high0 - 0)%N with high0 at 1 by nomega. - apply N.sub_le_mono_l. - apply N.ge_le; nomega. - Qed. - - Lemma range_mul_valid : - validBinaryWordOp - (fun range0 range1 => - match (range0, range1) with - | (range low0 high0, range low1 high1) => - if (overflows n (high0 * high1)) then None else - Some (range N (low0 * low1) (high0 * high1))%N - end) - (@wmult n). - Proof using Type. - unfold validBinaryWordOp; intros. - destruct (overflows n (high0 * high1))%N; repeat split. - - - rewrite <- wordize_mult. - - + apply N.mul_le_mono; assumption. - - + apply (N.le_lt_trans _ (high0 * high1)%N _); [|assumption]. - apply N.mul_le_mono; assumption. - - - transitivity (wordToN x * wordToN y)%N; [apply mult_le|]. - apply N.mul_le_mono; assumption. - - - assumption. - Qed. - - Lemma range_shiftr_valid : - validBinaryWordOp - (fun range0 range1 => - match (range0, range1) with - | (range low0 high0, range low1 high1) => - Some (range N (N.shiftr low0 high1) ( - if (Nge_dec high0 (Npow2 n)) - then (N.pred (Npow2 n)) - else (N.shiftr high0 low1)))%N - end) - (fun x k => extend (Nat.eq_le_incl _ _ eq_refl) (shiftr x (wordToNat k))). - Proof using Type. - unfold validBinaryWordOp; intros. - repeat split; unfold extend; try rewrite wordToN_convS, wordToN_zext. - - - rewrite <- wordize_shiftr. - rewrite <- Nshiftr_equiv_nat. - repeat rewrite N.shiftr_div_pow2. - transitivity (wordToN x / 2 ^ high1)%N. - - + apply N.div_le_mono; [|assumption]. - rewrite <- (N2Nat.id high1). - rewrite <- Npow2_N. - apply N.neq_0_lt_0. - apply Npow2_gt0. - - + apply N.div_le_compat_l; split. - - * rewrite <- Npow2_N; apply Npow2_gt0. - - * rewrite <- (N2Nat.id high1). - repeat rewrite <- Npow2_N. - apply Npow2_ordered. - rewrite <- (Nat2N.id (wordToNat y)). - apply to_nat_le. - rewrite <- wordToN_nat. - assumption. - - - destruct (Nge_dec high0 (Npow2 n)); - [apply N.lt_le_pred; apply word_size_bound |]. - - etransitivity; [eapply shiftr_bound'; eassumption|]. - - rewrite <- (Nat2N.id (wordToNat y)). - rewrite <- Nshiftr_equiv_nat. - rewrite N2Nat.id. - rewrite <- wordToN_nat. - repeat rewrite N.shiftr_div_pow2. - - apply N.div_le_compat_l; split; - rewrite <- (N2Nat.id low1); - [| rewrite <- (N2Nat.id (wordToN y))]; - repeat rewrite <- Npow2_N; - [apply Npow2_gt0 |]. - apply Npow2_ordered. - apply to_nat_le. - assumption. - - - destruct (Nge_dec high0 (Npow2 n)). - - + rewrite <- (N.pred_succ (Npow2 n)). - apply -> N.pred_lt_mono; instantiate; - rewrite (N.pred_succ (Npow2 n)); - [nomega|]. - apply N.neq_0_lt_0. - apply Npow2_gt0. - - + eapply N.le_lt_trans; [|eassumption]. - rewrite N.shiftr_div_pow2. - apply N.div_le_upper_bound. - - * induction low1; simpl; intro Z; inversion Z. - - * replace' high0 with (1 * high0)%N at 1 - by (rewrite N.mul_comm; nomega). - apply N.mul_le_mono; [|reflexivity]. - rewrite <- (N2Nat.id low1). - rewrite <- Npow2_N. - apply Npow2_ge1. - Qed. - - Lemma range_and_valid : - validBinaryWordOp - (fun range0 range1 => - match (range0, range1) with - | (range low0 high0, range low1 high1) => - let upper := (N.pred (Npow2 (min (N.to_nat (getBits high0)) (N.to_nat (getBits high1)))))%N in - Some (range N 0%N (if (Nge_dec upper (Npow2 n)) then (N.pred (Npow2 n)) else upper)) - end) - (@wand n). - Proof using Type. - unfold validBinaryWordOp; intros. - repeat split; [apply N_ge_0 | |]. - destruct (lt_dec (N.to_nat (getBits high0)) (N.to_nat (getBits high1))), - (Nge_dec _ (Npow2 n)); - try apply N.lt_le_pred; - try apply word_size_bound. - - - rewrite min_l; [|omega]. - rewrite wordize_and. - apply (N.lt_le_trans _ (Npow2 (N.to_nat (getBits (wordToN x)))) _); - [apply land_prop_bound_l|]. - apply Npow2_ordered. - apply to_nat_le. - unfold getBits. - apply N.le_pred_le_succ. - rewrite N.pred_succ. - apply N.log2_le_mono. - assumption. - - - rewrite min_r; [|omega]. - rewrite wordize_and. - apply (N.lt_le_trans _ (Npow2 (N.to_nat (getBits (wordToN y)))) _); - [apply land_prop_bound_r|]. - apply Npow2_ordered. - apply to_nat_le. - unfold getBits. - apply N.le_pred_le_succ. - rewrite N.pred_succ. - apply N.log2_le_mono. - assumption. - - - destruct (Nge_dec _ (Npow2 n)); [|assumption]. - - rewrite <- (N.pred_succ (Npow2 n)). - apply -> N.pred_lt_mono; instantiate; - rewrite (N.pred_succ (Npow2 n)); - [nomega|]. - apply N.neq_0_lt_0. - apply Npow2_gt0. - Qed. -End RangeUpdate. - -Section BoundedWord. - Context {n: nat}. - - Definition BW := @BoundedWord n. - Transparent BW. - - Definition bapp {rangeF wordF} - (op: @validBinaryWordOp n rangeF wordF) - (X Y: BW): option BW. - - refine ( - let op' := op _ _ _ _ _ _ - (ge_low X) (le_high X) (high_bound X) - (ge_low Y) (le_high Y) (high_bound Y) in - - let result := rangeF - (range N (bw_low X) (bw_high X)) - (range N (bw_low Y) (bw_high Y)) in - - match result as r' return result = r' -> _ with - | Some (range low high) => fun e => - Some (@bounded n low (wordF (bw_value X) (bw_value Y)) high _ _ _) - | None => fun _ => None - end eq_refl); abstract ( - - pose proof op' as p; clear op'; - unfold result in *; - rewrite e in p; - destruct p as [p0 p1]; destruct p1 as [p1 p2]; - assumption). - Defined. - - Definition rapp {rangeF wordF} - (op: @validBinaryWordOp n rangeF wordF) - (X Y: Range N): option (Range N) := - rangeF X Y. - - Definition vapp {rangeF wordF} - (op: @validBinaryWordOp n rangeF wordF) - (X Y: word n): option (word n) := - Some (wordF X Y). - - Definition bwToRWV (w: BW): RangeWithValue := - rwv (bw_low w) (wordToN (bw_value w)) (bw_high w). - - Definition bwFromRWV (r: RangeWithValue): option BW. - refine - match r with - | rwv l v h => - match (Nge_dec h v, Nge_dec v l, Nge_dec (N.pred (Npow2 n)) h) with - | (left p0, left p1, left p2) => Some (@bounded n l (NToWord n l) h _ _ _) - | _ => None - end - end; try rewrite wordToN_NToWord; - - assert (N.succ h <= Npow2 n)%N by abstract ( - apply N.ge_le in p2; - rewrite <- (N.pred_succ h) in p2; - apply -> N.le_pred_le_succ in p2; - rewrite N.succ_pred in p2; [assumption |]; - apply N.neq_0_lt_0; - apply Npow2_gt0); - - try abstract (apply (N.lt_le_trans _ (N.succ h) _); - [nomega|assumption]); - - [reflexivity| etransitivity; apply N.ge_le; eassumption]. - Defined. - - Definition bwToRange (w: BW): Range N := - range N (bw_low w) (bw_high w). - - Definition bwFromRange (r: Range N): option BW. - refine - match r with - | range l h => - match (Nge_dec h l, Nge_dec (N.pred (Npow2 n)) h) with - | (left p0, left p1) => Some (@bounded n l (NToWord n l) h _ _ _) - | _ => None - end - end; try rewrite wordToN_NToWord; - - assert (N.succ h <= Npow2 n)%N by abstract ( - apply N.ge_le in p1; - rewrite <- (N.pred_succ h) in p1; - apply -> N.le_pred_le_succ in p1; - rewrite N.succ_pred in p1; [assumption |]; - apply N.neq_0_lt_0; - apply Npow2_gt0); - - try abstract (apply (N.lt_le_trans _ (N.succ h) _); - [nomega|assumption]); - - [reflexivity|apply N.ge_le; assumption]. - Defined. - - Definition just (x: N): option BW. - refine - match Nge_dec (N.pred (Npow2 n)) x with - | left p => Some (@bounded n x (NToWord n x) x _ _ _) - | right _ => None - end; try rewrite wordToN_NToWord; try reflexivity; - - assert (N.succ x <= Npow2 n)%N by abstract ( - apply N.ge_le in p; - rewrite <- (N.pred_succ x) in p; - apply -> N.le_pred_le_succ in p; - rewrite N.succ_pred in p; [assumption |]; - apply N.neq_0_lt_0; - apply Npow2_gt0); - - try abstract ( - apply (N.lt_le_trans _ (N.succ x) _); - [nomega|assumption]). - Defined. - - Lemma just_None_spec: forall x, just x = None -> (x >= Npow2 n)%N. - Proof using Type. - intros x H; unfold just in *. - destruct (Nge_dec (N.pred (Npow2 n)) x) as [p|p]; [inversion H |]. - rewrite <- (N.pred_succ x) in p. - apply N.lt_pred_lt_succ in p. - rewrite N.succ_pred in p; [|apply N.neq_0_lt_0; nomega]. - apply N.le_succ_l in p. - apply N.le_ge; apply N.succ_le_mono; assumption. - Qed. - - Lemma just_value_spec: forall x b, just x = Some b -> bw_value b = NToWord n x. - Proof using Type. - intros x b H; destruct b; unfold just in *; - destruct (Nge_dec (N.pred (Npow2 n)) x); - simpl in *; inversion H; subst; reflexivity. - Qed. - - Lemma just_low_spec: forall x b, just x = Some b -> bw_low b = x. - Proof using Type. - intros x b H; destruct b; unfold just in *; - destruct (Nge_dec (N.pred (Npow2 n)) x); - simpl in *; inversion H; subst; reflexivity. - Qed. - - Lemma just_high_spec: forall x b, just x = Some b -> bw_high b = x. - Proof using Type. - intros x b H; destruct b; unfold just in *; - destruct (Nge_dec (N.pred (Npow2 n)) x); - simpl in *; inversion H; subst; reflexivity. - Qed. - - Definition any: BW. - refine (@bounded n 0%N (wzero n) (N.pred (Npow2 n)) _ _ _); - try rewrite wordToN_zero; - try reflexivity; - try abstract (apply N.lt_le_pred; apply Npow2_gt0). - - apply N.lt_pred_l; apply N.neq_0_lt_0; apply Npow2_gt0. - Defined. - - Instance BoundedEvaluable : Evaluable (option BW) := { - ezero := Some any; - - toT := fun x => omap x bwFromRWV; - fromT := option_map bwToRWV; - - eadd := fun x y => omap x (fun X => omap y (fun Y => bapp range_add_valid X Y)); - esub := fun x y => omap x (fun X => omap y (fun Y => bapp range_sub_valid X Y)); - emul := fun x y => omap x (fun X => omap y (fun Y => bapp range_mul_valid X Y)); - eshiftr := fun x y => omap x (fun X => omap y (fun Y => bapp range_shiftr_valid X Y)); - eand := fun x y => omap x (fun X => omap y (fun Y => bapp range_and_valid X Y)); - - eltb := fun x y => - orElse false (omap x (fun X => omap y (fun Y => - Some (N.ltb (wordToN (bw_value X)) (wordToN (bw_value Y)))))); - - eeqb := fun x y => - orElse false (omap x (fun X => omap y (fun Y => - Some (N.eqb (wordToN (bw_value X)) (wordToN (bw_value Y)))))) - }. -End BoundedWord. - -Section RangeWithValue. - Context {n: nat}. - - Definition rwv_app {rangeF wordF} - (op: @validBinaryWordOp n rangeF wordF) - (X Y: RangeWithValue): option (RangeWithValue) := - omap (rangeF (range N (rwv_low X) (rwv_high X)) - (range N (rwv_low Y) (rwv_high Y))) (fun r' => - match r' with - | range l h => Some ( - rwv l (wordToN (wordF (NToWord n (rwv_value X)) - (NToWord n (rwv_value Y)))) h) - end). - - Definition checkRWV (x: RangeWithValue): bool := - match x with - | rwv l v h => - match (Nge_dec h v, Nge_dec v l, Nge_dec (N.pred (Npow2 n)) h) with - | (left _, left _, left _) => true - | _ => false - end - end. - - Lemma rwv_None_spec : forall {rangeF wordF} - (op: @validBinaryWordOp n rangeF wordF) - (X Y: RangeWithValue), - omap (rwv_app op X Y) (bwFromRWV (n := n)) <> None. - Proof. - Admitted. - - Definition rwvToRange (x: RangeWithValue): Range N := - range N (rwv_low x) (rwv_high x). - - Definition rwvFromRange (x: Range N): RangeWithValue := - match x with - | range l h => rwv l h h - end. - - Lemma bwToFromRWV: forall x, option_map (@bwToRWV n) (omap x bwFromRWV) = x. - Proof. - Admitted. - - Instance RWVEvaluable : Evaluable (option RangeWithValue) := { - ezero := None; - - toT := fun x => x; - fromT := fun x => omap x (fun x' => if (checkRWV x') then x else None); - - eadd := fun x y => omap x (fun X => omap y (fun Y => - rwv_app range_add_valid X Y)); - - esub := fun x y => omap x (fun X => omap y (fun Y => - rwv_app range_sub_valid X Y)); - - emul := fun x y => omap x (fun X => omap y (fun Y => - rwv_app range_mul_valid X Y)); - - eshiftr := fun x y => omap x (fun X => omap y (fun Y => - rwv_app range_shiftr_valid X Y)); - - eand := fun x y => omap x (fun X => omap y (fun Y => - rwv_app range_and_valid X Y)); - - eltb := fun x y => - match (x, y) with - | (Some (rwv xlow xv xhigh), Some (rwv ylow yv yhigh)) => - N.ltb xv yv - - | _ => false - end; - - eeqb := fun x y => - match (x, y) with - | (Some (rwv xlow xv xhigh), Some (rwv ylow yv yhigh)) => - andb (andb (N.eqb xlow ylow) (N.eqb xhigh yhigh)) (N.eqb xv yv) - - | _ => false - end - }. -End RangeWithValue. diff --git a/src/Assembly/GF25519.v b/src/Assembly/GF25519.v deleted file mode 100644 index a904f14b1..000000000 --- a/src/Assembly/GF25519.v +++ /dev/null @@ -1,313 +0,0 @@ -Require Import Coq.ZArith.Znat. -Require Import Coq.ZArith.ZArith. - -Require Import Crypto.Assembly.Pipeline. -Require Import Crypto.Spec.ModularArithmetic. -Require Import Crypto.ModularArithmetic.ModularBaseSystem. -Require Import Crypto.Specific.GF25519. -Require Import Crypto.Util.Tuple. - -Require InitialRing. - -Module GF25519. - Definition bits: nat := 64. - Definition width: Width bits := W64. - - Existing Instance ZEvaluable. - - Fixpoint makeBoundList {n} k (b: @BoundedWord n) := - match k with - | O => nil - | S k' => cons b (makeBoundList k' b) - end. - - Section DefaultBounds. - Import ListNotations. - - Local Notation rr exp := (2^exp + 2^(exp-3))%Z. - - Definition feBound: list Z := - [rr 26; rr 27; rr 26; rr 27; rr 26; - rr 27; rr 26; rr 27; rr 26; rr 27]. - End DefaultBounds. - - Definition FE: type. - Proof. - let T := eval vm_compute in fe25519 in - let t := HL.reify_type T in - exact t. - Defined. - - Section Expressions. - Definition flatten {T}: (@interp_type Z FE -> T) -> NAry 10 Z T. - intro F; refine (fun (a b c d e f g h i j: Z) => - F (a, b, c, d, e, f, g, h, i, j)). - Defined. - - Definition unflatten {T}: - (forall a b c d e f g h i j : Z, T (a, b, c, d, e, f, g, h, i, j)) - -> (forall x: @interp_type Z FE, T x). - Proof. - intro F; refine (fun (x: @interp_type Z FE) => - let '(a, b, c, d, e, f, g, h, i, j) := x in - F a b c d e f g h i j). - Defined. - - Ltac intro_vars_for R := revert R; - match goal with - | [ |- forall x, @?T x ] => apply (@unflatten T); intros - end. - - Definition ge25519_add_expr := - Eval cbv beta delta [fe25519 carry_add mul carry_sub opp Let_In] in carry_add. - - Definition ge25519_sub_expr := - Eval cbv beta delta [fe25519 carry_add mul carry_sub opp Let_In] in carry_sub. - - Definition ge25519_mul_expr := - Eval cbv beta delta [fe25519 carry_add mul carry_sub opp Let_In] in mul. - - Definition ge25519_opp_expr := - Eval cbv beta delta [fe25519 carry_add mul carry_sub opp Let_In] in opp. - - Definition ge25519_add' (P Q: @interp_type Z FE): - { r: @HL.Expr Z FE | HL.Interp r = ge25519_add_expr P Q }. - Proof. - intro_vars_for P. - intro_vars_for Q. - - eexists. - - cbv beta delta [ge25519_add_expr]. - - etransitivity; [reflexivity|]. - - let R := HL.rhs_of_goal in - let X := HL.Reify R in - transitivity (HL.Interp (X bits)); [reflexivity|]. - - cbv iota beta delta [ HL.Interp - interp_type interp_binop HL.interp - Z.land ZEvaluable eadd esub emul eshiftr eand]. - - reflexivity. - Defined. - - Definition ge25519_sub' (P Q: @interp_type Z FE): - { r: @HL.Expr Z FE | HL.Interp r = ge25519_sub_expr P Q }. - Proof. - intro_vars_for P. - intro_vars_for Q. - - eexists. - - cbv beta delta [ge25519_sub_expr]. - - etransitivity; [reflexivity|]. - - let R := HL.rhs_of_goal in - let X := HL.Reify R in - transitivity (HL.Interp (X bits)); [reflexivity|]. - - cbv iota beta delta [ HL.Interp - interp_type interp_binop HL.interp - Z.land ZEvaluable eadd esub emul eshiftr eand]. - - reflexivity. - Defined. - - Definition ge25519_mul' (P Q: @interp_type Z FE): - { r: @HL.Expr Z FE | HL.Interp r = ge25519_mul_expr P Q }. - Proof. - intro_vars_for P. - intro_vars_for Q. - - eexists. - - cbv beta delta [ge25519_mul_expr]. - - etransitivity; [reflexivity|]. - - let R := HL.rhs_of_goal in - let X := HL.Reify R in - transitivity (HL.Interp (X bits)); [reflexivity|]. - - cbv iota beta delta [ HL.Interp - interp_type interp_binop HL.interp - Z.land ZEvaluable eadd esub emul eshiftr eand]. - - reflexivity. - Defined. - - Definition ge25519_opp' (P: @interp_type Z FE): - { r: @HL.Expr Z FE | HL.Interp r = ge25519_opp_expr P }. - Proof. - intro_vars_for P. - - eexists. - - cbv beta delta [ge25519_opp_expr zero_]. - - etransitivity; [reflexivity|]. - - let R := HL.rhs_of_goal in - let X := HL.Reify R in - transitivity (HL.Interp (X bits)); [reflexivity|]. - - cbv iota beta delta [ HL.Interp - interp_type interp_binop HL.interp - Z.land ZEvaluable eadd esub emul eshiftr eand]. - - reflexivity. - Defined. - - Definition ge25519_add (P Q: @interp_type Z FE) := - proj1_sig (ge25519_add' P Q). - - Definition ge25519_sub (P Q: @interp_type Z FE) := - proj1_sig (ge25519_sub' P Q). - - Definition ge25519_mul (P Q: @interp_type Z FE) := - proj1_sig (ge25519_mul' P Q). - - Definition ge25519_opp (P: @interp_type Z FE) := - proj1_sig (ge25519_opp' P). - End Expressions. - - Module AddExpr <: Expression. - Definition bits: nat := bits. - Definition inputs: nat := 20. - Definition width: Width bits := width. - Definition ResultType := FE. - Definition inputBounds := feBound ++ feBound. - - Definition prog: NAry 20 Z (@HL.Expr Z ResultType) := - Eval cbv in (flatten (fun p => (flatten (fun q => ge25519_add p q)))). - End AddExpr. - - Module SubExpr <: Expression. - Definition bits: nat := bits. - Definition inputs: nat := 20. - Definition width: Width bits := width. - Definition ResultType := FE. - Definition inputBounds := feBound ++ feBound. - - Definition ge25519_sub_expr := - Eval cbv beta delta [fe25519 carry_add mul carry_sub opp Let_In] in - carry_sub. - - Definition prog: NAry 20 Z (@HL.Expr Z ResultType) := - Eval cbv in (flatten (fun p => (flatten (fun q => ge25519_sub p q)))). - End SubExpr. - - Module MulExpr <: Expression. - Definition bits: nat := bits. - Definition inputs: nat := 20. - Definition width: Width bits := width. - Definition ResultType := FE. - Definition inputBounds := feBound ++ feBound. - - Definition prog: NAry 20 Z (@HL.Expr Z ResultType) := - Eval cbv in (flatten (fun p => (flatten (fun q => ge25519_mul p q)))). - End MulExpr. - - Module OppExpr <: Expression. - Definition bits: nat := bits. - Definition inputs: nat := 10. - Definition width: Width bits := width. - Definition ResultType := FE. - Definition inputBounds := feBound. - - Definition prog: NAry 10 Z (@HL.Expr Z ResultType) := - Eval cbv in (flatten ge25519_opp). - End OppExpr. - - Module Add := Pipeline AddExpr. - Module Sub := Pipeline SubExpr. - Module Mul := Pipeline MulExpr. - Module Opp := Pipeline OppExpr. - - Section Instantiation. - Import InitialRing. - - Definition Binary : Type := NAry 20 (word bits) (@interp_type (word bits) FE). - Definition Unary : Type := NAry 10 (word bits) (@interp_type (word bits) FE). - - Ltac ast_simpl := cbv [ - Add.bits Add.inputs AddExpr.inputs Add.ResultType AddExpr.ResultType - Add.W Add.R Add.ZEvaluable Add.WEvaluable Add.REvaluable - Add.AST.progW Add.LL.progW Add.HL.progW AddExpr.prog - - Sub.bits Sub.inputs SubExpr.inputs Sub.ResultType SubExpr.ResultType - Sub.W Sub.R Sub.ZEvaluable Sub.WEvaluable Sub.REvaluable - Sub.AST.progW Sub.LL.progW Sub.HL.progW SubExpr.prog - - Mul.bits Mul.inputs MulExpr.inputs Mul.ResultType MulExpr.ResultType - Mul.W Mul.R Mul.ZEvaluable Mul.WEvaluable Mul.REvaluable - Mul.AST.progW Mul.LL.progW Mul.HL.progW MulExpr.prog - - Opp.bits Opp.inputs OppExpr.inputs Opp.ResultType OppExpr.ResultType - Opp.W Opp.R Opp.ZEvaluable Opp.WEvaluable Opp.REvaluable - Opp.AST.progW Opp.LL.progW Opp.HL.progW OppExpr.prog - - HLConversions.convertExpr CompileHL.Compile CompileHL.compile - - LL.interp LL.uninterp_arg LL.under_lets LL.interp_arg - - ZEvaluable WordEvaluable RWVEvaluable rwv_value - eadd esub emul eand eshiftr toT fromT - - interp_binop interp_type FE liftN NArgMap id - omap option_map orElse]. - - (* Tack this on to make a simpler AST, but it really slows us down *) - Ltac word_simpl := cbv [ - AddExpr.bits SubExpr.bits MulExpr.bits OppExpr.bits bits - NToWord posToWord natToWord wordToNat wordToN wzero' - Nat.mul Nat.add]. - - Ltac kill_conv := let p := fresh in - pose proof N2Z.id as p; unfold Z.to_N in p; - repeat rewrite p; clear p; - repeat rewrite NToWord_wordToN. - - Local Notation unary_eq f g - := (forall x0 x1 x2 x3 x4 x5 x6 x7 x8 x9, - f x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 - = g x0 x1 x2 x3 x4 x5 x6 x7 x8 x9). - Local Notation binary_eq f g - := (forall x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9, - f x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9 - = g x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 y0 y1 y2 y3 y4 y5 y6 y7 y8 y9). - - Definition add' - : {f: Binary | - binary_eq f (NArgMap (fun x => Z.of_N (wordToN x)) Add.AST.progW) }. - Proof. eexists; intros; ast_simpl; kill_conv; reflexivity. Defined. - - Definition sub' - : {f: Binary | - binary_eq f (NArgMap (fun x => Z.of_N (wordToN x)) Sub.AST.progW) }. - Proof. eexists; ast_simpl; kill_conv; reflexivity. Defined. - - Definition mul' - : {f: Binary | - binary_eq f (NArgMap (fun x => Z.of_N (wordToN x)) Mul.AST.progW) }. - Proof. eexists; ast_simpl; kill_conv; reflexivity. Defined. - - Definition opp' : {f: Unary | - unary_eq f (NArgMap (fun x => Z.of_N (wordToN x)) Opp.AST.progW) }. - Proof. eexists; ast_simpl; kill_conv; reflexivity. Defined. - - Definition add := Eval simpl in proj1_sig add'. - Definition sub := Eval simpl in proj1_sig sub'. - Definition mul := Eval simpl in proj1_sig mul'. - Definition opp := Eval simpl in proj1_sig opp'. - End Instantiation. -End GF25519. -(* -Extraction "GF25519Add" GF25519.Add. -Extraction "GF25519Sub" GF25519.Sub. -Extraction "GF25519Mul" GF25519.Mul. -Extraction "GF25519Opp" GF25519.Opp. -*) diff --git a/src/Assembly/HL.v b/src/Assembly/HL.v deleted file mode 100644 index e9eecd4c8..000000000 --- a/src/Assembly/HL.v +++ /dev/null @@ -1,212 +0,0 @@ -Require Import Crypto.Assembly.PhoasCommon. -Require Import Coq.setoid_ring.InitialRing. -Require Import Crypto.Util.LetIn. - -Module HL. - Definition typeMap {A B t} (f: A -> B) (x: @interp_type A t): @interp_type B t. - Proof. - induction t; [refine (f x)|]. - destruct x as [x1 x2]. - refine (IHt1 x1, IHt2 x2). - Defined. - - Section Language. - Context {T: Type}. - Context {E: Evaluable T}. - - Section expr. - Context {var : type -> Type}. - - Inductive expr : type -> Type := - | Const : forall {_ : Evaluable T}, @interp_type T TT -> expr TT - | Var : forall {t}, var t -> expr t - | Binop : forall {t1 t2 t3}, binop t1 t2 t3 -> expr t1 -> expr t2 -> expr t3 - | Let : forall {tx}, expr tx -> forall {tC}, (var tx -> expr tC) -> expr tC - | Pair : forall {t1}, expr t1 -> forall {t2}, expr t2 -> expr (Prod t1 t2) - | MatchPair : forall {t1 t2}, expr (Prod t1 t2) -> forall {tC}, (var t1 -> var t2 -> expr tC) -> expr tC. - End expr. - - Local Notation ZConst z := (@Const Z ConstEvaluable _ z%Z). - - Fixpoint interp {t} (e: @expr interp_type t) : @interp_type T t := - match e in @expr _ t return interp_type t with - | Const _ x => x - | Var _ n => n - | Binop _ _ _ op e1 e2 => interp_binop op (interp e1) (interp e2) - | Let _ ex _ eC => dlet x := interp ex in interp (eC x) - | Pair _ e1 _ e2 => (interp e1, interp e2) - | MatchPair _ _ ep _ eC => let (v1, v2) := interp ep in interp (eC v1 v2) - end. - - Definition Expr t : Type := forall var, @expr var t. - - Definition Interp {t} (e: Expr t) : interp_type t := interp (e interp_type). - End Language. - - Definition zinterp {t} E := @interp Z ZEvaluable t E. - - Definition ZInterp {t} E := @Interp Z ZEvaluable t E. - - Definition wordInterp {n t} E := @interp (word n) (@WordEvaluable n) t E. - - Definition WordInterp {n t} E := @Interp (word n) (@WordEvaluable n) t E. - - Existing Instance ZEvaluable. - - Example example_Expr : Expr TT := fun var => ( - Let (Const 7) (fun a => - Let (Let (Binop OPadd (Var a) (Var a)) (fun b => Pair (Var b) (Var b))) (fun p => - MatchPair (Var p) (fun x y => - Binop OPadd (Var x) (Var y)))))%Z. - - Example interp_example_Expr : ZInterp example_Expr = 28%Z. - Proof. reflexivity. Qed. - - (* Reification assumes the argument type is Z *) - - Ltac reify_type t := - lazymatch t with - | BinInt.Z => constr:(TT) - | prod ?l ?r => - let l := reify_type l in - let r := reify_type r in - constr:(Prod l r) - end. - - Ltac reify_binop op := - lazymatch op with - | Z.add => constr:(OPadd) - | Z.sub => constr:(OPsub) - | Z.mul => constr:(OPmul) - | Z.land => constr:(OPand) - | Z.shiftr => constr:(OPshiftr) - end. - - Class reify (n: nat) {varT} (var:varT) {eT} (e:eT) {T:Type} := Build_reify : T. - Definition reify_var_for_in_is {T} (x:T) (t:type) {eT} (e:eT) := False. - - Ltac reify n var e := - lazymatch e with - | let x := ?ex in @?eC x => - let ex := reify n var ex in - let eC := reify n var eC in - constr:(Let (T:=Z) (var:=var) ex eC) - | match ?ep with (v1, v2) => @?eC v1 v2 end => - let ep := reify n var ep in - let eC := reify n var eC in - constr:(MatchPair (T:=Z) (var:=var) ep eC) - | pair ?a ?b => - let a := reify n var a in - let b := reify n var b in - constr:(Pair (T:=Z) (var:=var) a b) - | ?op ?a ?b => - let op := reify_binop op in - let b := reify n var b in - let a := reify n var a in - constr:(Binop (T:=Z) (var:=var) op a b) - | (fun x : ?T => ?C) => - let t := reify_type T in - (* Work around Coq 8.5 and 8.6 bug *) - (* <https://coq.inria.fr/bugs/show_bug.cgi?id=4998> *) - (* Avoid re-binding the Gallina variable referenced by Ltac [x] *) - (* even if its Gallina name matches a Ltac in this tactic. *) - (* [C] here is an open term that references "x" by name *) - let maybe_x := fresh x in - let not_x := fresh x in - lazymatch constr:(fun (x : T) (not_x : var t) (_:reify_var_for_in_is x t not_x) => - (_ : reify n var C)) - with fun _ v _ => @?C v => C end - | ?x => - lazymatch goal with - | _:reify_var_for_in_is x ?t ?v |- _ => constr:(@Var Z var t v) - | _ => let x' := eval cbv in x in - match isZcst x with - | true => constr:(@Const Z var (@ConstEvaluable n) x) - | false => constr:(@Const Z var InputEvaluable x) - end - end - end. - - Hint Extern 0 (reify ?n ?var ?e) => (let e := reify n var e in eexact e) : typeclass_instances. - - Ltac Reify e := - lazymatch constr:(fun (n: nat) (var:type->Type) => (_:reify n var e)) with - (fun n var => ?C) => constr:(fun (n: nat) (var:type->Type) => C) (* copy the term but not the type cast *) - end. - - Definition zinterp_type := @interp_type Z. - Transparent zinterp_type. - - Goal forall (x : Z) (v : zinterp_type TT) (_:reify_var_for_in_is x TT v), reify (T:=Z) 16 zinterp_type ((fun x => x+x) x)%Z. - intros. - let A := (reify 16 zinterp_type (x + x + 1)%Z) in idtac A. - Abort. - - Goal False. - let z := (reify 16 zinterp_type (let x := 0 in x)%Z) in pose z. - Abort. - - Ltac lhs_of_goal := match goal with |- ?R ?LHS ?RHS => constr:(LHS) end. - Ltac rhs_of_goal := match goal with |- ?R ?LHS ?RHS => constr:(RHS) end. - - Ltac Reify_rhs n := - let rhs := rhs_of_goal in - let RHS := Reify rhs in - transitivity (ZInterp (RHS n)); - [|cbv iota beta delta [ZInterp Interp interp_type interp_binop interp]; reflexivity]. - - Goal (0 = let x := 1+2 in x*3)%Z. - Reify_rhs 32. - Abort. - - Goal (0 = let x := 1 in let y := 2 in x * y)%Z. - Reify_rhs 32. - Abort. - - Section wf. - Context {T : Type} {var1 var2 : type -> Type}. - - Local Notation "x ≡ y" := (existT _ _ (x, y)). - - Definition Texpr var t := @expr Z var t. - - Inductive wf : list (sigT (fun t => var1 t * var2 t))%type -> forall {t}, Texpr var1 t -> Texpr var2 t -> Prop := - | WfConst : forall G n, wf G (Const n) (Const n) - | WfVar : forall G t x x', In (x ≡ x') G -> @wf G t (Var x) (Var x') - | WfBinop : forall G {t1} {t2} {t3} (e1:Texpr var1 t1) (e2:Texpr var1 t2) - (e1':Texpr var2 t1) (e2':Texpr var2 t2) - (op: binop t1 t2 t3), - wf G e1 e1' - -> wf G e2 e2' - -> wf G (Binop op e1 e2) (Binop op e1' e2') - | WfLet : forall G t1 t2 e1 e1' (e2 : _ t1 -> Texpr _ t2) e2', - wf G e1 e1' - -> (forall x1 x2, wf ((x1 ≡ x2) :: G) (e2 x1) (e2' x2)) - -> wf G (Let e1 e2) (Let e1' e2') - | WfPair : forall G {t1} {t2} (e1: Texpr var1 t1) (e2: Texpr var1 t2) - (e1': Texpr var2 t1) (e2': Texpr var2 t2), - wf G e1 e1' - -> wf G e2 e2' - -> wf G (Pair e1 e2) (Pair e1' e2') - | WfMatchPair : forall G t1 t2 tC ep ep' (eC : _ t1 -> _ t2 -> Texpr _ tC) eC', - wf G ep ep' - -> (forall x1 x2 y1 y2, wf ((x1 ≡ x2) :: (y1 ≡ y2) :: G) (eC x1 y1) (eC' x2 y2)) - -> wf G (MatchPair ep eC) (MatchPair ep' eC'). - End wf. - - Definition Wf {T: Type} {t} (E : Expr t) := forall var1 var2, wf nil (E var1) (E var2). - - Example example_Expr_Wf : Wf (T := Z) example_Expr. - Proof. - unfold Wf; repeat match goal with - | [ |- wf _ _ _ ] => constructor - | [ |- In ?x (cons ?x _) ] => constructor 1; reflexivity - | [ |- In _ _ ] => constructor 2 - | _ => intros - end. - Qed. - - Axiom Wf_admitted : forall {t} (E:Expr t), @Wf Z t E. - Ltac admit_Wf := apply Wf_admitted. - -End HL. diff --git a/src/Assembly/LL.v b/src/Assembly/LL.v deleted file mode 100644 index c2faf955d..000000000 --- a/src/Assembly/LL.v +++ /dev/null @@ -1,180 +0,0 @@ -Require Import Crypto.Assembly.PhoasCommon. -Require Import Crypto.Util.LetIn. - -Local Arguments Let_In / _ _ _ _. - -Module LL. - Section Language. - Context {T: Type}. - Context {E: Evaluable T}. - - (* A very restricted language where binary operations are restricted - to returning [T] and must appear in [let] binders, and all pairs - must be constructed in the return clause. No matching on pairs is - allowed *) - - Section expr. - Context {var: Type}. - - Inductive arg : type -> Type := - | Const : @interp_type T TT -> arg TT - | Var : var -> arg TT - | Pair : forall {t1 t2}, arg t1 -> arg t2 -> arg (Prod t1 t2). - - Inductive expr : type -> Type := - | LetBinop : forall {t1 t2 t3}, binop t1 t2 t3 -> arg t1 -> arg t2 -> - forall {tC}, (arg t3 -> expr tC) -> expr tC - | Return : forall {t}, arg t -> expr t. - End expr. - - Definition Expr t := forall var, @expr var t. - - Fixpoint interp_arg' {V t} (f: V -> T) (e: arg t) : interp_type t := - match e with - | Pair _ _ x y => (interp_arg' f x, interp_arg' f y) - | Const x => x - | Var x => f x - end. - - Fixpoint interp_arg {t} (e: arg t) : interp_type t := - match e with - | Pair _ _ x y => (interp_arg x, interp_arg y) - | Const x => x - | Var x => x - end. - - Lemma interp_arg_spec: forall {t} (x: arg t), interp_arg x = interp_arg' id x. - Proof using Type. - intros; induction x; unfold id in *; simpl; repeat f_equal; - first [reflexivity| assumption]. - Qed. - - Fixpoint uninterp_arg {var t} (x: interp_type t) : @arg var t := - match t as t' return interp_type t' -> arg t' with - | Prod t0 t1 => fun x' => - match x' with - | (x0, x1) => Pair (uninterp_arg x0) (uninterp_arg x1) - end - | TT => Const - end x. - - Fixpoint uninterp_arg_as_var {var t} (x: @interp_type var t) : @arg var t := - match t as t' return @interp_type var t' -> @arg var t' with - | Prod t0 t1 => fun x' => - match x' with - | (x0, x1) => Pair (uninterp_arg_as_var x0) (uninterp_arg_as_var x1) - end - | TT => Var - end x. - - Fixpoint interp' {V t} (f: V -> T) (e:expr t) : interp_type t := - match e with - | LetBinop _ _ _ op a b _ eC => - let x := interp_binop op (interp_arg' f a) (interp_arg' f b) in interp' f (eC (uninterp_arg x)) - | Return _ a => interp_arg' f a - end. - - Fixpoint interp {t} (e:expr t) : interp_type t := - match e with - | LetBinop _ _ _ op a b _ eC => - dlet x := interp_binop op (interp_arg a) (interp_arg b) in interp (eC (uninterp_arg x)) - | Return _ a => interp_arg a - end. - - Lemma interp_spec: forall {t} (e: expr t), interp e = interp' id e. - Proof using Type. - intros; induction e; unfold id in *; simpl; repeat f_equal; - try rewrite H; simpl; repeat f_equal; - rewrite interp_arg_spec; repeat f_equal. - Qed. - End Language. - - Transparent interp interp_arg. - - Example example_expr : - (@interp Z (ZEvaluable) _ - (LetBinop OPadd (Const 7%Z) (Const 8%Z) (fun v => Return v)) = 15)%Z. - Proof. reflexivity. Qed. - - Section under_lets. - Context {T: Type}. - - Fixpoint under_lets {t var} (e: @expr T var t) {struct e} : - forall {tC} (C: @arg T var t -> @expr T var tC), @expr T var tC := - match e with - | LetBinop _ _ _ op a b tC eC => fun tC C => LetBinop op a b (fun v => @under_lets _ _ (eC v) _ C) - | Return t a => fun _ C => C a - end. - End under_lets. - - Lemma under_lets_correct {T} {E: Evaluable T} {t} (e: expr t) {tC} - (C: arg t -> expr tC) - (C_Proper : forall a1 a2, interp_arg a1 = interp_arg a2 -> interp (C a1) = interp (C a2)) : - forall a, interp_arg a = interp e -> interp (under_lets e C) = interp (C a). - Proof. induction e; repeat (intuition (congruence || eauto); simpl). Qed. - - Section match_arg. - Context {T : Type}. - - Arguments arg _ _ _ : clear implicits. - Arguments expr _ _ _ : clear implicits. - - Definition match_arg_Prod {var t1 t2} (a:arg T var (Prod t1 t2)) : (arg T var t1 * arg T var t2) := - match a with - | Pair _ _ a1 a2 => (a1, a2) - | _ => I (* dummy *) - end. - - Global Arguments match_arg_Prod / : simpl nomatch. - - Lemma match_arg_Prod_correct_helper {var t} (a: arg T var t) : - match t return arg T var t -> Prop with - | Prod _ _ => fun a => forall a1 a2, - match_arg_Prod a = (a1, a2) <-> a = Pair a1 a2 - | _ => fun _ => True - end a. - Proof using Type. - unfold match_arg_Prod; destruct a; - repeat match goal with - | _ => split - | _ => intro - | _ => progress simpl in * - | _ => break_match - | _ => intuition congruence - | H: _ |- _ => eapply (f_equal match_arg_Prod) in H - end. - Qed. - - Lemma match_arg_Prod_correct {var t1 t2} (a:arg T var (Prod t1 t2)) (a1:arg T var t1) (a2:arg T var t2) : - match_arg_Prod a = (a1, a2) <-> a = Pair a1 a2. - Proof using Type. - pose proof (match_arg_Prod_correct_helper a) as H; simpl in H; rewrite H; reflexivity. - Qed. - End match_arg. - - Lemma interp_arg_uninterp_arg : forall T t (a:interp_type t), @interp_arg T t (uninterp_arg a) = a. - Proof. - induction t as [|i0 v0 i1 v1]; simpl; intros; try reflexivity. - break_match; subst; simpl. - unfold interp_arg in *. - simpl; rewrite v0, v1; reflexivity. - Qed. - - Lemma interp_under_lets {T} {_: Evaluable T} {t: type} {tC: type} - (e: @expr T T t) - (C: @arg T T t -> @expr T T tC) - (C_Proper : forall a1 a2, interp_arg a1 = interp_arg a2 -> - interp (C a1) = interp (C a2)) : - interp (under_lets e C) = interp (C (uninterp_arg (interp e))). - Proof. - intros; apply under_lets_correct; - [ assumption - | rewrite interp_arg_uninterp_arg; reflexivity ]. - Qed. - - Lemma Pair_eq T var t0 t1 x0 x1 x0' x1' : @Pair T var t0 t1 x0 x1 = @Pair T var t0 t1 x0' x1' <-> (x0, x1) = (x0', x1'). - Proof. - split; intro H; try congruence. - apply (f_equal match_arg_Prod) in H; assumption. - Qed. -End LL. diff --git a/src/Assembly/Output.ml b/src/Assembly/Output.ml deleted file mode 100644 index d84aee0a2..000000000 --- a/src/Assembly/Output.ml +++ /dev/null @@ -1,14 +0,0 @@ - -open Result - -let list_to_string s = - let rec loop s n = - match s with - [] -> String.make n '?' - | car :: cdr -> - let result = loop cdr (n + 1) in - Bytes.set result n car; - result - in loop s 0 ;; - -print_string (list_to_string result) ;; diff --git a/src/Assembly/PhoasCommon.v b/src/Assembly/PhoasCommon.v deleted file mode 100644 index fbdc4c349..000000000 --- a/src/Assembly/PhoasCommon.v +++ /dev/null @@ -1,42 +0,0 @@ -Require Export Coq.ZArith.BinInt. -Require Export Coq.NArith.BinNat. -Require Export Coq.Bool.Bool. -Require Export Coq.Lists.List. - -Require Export Bedrock.Word Bedrock.Nomega. - -Require Export Crypto.Util.GlobalSettings. -Require Export Crypto.Util.Tactics. -Require Export Crypto.Util.Notations. -Require Export Crypto.Tactics.VerdiTactics. - -Require Export Crypto.Assembly.Evaluables. - -Section Definitions. - Context {T: Type} {E: Evaluable T}. - - Inductive type := TT | Prod : type -> type -> type. - - Fixpoint interp_type (t:type): Type := - match t with - | TT => T - | Prod a b => prod (interp_type a) (interp_type b) - end. - - Inductive binop : type -> type -> type -> Type := - | OPadd : binop TT TT TT - | OPsub : binop TT TT TT - | OPmul : binop TT TT TT - | OPand : binop TT TT TT - | OPshiftr : binop TT TT TT. - (* TODO: should [Pair] be a [binop]? *) - - Definition interp_binop {t1 t2 t} (op:binop t1 t2 t) : interp_type t1 -> interp_type t2 -> interp_type t := - match op with - | OPadd => @eadd T E - | OPsub => @esub T E - | OPmul => @emul T E - | OPand => @eand T E - | OPshiftr => @eshiftr T E - end. -End Definitions. diff --git a/src/Assembly/Pipeline.v b/src/Assembly/Pipeline.v deleted file mode 100644 index 40d5abca9..000000000 --- a/src/Assembly/Pipeline.v +++ /dev/null @@ -1,140 +0,0 @@ -Require Export Crypto.Assembly.QhasmCommon. - -Require Export Crypto.Assembly.PhoasCommon. -Require Export Crypto.Assembly.HL. -Require Export Crypto.Assembly.LL. -Require Export Crypto.Assembly.Compile. -Require Export Crypto.Assembly.Conversions. -Require Export Crypto.Assembly.StringConversion. -Require Export Crypto.Assembly.State. - -Require Export Crypto.Util.Notations. -Require Export Crypto.Util.LetIn. - -Require Export Coq.ZArith.BinInt. - -Require Export ExtrOcamlBasic. -Require Export ExtrOcamlString. - -Module Type Expression. - Parameter bits: nat. - Parameter width: Width bits. - Parameter inputs: nat. - Parameter inputBounds: list Z. - Parameter ResultType: type. - - Parameter prog: NAry inputs Z (@HL.Expr Z ResultType). -End Expression. - -Module Pipeline (Input: Expression). - Definition bits := Input.bits. - Definition inputs := Input.inputs. - Definition ResultType := Input.ResultType. - - Hint Unfold bits inputs ResultType. - Definition width: Width bits := Input.width. - - Definition W: Type := word bits. - Definition R: Type := option RangeWithValue. - Definition B: Type := option (@BoundedWord bits). - - Instance ZEvaluable : Evaluable Z := ZEvaluable. - Instance WEvaluable : Evaluable W := @WordEvaluable bits. - Instance REvaluable : Evaluable R := @RWVEvaluable bits. - Instance BEvaluable : Evaluable B := @BoundedEvaluable bits. - - Existing Instances ZEvaluable WEvaluable REvaluable BEvaluable. - - Module Util. - Fixpoint applyProgOn {A B k} (d: A) ins (f: NAry k A B): B := - match k as k' return NAry k' A B -> B with - | O => id - | S m => fun f' => - match ins with - | cons x xs => @applyProgOn A B m d xs (f' x) - | nil => @applyProgOn A B m d nil (f' d) - end - end f. - End Util. - - Module HL. - Definition progZ: NAry inputs Z (@HL.Expr Z ResultType) := - Input.prog. - - Definition progR: NAry inputs Z (@HL.Expr R ResultType) := - liftN (fun x v => @HLConversions.convertExpr Z R _ _ _ (x v)) Input.prog. - - Definition progW: NAry inputs Z (@HL.Expr W ResultType) := - liftN (fun x v => @HLConversions.convertExpr Z W _ _ _ (x v)) Input.prog. - End HL. - - Module LL. - Definition progZ: NAry inputs Z (@LL.expr Z Z ResultType) := - liftN CompileHL.Compile HL.progZ. - - Definition progR: NAry inputs Z (@LL.expr R R ResultType) := - liftN CompileHL.Compile HL.progR. - - Definition progW: NAry inputs Z (@LL.expr W W ResultType) := - liftN CompileHL.Compile HL.progW. - End LL. - - Module AST. - Definition progZ: NAry inputs Z (@interp_type Z ResultType) := - liftN LL.interp LL.progZ. - - Definition progR: NAry inputs Z (@interp_type R ResultType) := - liftN LL.interp LL.progR. - - Definition progW: NAry inputs Z (@interp_type W ResultType) := - liftN LL.interp LL.progW. - End AST. - - Module Qhasm. - Definition pair := - @CompileLL.compile bits width ResultType _ LL.progW. - - Definition prog := option_map (@fst _ _) pair. - - Definition outputRegisters := option_map (@snd _ _) pair. - - Definition code := option_map StringConversion.convertProgram prog. - End Qhasm. - - Module Bounds. - Definition input := map (fun x => range N 0%N (Z.to_N x)) Input.inputBounds. - - Definition upper := Z.of_N (wordToN (wones bits)). - - Definition prog := - Util.applyProgOn upper Input.inputBounds LL.progR. - - Definition valid := LLConversions.check (n := bits) (f := id) prog. - - Definition output := - typeMap (option_map (fun x => range N (rwv_low x) (rwv_high x))) - (LL.interp prog). - End Bounds. -End Pipeline. - -Module SimpleExample. - Module SimpleExpression <: Expression. - Import ListNotations. - - Definition bits: nat := 32. - Definition width: Width bits := W32. - Definition inputs: nat := 1. - Definition ResultType := TT. - - Definition inputBounds: list Z := [ (2^30)%Z ]. - - Existing Instance ZEvaluable. - - Definition prog: NAry 1 Z (@HL.Expr Z TT). - intros x var. - refine (HL.Binop OPadd (HL.Const x) (HL.Const 5%Z)). - Defined. - End SimpleExpression. - - Module SimplePipeline := Pipeline SimpleExpression. -End SimpleExample. diff --git a/src/Assembly/Qhasm.v b/src/Assembly/Qhasm.v deleted file mode 100644 index 9e376f71b..000000000 --- a/src/Assembly/Qhasm.v +++ /dev/null @@ -1,81 +0,0 @@ -Require Import QhasmCommon QhasmEvalCommon. -Require Import List NPeano. - -Module Qhasm. - Import ListNotations. - Import QhasmEval. - - Definition State := State. - - (* Program Types *) - Inductive QhasmStatement := - | QAssign: Assignment -> QhasmStatement - | QOp: Operation -> QhasmStatement - | QCond: Conditional -> Label -> QhasmStatement - | QLabel: Label -> QhasmStatement - | QCall: Label -> QhasmStatement - | QRet: QhasmStatement. - - Hint Constructors QhasmStatement. - - Definition Program := list QhasmStatement. - - (* Only execute while loops a fixed number of times. - TODO (rsloan): can we do any better? *) - - Fixpoint getLabelMap' (prog: Program) (cur: LabelMap) (index: nat): LabelMap := - match prog with - | p :: ps => - match p with - | QLabel label => @getLabelMap' ps (NatM.add label index cur) (S index) - | _ => @getLabelMap' ps cur (S index) - end - | [] => cur - end. - - Definition getLabelMap (prog: Program): LabelMap := - getLabelMap' prog (NatM.empty nat) O. - - Inductive QhasmEval: nat -> Program -> LabelMap -> State -> State -> Prop := - | QEOver: forall p n m s, (n > (length p))%nat -> QhasmEval n p m s s - | QEZero: forall p s m, QhasmEval O p m s s - | QEAssign: forall n p m a s s' s'', - (nth_error p n) = Some (QAssign a) - -> evalAssignment a s = Some s' - -> QhasmEval (S n) p m s' s'' - -> QhasmEval n p m s s'' - | QEOp: forall n p m a s s' s'', - (nth_error p n) = Some (QOp a) - -> evalOperation a s = Some s' - -> QhasmEval (S n) p m s' s'' - -> QhasmEval n p m s s'' - | QECondTrue: forall (n loc next: nat) p m c l s s', - (nth_error p n) = Some (QCond c l) - -> evalCond c s = Some true - -> NatM.find l m = Some loc - -> QhasmEval loc p m s s' - -> QhasmEval n p m s s' - | QECondFalse: forall (n loc next: nat) p m c l s s', - (nth_error p n) = Some (QCond c l) - -> evalCond c s = Some false - -> QhasmEval (S n) p m s s' - -> QhasmEval n p m s s' - | QERet: forall (n n': nat) s s' s'' p m, - (nth_error p n) = Some QRet - -> popRet s = Some (s', n') - -> QhasmEval n' p m s' s'' - -> QhasmEval n p m s s'' - | QECall: forall (w n n' lbl: nat) s s' s'' p m, - (nth_error p n) = Some (QCall lbl) - -> NatM.find lbl m = Some n' - -> QhasmEval n' p m (pushRet (S n) s') s'' - -> QhasmEval n p m s s'' - | QELabel: forall n p m l s s', - (nth_error p n) = Some (QLabel l) - -> QhasmEval (S n) p m s s' - -> QhasmEval n p m s s'. - - Definition evaluatesTo := fun p => @QhasmEval O p (getLabelMap p). - - (* world peace *) -End Qhasm. diff --git a/src/Assembly/QhasmCommon.v b/src/Assembly/QhasmCommon.v deleted file mode 100644 index dfb080e8c..000000000 --- a/src/Assembly/QhasmCommon.v +++ /dev/null @@ -1,149 +0,0 @@ -Require Export Coq.Strings.String Coq.Lists.List Coq.Numbers.Natural.Peano.NPeano Coq.NArith.NArith. -Require Export Bedrock.Word. - -(* Utilities *) -Definition Label := nat. - -Definition Index (limit: nat) := {x: nat | (x <= (pred limit))%nat}. -Coercion indexToNat {lim: nat} (i: Index lim): nat := proj1_sig i. - -Fixpoint NAry (n: nat) (A: Type) (B: Type): Type := - match n with - | (S m) => A -> NAry m A B - | O => B - end. - -Fixpoint liftN {n A B C} (f: B -> C) (x: NAry n A B) {struct n}: NAry n A C := - match n as n' return NAry n' A B -> NAry n' A C with - | S m => fun x' => (fun arg => liftN f (x' arg)) - | O => f - end x. - -Fixpoint NArgMap {n A B C} (f: A -> B) (x: NAry n B C) {struct n}: NAry n A C := - match n as n' return NAry n' B C -> NAry n' A C with - | S m => fun x' => (fun arg => NArgMap f (x' (f arg))) - | O => id - end x. - -Inductive Either A B := - | xleft: A -> Either A B - | xright: B -> Either A B. - -Definition convert {A B: Type} (x: A) (H: A = B): B := - eq_rect A (fun B0 : Type => B0) x B H. - -(* Asm Types *) -Inductive Width: nat -> Type := | W32: Width 32 | W64: Width 64. - -(* A constant value *) -Inductive Const: nat -> Type := - | constant: forall {n}, Width n -> word n -> Const n. - -(* A variable in any register *) -Inductive Reg: nat -> Type := - | reg: forall {n}, Width n -> nat -> Reg n. - -(* A variable on the stack. We should use this sparingly. *) -Inductive Stack: nat -> Type := - | stack: forall {n}, Width n -> nat -> Stack n. - -(* A pointer to a memory block. Called as: - mem width index length - where length is in words of size width. - - All Mem pointers will be declared as Stack arguments in the - resulting qhasm output *) -Inductive Mem: nat -> nat -> Type := - | mem: forall {n m}, Width n -> nat -> Mem n m. - -(* The state of the carry flag: - 1 = Some true - 0 = Some false - unknown = None *) -Definition Carry := option bool. - -(* Assignments *) - -Inductive Assignment : Type := - | ARegMem: forall {n m}, Reg n -> Mem n m -> Index m -> Assignment - | AMemReg: forall {n m}, Mem n m -> Index m -> Reg n -> Assignment - | AStackReg: forall {n}, Stack n -> Reg n -> Assignment - | ARegStack: forall {n}, Reg n -> Stack n -> Assignment - | ARegReg: forall {n}, Reg n -> Reg n -> Assignment - | AConstInt: forall {n}, Reg n -> Const n -> Assignment. - -(* Operations *) - -Inductive IntOp := - | IAdd: IntOp - | ISub: IntOp - | IXor: IntOp - | IAnd: IntOp - | IOr: IntOp. - -Inductive CarryOp := | AddWithCarry: CarryOp. - -Inductive DualOp := | Mult: DualOp. - -Inductive RotOp := | Shl: RotOp | Shr: RotOp. - -Inductive Operation := - | IOpConst: forall {n}, IntOp -> Reg n -> Const n -> Operation - | IOpReg: forall {n}, IntOp -> Reg n -> Reg n -> Operation - | IOpMem: forall {n m}, IntOp -> Reg n -> Mem n m -> Index m -> Operation - | IOpStack: forall {n}, IntOp -> Reg n -> Stack n -> Operation - | DOp: forall {n}, DualOp -> Reg n -> Reg n -> option (Reg n) -> Operation - | ROp: forall {n}, RotOp -> Reg n -> Index n -> Operation - | COp: forall {n}, CarryOp -> Reg n -> Reg n -> Operation. - -(* Control Flow *) - -Inductive TestOp := - | TEq: TestOp | TLt: TestOp | TLe: TestOp - | TGt: TestOp | TGe: TestOp. - -Inductive Conditional := - | CTrue: Conditional - | CZero: forall n, Reg n -> Conditional - | CReg: forall n, TestOp -> Reg n -> Reg n -> Conditional - | CConst: forall n, TestOp -> Reg n -> Const n -> Conditional. - -(* Generalized Variable Entry *) - -Inductive Mapping (n: nat) := - | regM: forall (r: Reg n), Mapping n - | stackM: forall (s: Stack n), Mapping n - | memM: forall {m} (x: Mem n m) (i: Index m), Mapping n - | constM: forall (x: Const n), Mapping n. - -(* Parameter Accessors *) - -Definition constWidth {n} (x: Const n): nat := n. - -Definition regWidth {n} (x: Reg n): nat := n. - -Definition stackWidth {n} (x: Stack n): nat := n. - -Definition memWidth {n m} (x: Mem n m): nat := n. - -Definition memLength {n m} (x: Mem n m): nat := m. - -Definition constValueW {n} (x: Const n): word n := - match x with | @constant n _ v => v end. - -Definition constValueN {n} (x: Const n): nat := - match x with | @constant n _ v => wordToNat v end. - -Definition regName {n} (x: Reg n): nat := - match x with | @reg n _ v => v end. - -Definition stackName {n} (x: Stack n): nat := - match x with | @stack n _ v => v end. - -Definition memName {n m} (x: Mem n m): nat := - match x with | @mem n m _ v => v end. - -(* Hints *) -Hint Constructors - Reg Stack Const Mem Mapping - Assignment Operation Conditional. diff --git a/src/Assembly/QhasmEvalCommon.v b/src/Assembly/QhasmEvalCommon.v deleted file mode 100644 index 9760dc869..000000000 --- a/src/Assembly/QhasmEvalCommon.v +++ /dev/null @@ -1,299 +0,0 @@ -Require Import Crypto.Assembly.QhasmCommon Crypto.Assembly.QhasmUtil Crypto.Assembly.State. -Require Import Coq.ZArith.ZArith Coq.Bool.Sumbool. -Require Import Bedrock.Word. -Require Import Coq.Logic.Eqdep_dec Coq.Logic.ProofIrrelevance. -Require Export Crypto.Util.FixCoqMistakes. - -Module EvalUtil. - Definition evalTest {n} (o: TestOp) (a b: word n): bool := - let c := (N.compare (wordToN a) (wordToN b)) in - - let eqBit := match c with | Eq => true | _ => false end in - let ltBit := match c with | Lt => true | _ => false end in - let gtBit := match c with | Gt => true | _ => false end in - - match o with - | TEq => eqBit - | TLt => ltBit - | TLe => orb (eqBit) (ltBit) - | TGt => gtBit - | TGe => orb (eqBit) (gtBit) - end. - - Definition evalIntOp {b} (io: IntOp) (x y: word b) := - match io return (word b) * option bool with - | ISub => (wminus x y, None) - | IXor => (wxor x y, None) - | IAnd => (wand x y, None) - | IOr => (wor x y, None) - | IAdd => - let v := (wordToN x + wordToN y)%N in - let c := (overflows b (&x + &y)%N)%w in - - match c as c' return c' = c -> _ with - | right _ => fun _ => (NToWord b v, Some false) - | left _ => fun _ => (NToWord b v, Some true) - end eq_refl - end. - - Definition evalCarryOp {b} (io: CarryOp) (x y: word b) (c: bool): (word b) * bool := - match io with - | AddWidthCarry => - let c' := (overflows b (&x + &y + (if c then 1 else 0))%N)%w in - let v := addWithCarry x y c in - - match c' as c'' return c' = c'' -> _ with - | right _ => fun _ => (v, false) - | left _ => fun _ => (v, true) - end eq_refl - end. - - Definition highBits {n} (m: nat) (x: word n) := snd (break m x). - - Definition multHigh {n} (x y: word n): word n. - refine (@extend _ n _ ((highBits (n/2) x) ^* (highBits (n/2) y))); - abstract omega. - Defined. - - Definition evalDualOp {n} (duo: DualOp) (x y: word n) := - match duo with - | Mult => (x ^* y, multHigh x y) - end. - - Definition evalRotOp {b} (ro: RotOp) (x: word b) (n: nat) := - match ro with - | Shl => NToWord b (N.shiftl_nat (wordToN x) n) - | Shr => NToWord b (N.shiftr_nat (wordToN x) n) - end. - - (* Width decideability *) - - Definition getWidth (n: nat): option (Width n) := - match n with - | 32 => Some W32 - | 64 => Some W64 - | _ => None - end. - - Lemma getWidth_eq {n} (a: Width n): Some a = getWidth n. - Proof. induction a; unfold getWidth; simpl; intuition. Qed. - - Lemma width_eq {n} (a b: Width n): a = b. - Proof. - assert (Some a = Some b) as H by ( - replace (Some a) with (getWidth n) by (rewrite getWidth_eq; intuition); - replace (Some b) with (getWidth n) by (rewrite getWidth_eq; intuition); - intuition). - inversion H; intuition. - Qed. - - (* Mapping Conversions *) - - Definition wordToM {n: nat} {spec: Width n} (w: word n): Mapping n := - constM _ (constant spec w). - - Definition regToM {n: nat} {spec: Width n} (r: Reg n): Mapping n := - regM _ r. - - Definition stackToM {n: nat} {spec: Width n} (s: Stack n): Mapping n := - stackM _ s. - - Definition constToM {n: nat} {spec: Width n} (c: Const n): Mapping n := - constM _ c. - - Definition mapping_dec {n} (a b: Mapping n): {a = b} + {a <> b}. - refine (match (a, b) as p' return (a, b) = p' -> _ with - | (regM v, regM v') => fun _ => - if (Nat.eq_dec (regName v) (regName v')) - then left _ - else right _ - - | (stackM v, stackM v') => fun _ => - if (Nat.eq_dec (stackName v) (stackName v')) - then left _ - else right _ - - | (constM v, constM v') => fun _ => - if (Nat.eq_dec (constValueN v) (constValueN v')) - then left _ - else right _ - - | (memM _ v i, memM _ v' i') => fun _ => - if (Nat.eq_dec (memName v) (memName v')) - then if (Nat.eq_dec (memLength v) (memLength v')) - then if (Nat.eq_dec (proj1_sig i) (proj1_sig i')) - then left _ else right _ else right _ else right _ - - | _ => fun _ => right _ - end (eq_refl (a, b))); - try destruct v, v'; subst; - unfold regName, stackName, constValueN, memName, memLength in *; - repeat progress (try apply f_equal; subst; match goal with - (* Makeshift intuition *) - | [ |- ?x = ?x ] => reflexivity - | [ H: ?x <> ?x |- _ ] => destruct H - | [ |- ?x = ?y ] => apply proof_irrelevance - - (* Destruct the widths *) - | [ w0: Width ?x, w1: Width ?x |- _ ] => - let H := fresh in - assert (w0 = w1) as H by (apply width_eq); - rewrite H in *; - clear w0 H - - (* Invert <> *) - | [ |- regM _ _ <> _ ] => let H := fresh in (intro H; inversion H) - | [ |- memM _ _ _ <> _ ] => let H := fresh in (intro H; inversion H) - | [ |- stackM _ _ <> _ ] => let H := fresh in (intro H; inversion H) - | [ |- constM _ _ <> _ ] => let H := fresh in (intro H; inversion H) - - (* Invert common structures *) - | [ H: regName _ = regName _ |- _ ] => inversion_clear H - | [ H: (_, _) = _ |- _ ] => inversion_clear H - | [ H: ?x = _ |- _ ] => is_var x; rewrite H in *; clear H - - (* Destruct sigmas, exist, existT *) - | [ H: proj1_sig ?a = proj1_sig ?b |- _ ] => - let l0 := fresh in let l1 := fresh in - destruct a, b; simpl in H; subst - | [ H: proj1_sig ?a <> proj1_sig ?b |- _ ] => - let l0 := fresh in let l1 := fresh in - destruct a, b; simpl in H; subst - | [ H: existT ?a ?b _ = existT ?a ?b _ |- _ ] => - apply (inj_pair2_eq_dec _ Nat.eq_dec) in H; - subst; intuition - | [ H: exist _ _ _ = exist _ _ _ |- _ ] => - inversion H; subst; intuition - - (* Single specialized wordToNat proof *) - | [ H: wordToNat ?a = wordToNat ?b |- ?a = ?b] => - rewrite <- (natToWord_wordToNat a); - rewrite <- (natToWord_wordToNat b); - rewrite H; reflexivity - - | _ => idtac - end). - Defined. - - Definition dec_lt (a b: nat): {(a < b)%nat} + {(a >= b)%nat}. - assert ({(a <? b)%nat = true} + {(a <? b)%nat <> true}) - by abstract (destruct (a <? b)%nat; intuition auto with bool); - destruct H. - - - left; abstract (apply Nat.ltb_lt; intuition). - - - right; abstract (rewrite Nat.ltb_lt in *; intuition auto with zarith). - Defined. - - Fixpoint stackNames {n} (lst: list (Mapping n)): list nat := - match lst with - | nil => nil - | cons c cs => - match c with - | stackM v => cons (stackName v) (stackNames cs) - | _ => stackNames cs - end - end. - - Fixpoint regNames {n} (lst: list (Mapping n)): list nat := - match lst with - | nil => nil - | cons c cs => - match c with - | regM v => cons (regName v) (regNames cs) - | _ => regNames cs - end - end. - -End EvalUtil. - -Module QhasmEval. - Export EvalUtil FullState. - - Definition evalCond (c: Conditional) (state: State): option bool := - match c with - | CTrue => Some true - | CZero n r => - omap (getReg r state) (fun v => - if (Nat.eq_dec O (wordToNat v)) - then Some true - else Some false) - | CReg n o a b => - omap (getReg a state) (fun va => - omap (getReg b state) (fun vb => - Some (evalTest o va vb))) - | CConst n o a c => - omap (getReg a state) (fun va => - Some (evalTest o va (constValueW c))) - end. - - Definition evalOperation (o: Operation) (state: State): option State := - match o with - | IOpConst _ o r c => - omap (getReg r state) (fun v => - let (v', co) := (evalIntOp o v (constValueW c)) in - Some (setCarryOpt co (setReg r v' state))) - - | IOpReg _ o a b => - omap (getReg a state) (fun va => - omap (getReg b state) (fun vb => - let (v', co) := (evalIntOp o va vb) in - Some (setCarryOpt co (setReg a v' state)))) - - | IOpStack _ o a b => - omap (getReg a state) (fun va => - omap (getStack b state) (fun vb => - let (v', co) := (evalIntOp o va vb) in - Some (setCarryOpt co (setReg a v' state)))) - - | IOpMem _ _ o r m i => - omap (getReg r state) (fun va => - omap (getMem m i state) (fun vb => - let (v', co) := (evalIntOp o va vb) in - Some (setCarryOpt co (setReg r v' state)))) - - | DOp _ o a b (Some x) => - omap (getReg a state) (fun va => - omap (getReg b state) (fun vb => - let (low, high) := (evalDualOp o va vb) in - Some (setReg x high (setReg a low state)))) - - | DOp _ o a b None => - omap (getReg a state) (fun va => - omap (getReg b state) (fun vb => - let (low, high) := (evalDualOp o va vb) in - Some (setReg a low state))) - - | ROp _ o r i => - omap (getReg r state) (fun v => - let v' := (evalRotOp o v i) in - Some (setReg r v' state)) - - | COp _ o a b => - omap (getReg a state) (fun va => - omap (getReg b state) (fun vb => - match (getCarry state) with - | None => None - | Some c0 => - let (v', c') := (evalCarryOp o va vb c0) in - Some (setCarry c' (setReg a v' state)) - end)) - end. - - Definition evalAssignment (a: Assignment) (state: State): option State := - match a with - | ARegMem _ _ r m i => - omap (getMem m i state) (fun v => Some (setReg r v state)) - | AMemReg _ _ m i r => - omap (getReg r state) (fun v => Some (setMem m i v state)) - | AStackReg _ a b => - omap (getReg b state) (fun v => Some (setStack a v state)) - | ARegStack _ a b => - omap (getStack b state) (fun v => Some (setReg a v state)) - | ARegReg _ a b => - omap (getReg b state) (fun v => Some (setReg a v state)) - | AConstInt _ r c => - Some (setReg r (constValueW c) state) - end. - -End QhasmEval. diff --git a/src/Assembly/QhasmUtil.v b/src/Assembly/QhasmUtil.v deleted file mode 100644 index b7dd90da6..000000000 --- a/src/Assembly/QhasmUtil.v +++ /dev/null @@ -1,91 +0,0 @@ -Require Import ZArith NArith NPeano. -Require Import QhasmCommon. -Require Export Bedrock.Word Bedrock.Nomega. - -Delimit Scope nword_scope with w. -Local Open Scope nword_scope. - -Notation "& x" := (wordToN x) (at level 30) : nword_scope. -Notation "** x" := (NToWord _ x) (at level 30) : nword_scope. - -Section Util. - Definition convS {n m} (x: word n) (H: n = m): word m. - refine (eq_rect _ (fun B0 : Set => B0) x _ _). - abstract (subst; intuition). - Defined. - - Definition low {k n: nat} (p: (k <= n)%nat) (w: word n): word k. - refine (split1 k (n - k) (convS w _)); abstract omega. - Defined. - - Definition high {k n: nat} (p: (k <= n)%nat) (w: word n): word (n - k). - refine (split2 k (n - k) (convS w _)); abstract omega. - Defined. - - Definition extend {k n: nat} (p: (k <= n)%nat) (w: word k): word n. - refine (convS (zext w (n - k)) _); abstract omega. - Defined. - - Definition shiftr {n} (w: word n) (k: nat): word n. - refine match (le_dec k n) with - | left p => extend _ (@high k _ _ w) - | right _ => wzero n - end; abstract nomega. - Defined. - - Definition mask {n} (k: nat) (w: word n): word n := - match (le_dec k n) with - | left p => extend p (low p w) - | right _ => w - end. - - Definition Nge_dec (x y: N) : - {(x >= y)%N} + {(x < y)%N}. - refine ( - let c := (x ?= y)%N in - match c as c' return c = c' -> _ with - | Lt => fun _ => right _ - | _ => fun _ => left _ - end eq_refl); abstract ( - unfold c in *; unfold N.lt, N.ge; - repeat match goal with - | [ H: (_ ?= _)%N = _ |- _] => - rewrite H; intuition; try inversion H - | [ H: Eq = _ |- _] => inversion H - | [ H: Gt = _ |- _] => inversion H - | [ H: Lt = _ |- _] => inversion H - end). - Defined. - - Definition overflows (n: nat) (x: N) := Nge_dec x (Npow2 n). - - Definition ind (b: bool): N := if b then 1%N else 0%N. - - Definition ind' {A B} (b: {A} + {B}): N := if b then 1%N else 0%N. - - Definition break {n} (m: nat) (x: word n): word m * word (n - m). - refine match (le_dec m n) with - | left p => (extend _ (low p x), extend _ (@high m n _ x)) - | right p => (extend _ x, extend _ WO) - end; try abstract intuition. - Defined. - - Definition addWithCarry {n} (x y: word n) (c: bool): word n := - x ^+ y ^+ (natToWord _ (if c then 1 else 0)). - - Definition omap {A B} (x: option A) (f: A -> option B) := - match x with - | Some y => f y - | _ => None - end. - - Notation "A <- X ; B" := (omap X (fun A => B)) (at level 70, right associativity). - - Definition orElse {T} (d: T) (o: option T): T := - match o with - | Some v => v - | None => d - end. -End Util. - -Close Scope nword_scope.
\ No newline at end of file diff --git a/src/Assembly/State.v b/src/Assembly/State.v deleted file mode 100644 index 3467a5cad..000000000 --- a/src/Assembly/State.v +++ /dev/null @@ -1,331 +0,0 @@ -Require Export Coq.Strings.String Coq.Lists.List Coq.Init.Logic. -Require Export Bedrock.Word. - -Require Import Coq.ZArith.ZArith Coq.NArith.NArith Coq.Numbers.Natural.Peano.NPeano Coq.NArith.Ndec. -Require Import Coq.Arith.Compare_dec Coq.omega.Omega. -Require Import Coq.Structures.OrderedType Coq.Structures.OrderedTypeEx. -Require Import Coq.FSets.FMapPositive Coq.FSets.FMapFullAVL Coq.Logic.JMeq. - -Require Import Crypto.Assembly.QhasmUtil Crypto.Assembly.QhasmCommon. - -Require Export Crypto.Util.FixCoqMistakes. - -(* We want to use pairs and triples as map keys: *) - -Module Pair_as_OT <: UsualOrderedType. - Definition t := (nat * nat)%type. - - Definition eq := @eq t. - Definition eq_refl := @eq_refl t. - Definition eq_sym := @eq_sym t. - Definition eq_trans := @eq_trans t. - - Definition lt (a b: t) := - if (Nat.eq_dec (fst a) (fst b)) - then lt (snd a) (snd b) - else lt (fst a) (fst b). - - Lemma conv: forall {x0 x1 y0 y1: nat}, - (x0 = y0 /\ x1 = y1) <-> (x0, x1) = (y0, y1). - Proof. - intros; split; intros. - - destruct H; destruct H0; subst; intuition. - - inversion_clear H; intuition. - Qed. - - Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. - intros; destruct x as [x0 x1], y as [y0 y1], z as [z0 z1]; - unfold lt in *; simpl in *; - destruct (Nat.eq_dec x0 y0), (Nat.eq_dec y0 z0), (Nat.eq_dec x0 z0); - omega. - Qed. - - Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y. - intros; destruct x as [x0 x1], y as [y0 y1]; - unfold lt, eq in *; simpl in *; - destruct (Nat.eq_dec x0 y0); subst; intuition; - inversion H0; subst; omega. - Qed. - - Definition compare x y : Compare lt eq x y. - destruct x as [x0 x1], y as [y0 y1]; - destruct (Nat_as_OT.compare x0 y0); - unfold Nat_as_OT.lt, Nat_as_OT.eq in *. - - - apply LT; abstract (unfold lt; simpl; destruct (Nat.eq_dec x0 y0); intuition auto with zarith). - - - destruct (Nat_as_OT.compare x1 y1); - unfold Nat_as_OT.lt, Nat_as_OT.eq in *. - - + apply LT; abstract (unfold lt; simpl; destruct (Nat.eq_dec x0 y0); intuition). - + apply EQ; abstract (unfold lt; simpl; subst; intuition auto with relations). - + apply GT; abstract (unfold lt; simpl; destruct (Nat.eq_dec y0 x0); intuition auto with zarith). - - - apply GT; abstract (unfold lt; simpl; destruct (Nat.eq_dec y0 x0); intuition auto with zarith). - Defined. - - Definition eq_dec (a b: t): {a = b} + {a <> b}. - destruct (compare a b); - destruct a as [a0 a1], b as [b0 b1]. - - - right; abstract ( - unfold lt in *; simpl in *; - destruct (Nat.eq_dec a0 b0); intuition; - inversion H; intuition auto with zarith). - - - left; abstract (inversion e; intuition). - - - right; abstract ( - unfold lt in *; simpl in *; - destruct (Nat.eq_dec b0 a0); intuition; - inversion H; intuition auto with zarith). - Defined. -End Pair_as_OT. - -Module Triple_as_OT <: UsualOrderedType. - Definition t := (nat * nat * nat)%type. - - Definition get0 (x: t) := fst (fst x). - Definition get1 (x: t) := snd (fst x). - Definition get2 (x: t) := snd x. - - Definition eq := @eq t. - Definition eq_refl := @eq_refl t. - Definition eq_sym := @eq_sym t. - Definition eq_trans := @eq_trans t. - - Definition lt (a b: t) := - if (Nat.eq_dec (get0 a) (get0 b)) - then - if (Nat.eq_dec (get1 a) (get1 b)) - then lt (get2 a) (get2 b) - else lt (get1 a) (get1 b) - else lt (get0 a) (get0 b). - - Lemma conv: forall {x0 x1 x2 y0 y1 y2: nat}, - (x0 = y0 /\ x1 = y1 /\ x2 = y2) <-> (x0, x1, x2) = (y0, y1, y2). - Proof. - intros; split; intros. - - destruct H; destruct H0; subst; intuition. - - inversion_clear H; intuition. - Qed. - - Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. - intros; unfold lt in *; - destruct (Nat.eq_dec (get0 x) (get0 y)), - (Nat.eq_dec (get1 x) (get1 y)), - (Nat.eq_dec (get0 y) (get0 z)), - (Nat.eq_dec (get1 y) (get1 z)), - (Nat.eq_dec (get0 x) (get0 z)), - (Nat.eq_dec (get1 x) (get1 z)); - omega. - Qed. - - Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y. - intros; unfold lt, eq in *; - destruct (Nat.eq_dec (get0 x) (get0 y)), - (Nat.eq_dec (get1 x) (get1 y)); - subst; intuition; - inversion H0; subst; omega. - Qed. - - Ltac compare_tmp x y := - abstract ( - unfold Nat_as_OT.lt, Nat_as_OT.eq, lt, eq in *; - destruct (Nat.eq_dec (get0 x) (get0 y)); - destruct (Nat.eq_dec (get1 x) (get1 y)); - simpl; intuition auto with zarith). - - Ltac compare_eq x y := - abstract ( - unfold Nat_as_OT.lt, Nat_as_OT.eq, lt, eq, get0, get1 in *; - destruct x as [x x2], y as [y y2]; - destruct x as [x0 x1], y as [y0 y1]; - simpl in *; subst; intuition). - - Definition compare x y : Compare lt eq x y. - destruct (Nat_as_OT.compare (get0 x) (get0 y)). - - - apply LT; compare_tmp x y. - - destruct (Nat_as_OT.compare (get1 x) (get1 y)). - + apply LT; compare_tmp x y. - + destruct (Nat_as_OT.compare (get2 x) (get2 y)). - * apply LT; compare_tmp x y. - * apply EQ; compare_eq x y. - * apply GT; compare_tmp y x. - + apply GT; compare_tmp y x. - - apply GT; compare_tmp y x. - Defined. - - Definition eq_dec (a b: t): {a = b} + {a <> b}. - destruct (compare a b); - destruct a as [a a2], b as [b b2]; - destruct a as [a0 a1], b as [b0 b1]. - - - right; abstract ( - unfold lt, get0, get1, get2 in *; simpl in *; - destruct (Nat.eq_dec a0 b0), (Nat.eq_dec a1 b1); - intuition; inversion H; intuition auto with zarith). - - - left; abstract (inversion e; intuition). - - - right; abstract ( - unfold lt, get0, get1, get2 in *; simpl in *; - destruct (Nat.eq_dec b0 a0), (Nat.eq_dec b1 a1); - intuition; inversion H; intuition auto with zarith). - Defined. -End Triple_as_OT. - -Module StateCommon. - Export ListNotations. - - Module NatM := FMapFullAVL.Make(Nat_as_OT). - Module PairM := FMapFullAVL.Make(Pair_as_OT). - Module TripleM := FMapFullAVL.Make(Triple_as_OT). - - Definition NatNMap: Type := NatM.t N. - Definition PairNMap: Type := PairM.t N. - Definition TripleNMap: Type := TripleM.t N. - Definition LabelMap: Type := NatM.t nat. -End StateCommon. - -Module ListState. - Export StateCommon. - - Definition ListState (n: nat) := ((list (word n)) * TripleNMap * (option bool))%type. - - Definition emptyState {n}: ListState n := ([], TripleM.empty N, None). - - Definition getVar {n: nat} (name: nat) (st: ListState n): option (word n) := - nth_error (fst (fst st)) name. - - Definition getList {n: nat} (st: ListState n): list (word n) := - fst (fst st). - - Definition setList {n: nat} (lst: list (word n)) (st: ListState n): ListState n := - (lst, snd (fst st), snd st). - - Definition getMem {n: nat} (name index: nat) (st: ListState n): option (word n) := - omap (TripleM.find (n, name, index) (snd (fst st))) (fun v => Some (NToWord n v)). - - Definition setMem {n: nat} (name index: nat) (v: word n) (st: ListState n): ListState n := - (fst (fst st), TripleM.add (n, name, index) (wordToN v) (snd (fst st)), snd st). - - Definition getCarry {n: nat} (st: ListState n): option bool := (snd st). - - Definition setCarry {n: nat} (v: bool) (st: ListState n): ListState n := - (fst st, Some v). - - Definition setCarryOpt {n: nat} (v: option bool) (st: ListState n): ListState n := - match v with - | Some v' => (fst st, v) - | None => st - end. - -End ListState. - -Module FullState. - Export StateCommon. - - (* The Big Definition *) - - Inductive State := - | fullState (regState: PairNMap) - (stackState: PairNMap) - (memState: TripleNMap) - (retState: list nat) - (carry: Carry): State. - - Definition emptyState: State := - fullState (PairM.empty N) (PairM.empty N) (TripleM.empty N) [] None. - - (* Register *) - - Definition getReg {n} (r: Reg n) (state: State): option (word n) := - match state with - | fullState regS _ _ _ _ => - match (PairM.find (n, regName r) regS) with - | Some v => Some (NToWord n v) - | None => None - end - end. - - Definition setReg {n} (r: Reg n) (value: word n) (state: State): State := - match state with - | fullState regS stackS memS retS carry => - fullState (PairM.add (n, regName r) (wordToN value) regS) - stackS memS retS carry - end. - - (* Stack *) - - Definition getStack {n} (s: Stack n) (state: State): option (word n) := - match state with - | fullState _ stackS _ _ _ => - match (PairM.find (n, stackName s) stackS) with - | Some v => Some (NToWord n v) - | None => None - end - end. - - Definition setStack {n} (s: Stack n) (value: word n) (state: State): State := - match state with - | fullState regS stackS memS retS carry => - fullState regS - (PairM.add (n, stackName s) (wordToN value) stackS) - memS retS carry - end. - - (* Memory *) - - Definition getMem {n m} (x: Mem n m) (i: Index m) (state: State): option (word n) := - match state with - | fullState _ _ memS _ _ => - match (TripleM.find (n, memName x, proj1_sig i) memS) with - | Some v => Some (NToWord n v) - | None => None - end - end. - - Definition setMem {n m} (x: Mem n m) (i: Index m) (value: word n) (state: State): State := - match state with - | fullState regS stackS memS retS carry => - fullState regS stackS - (TripleM.add (n, memName x, proj1_sig i) (wordToN value) memS) - retS carry - end. - - (* Return Pointers *) - - Definition pushRet (x: nat) (state: State): State := - match state with - | fullState regS stackS memS retS carry => - fullState regS stackS memS (cons x retS) carry - end. - - Definition popRet (state: State): option (State * nat) := - match state with - | fullState regS stackS memS [] carry => None - | fullState regS stackS memS (r :: rs) carry => - Some (fullState regS stackS memS rs carry, r) - end. - - (* Carry State Manipulations *) - - Definition getCarry (state: State): Carry := - match state with - | fullState _ _ _ _ b => b - end. - - Definition setCarry (value: bool) (state: State): State := - match state with - | fullState regS stackS memS retS carry => - fullState regS stackS memS retS (Some value) - end. - - Definition setCarryOpt (value: option bool) (state: State): State := - match value with - | Some c' => setCarry c' state - | _ => state - end. -End FullState. diff --git a/src/Assembly/StringConversion.v b/src/Assembly/StringConversion.v deleted file mode 100644 index f1ec58dca..000000000 --- a/src/Assembly/StringConversion.v +++ /dev/null @@ -1,367 +0,0 @@ -Require Export Coq.Strings.String Coq.Strings.Ascii Coq.Program.Basics Coq.Bool.Sumbool. -Require Import Crypto.Assembly.QhasmCommon Crypto.Assembly.QhasmEvalCommon Crypto.Assembly.QhasmUtil Crypto.Assembly.Qhasm. -Require Import Coq.NArith.NArith Coq.Numbers.Natural.Peano.NPeano. -Require Export Bedrock.Word. - -Module StringConversion. - Import Qhasm ListNotations. - - Section Hex. - Local Open Scope string_scope. - - Definition natToDigit (n : nat) : string := - match n with - | 0 => "0" | 1 => "1" | 2 => "2" | 3 => "3" - | 4 => "4" | 5 => "5" | 6 => "6" | 7 => "7" - | 8 => "8" | 9 => "9" | 10 => "A" | 11 => "B" - | 12 => "C" | 13 => "D" | 14 => "E" | _ => "F" - end. - - Fixpoint nToHex' (n: N) (digitsLeft: nat): string := - match digitsLeft with - | O => "" - | S nextLeft => - match n with - | N0 => "0" - | _ => (nToHex' (N.shiftr_nat n 4) nextLeft) ++ - (natToDigit (N.to_nat (N.land n 15%N))) - end - end. - - Definition nToHex (n: N): string := - let size := (N.size n) in - let div4 := fun x => (N.shiftr x 2%N) in - let size' := (size + 4 - (N.land size 3))%N in - nToHex' n (N.to_nat (div4 size')). - - End Hex. - - Section Elements. - Local Open Scope string_scope. - - Definition nameSuffix (n: nat): string := - (nToHex (N.of_nat n)). - - Coercion wordToString {n} (w: word n): string := - "0x" ++ (nToHex (wordToN w)). - - Coercion constToString {n} (c: Const n): string := - match c with | constant _ _ w => wordToString w end. - - Coercion regToString {n} (r: Reg n): string := - match r with - | reg _ W32 n => "w" ++ (nameSuffix n) - | reg _ W64 n => "d" ++ (nameSuffix n) - end. - - Coercion natToString (n: nat): string := - "0x" ++ (nToHex (N.of_nat n)). - - Coercion stackToString {n} (s: Stack n): string := - match s with - | stack _ W32 n => "ws" ++ (nameSuffix n) - | stack _ W64 n => "ds" ++ (nameSuffix n) - end. - - Coercion memToString {n m} (s: Mem n m): string := - match s with - | mem _ _ W32 v => "wm" ++ (nameSuffix v) - | mem _ _ W64 v => "dm" ++ (nameSuffix v) - end. - - Coercion stringToSome (x: string): option string := Some x. - - Definition stackLocation {n} (s: Stack n): word 32 := - combine (natToWord 8 n) (natToWord 24 n). - - Definition assignmentToString (a: Assignment): option string := - let f := fun x => if (Nat.eq_dec x 32) then "32" else "64" in - match a with - | ARegStack n r s => r ++ " = *(int" ++ f n ++ " *)" ++ s - | AStackReg n s r => "*(int" ++ f n ++ " *) " ++ s ++ " = " ++ r - | ARegMem n m r v i => r ++ " = " ++ "*(int" ++ f n ++ " *) (" ++ v ++ " + " ++ i ++ ")" - | AMemReg n m v i r => "*(int" ++ f n ++ " *) (" ++ v ++ " + " ++ i ++ ") = " ++ r - | ARegReg n a b => a ++ " = " ++ b - | AConstInt n r c => r ++ " = " ++ c - end. - - Coercion intOpToString (b: IntOp): string := - match b with - | IAdd => "+" - | ISub => "-" - | IXor => "^" - | IAnd => "&" - | IOr => "|" - end. - - Coercion dualOpToString (b: DualOp): string := - match b with - | Mult => "*" - end. - - Coercion carryOpToString (b: CarryOp): string := - match b with - | AddWithCarry => "+" - end. - - Coercion rotOpToString (r: RotOp): string := - match r with - | Shl => "<<" - | Shr => ">>" - end. - - Definition operationToString (op: Operation): option string := - let f := fun x => ( - if (Nat.eq_dec x 32) - then "32" - else if (Nat.eq_dec x 64) - then "64" - else "128") in - - match op with - | IOpConst n o r c => - r ++ " " ++ o ++ "= " ++ c - | IOpReg n o a b => - a ++ " " ++ o ++ "= " ++ b - | IOpMem n _ o a b i => - a ++ " " ++ o ++ "= *(int" ++ (f n) ++ "* " ++ b ++ " + " ++ i ++ ")" - | IOpStack n o a b => - a ++ " " ++ o ++ "= " ++ b - | DOp n o a b x => - match x with - | Some r => - "(int" ++ (f (2 * n)) ++ ") " ++ r ++ " " ++ a ++ " " ++ o ++ "= " ++ b - | None => a ++ " " ++ o ++ "= " ++ b - end - | COp n o a b => - a ++ " " ++ o ++ "= " ++ b - | ROp n o r i => - r ++ " " ++ o ++ "= " ++ i - end. - - Definition testOpToString (t: TestOp): bool * string := - match t with - | TEq => (true, "=") - | TLt => (true, "<") - | TGt => (true, ">") - | TLe => (false, ">") - | TGe => (false, "<") - end. - - Definition conditionalToString (c: Conditional): string * string := - match c with - | CTrue => ("=? 0", "=") - | CZero n r => ("=? " ++ r, "=") - | CReg n t a b => - match (testOpToString t) with - | (true, s) => - (s ++ "? " ++ a ++ " - " ++ b, s) - | (false, s) => - (s ++ "? " ++ a ++ " - " ++ b, "!" ++ s) - end - - | CConst n t a b => - match (testOpToString t) with - | (true, s) => - (s ++ "? " ++ a ++ " - " ++ b, s) - | (false, s) => - (s ++ "? " ++ a ++ " - " ++ b, "!" ++ s) - end - end. - - End Elements. - - Section Parsing. - Definition convM {n m} (x: list (Mapping n)): list (Mapping m). - destruct (Nat.eq_dec n m); subst. exact x. exact []. - Defined. - - Arguments regM [n] r. - Arguments stackM [n] s. - Arguments memM [n m] x i. - Arguments constM [n] x. - - Fixpoint entries (width: nat) (prog: list QhasmStatement): list (Mapping width) := - match prog with - | cons s next => - match s with - | QAssign a => - match a with - | ARegStack n r s => convM [regM r; stackM s] - | AStackReg n s r => convM [regM r; stackM s] - | ARegMem n m a b i => convM [regM a; memM b i] - | AMemReg n m a i b => convM [memM a i; regM b] - | ARegReg n a b => convM [regM a; regM b] - | AConstInt n r c => convM [regM r; constM c] - end - | QOp o => - match o with - | IOpConst _ o a c => convM [regM a; constM c] - | IOpReg _ o a b => convM [regM a; regM b] - | IOpStack _ o a b => convM [regM a; stackM b] - | IOpMem _ _ o a b i => convM [regM a; memM b i] - | DOp _ o a b (Some x) => convM [regM a; regM b; regM x] - | DOp _ o a b None => convM [regM a; regM b] - | ROp _ o a i => convM [regM a] - | COp _ o a b => convM [regM a; regM b] - end - | QCond c _ => - match c with - | CTrue => [] - | CZero n r => convM [regM r] - | CReg n o a b => convM [regM a; regM b] - | CConst n o a c => convM [regM a; constM c] - end - | _ => [] - end ++ (entries width next) - | nil => nil - end. - - Definition flatMapOpt {A B} (lst: list A) (f: A -> option B): list B := - fold_left - (fun lst a => match (f a) with | Some x => cons x lst | _ => lst end) - lst []. - - Definition flatMapList {A B} (lst: list A) (f: A -> list B): list B := - fold_left (fun lst a => lst ++ (f a)) lst []. - - Fixpoint dedup {n} (l : list (Mapping n)) : list (Mapping n) := - match l with - | [] => [] - | x::xs => - if in_dec EvalUtil.mapping_dec x xs - then dedup xs - else x::(dedup xs) - end. - - Definition getRegNames (n: nat) (lst: list (Mapping n)): list nat := - flatMapOpt (dedup lst) (fun e => - match e with | regM (reg _ _ x) => Some x | _ => None end). - - Definition getStackNames (n: nat) (lst: list (Mapping n)): list nat := - flatMapOpt (dedup lst) (fun e => - match e with | stackM (stack _ _ x) => Some x | _ => None end). - - Definition getMemNames (n: nat) (lst: list (Mapping n)): list nat := - flatMapOpt (dedup lst) (fun e => - match e with | memM _ (mem _ _ _ x) _ => Some x | _ => None end). - - Fixpoint getInputs' (n: nat) (prog: list QhasmStatement) (init: list (Mapping n)): list (Mapping n) := - let f := fun rs => filter (fun x => - negb (proj1_sig (bool_of_sumbool (in_dec EvalUtil.mapping_dec x init)))) rs in - let g := fun {w} p => (@convM w n (fst p), @convM w n (snd p)) in - match prog with - | [] => [] - | cons p ps => - let requiredCommaUsed := match p with - | QAssign a => - match a with - | ARegStack n r s => g ([stackM s], [regM r; stackM s]) - | AStackReg n s r => g ([regM r], [regM r; stackM s]) - | ARegMem n m r x i => g ([memM x i], [regM r; memM x i]) - | AMemReg n m x i r => g ([regM r], [regM r; memM x i]) - | ARegReg n a b => g ([regM b], [regM a; regM b]) - | AConstInt n r c => g ([], [regM r]) - end - | QOp o => - match o with - | IOpConst _ o a c => g ([regM a], [regM a]) - | IOpReg _ o a b => g ([regM a], [regM a; regM b]) - | IOpStack _ o a b => g ([regM a], [regM a; stackM b]) - | IOpMem _ _ o a b i => g ([regM a], [regM a; memM b i]) - | DOp _ o a b (Some x) => g ([regM a; regM b], [regM a; regM b; regM x]) - | DOp _ o a b None => g ([regM a; regM b], [regM a; regM b]) - | ROp _ o a i => g ([regM a], [regM a]) - | COp _ o a b => g ([regM a], [regM a; regM b]) - end - | QCond c _ => - match c with - | CTrue => ([], []) - | CZero n r => g ([], [regM r]) - | CReg n o a b => g ([], [regM a; regM b]) - | CConst n o a c => g ([], [regM a]) - end - | _ => ([], []) - end in match requiredCommaUsed with - | (r, u) => ((f r) ++ (getInputs' n ps ((f u) ++ init))) - end - end. - - Definition getInputs (n: nat) (prog: list QhasmStatement) := getInputs' n prog []. - - Definition mappingDeclaration {n} (x: Mapping n): option string := - match x with - | regM (reg _ w x) => - match w with - | W32 => Some ("int32 " ++ (reg w x))%string - | W64 => Some ("int64 " ++ (reg w x))%string - end - - | stackM (stack _ w x) => - match w with - | W32 => Some ("stack32 " ++ (stack w x))%string - | W64 => Some ("stack64 " ++ (stack w x))%string - end - - | memM _ (mem _ m w x) _ => - match w with - | W32 => Some ("stack32 " ++ (@mem _ m w x))%string - | W64 => Some ("stack64 " ++ (@mem _ m w x))%string - end - - | _ => None - end. - - Definition inputDeclaration {n} (x: Mapping n): option string := - match x with - | regM r => Some ("input " ++ r)%string - | stackM s => Some ("input " ++ s)%string - | memM _ m i => Some ("input " ++ m)%string - | _ => None - end. - - End Parsing. - - (* Macroscopic Conversion Methods *) - Definition optionToList {A} (o: option A): list A := - match o with - | Some a => [a] - | None => [] - end. - - Definition convertStatement (statement: QhasmStatement): list string := - match statement with - | QAssign a => optionToList (assignmentToString a) - | QOp o => optionToList (operationToString o) - | QCond c l => - match (conditionalToString c) with - | (s1, s2) => - let s' := ("goto lbl" ++ l ++ " if " ++ s2)%string in - [s1; s'] - end - | QLabel l => [("lbl" ++ l ++ ": ")%string] - | QCall l => [("push %eip+2")%string; ("goto" ++ l)%string] - | QRet => [("pop %eip")%string] - end. - - Definition convertProgram (prog: Qhasm.Program): option string := - let decls := fun x => flatMapList (dedup (entries x prog)) - (compose optionToList mappingDeclaration) in - - let inputs := fun x => flatMapList (getInputs x prog) - (compose optionToList inputDeclaration) in - - let stmts := (flatMapList prog convertStatement) in - let enter := [("enter prog")%string] in - let leave := [("leave")%string] in - let blank := [EmptyString] in - let newline := String (ascii_of_nat 10) EmptyString in - - Some (fold_left (fun x y => (x ++ newline ++ y)%string) - (decls 32 ++ inputs 32 ++ - decls 64 ++ inputs 64 ++ blank ++ - enter ++ blank ++ - stmts ++ blank ++ - leave ++ blank) EmptyString). - -End StringConversion. diff --git a/src/Assembly/WordizeUtil.v b/src/Assembly/WordizeUtil.v deleted file mode 100644 index b5f246fb1..000000000 --- a/src/Assembly/WordizeUtil.v +++ /dev/null @@ -1,996 +0,0 @@ -Require Import Bedrock.Word Bedrock.Nomega. -Require Import NArith PArith Ndigits Nnat NPow NPeano Ndec. -Require Import List Omega NArith Nnat BoolEq Compare_dec. -Require Import SetoidTactics. -Require Import ProofIrrelevance FunctionalExtensionality. -Require Import QhasmUtil QhasmEvalCommon. - -(* Custom replace-at wrapper for 8.4pl3 compatibility *) -Definition ltac_nat_from_int (x:BinInt.Z) : nat := - match x with - | BinInt.Z0 => 0%nat - | BinInt.Zpos p => BinPos.nat_of_P p - | BinInt.Zneg p => 0%nat - end. - -Ltac nat_from_number N := - match type of N with - | nat => constr:(N) - | BinInt.Z => let N' := constr:(ltac_nat_from_int N) in eval compute in N' - end. - -Tactic Notation "replace'" constr(x) "with" constr(y) "at" constr(n) "by" tactic(tac) := - let tmp := fresh in ( - match nat_from_number n with - | 1 => set (tmp := x) at 1 - | 2 => set (tmp := x) at 2 - | 3 => set (tmp := x) at 3 - | 4 => set (tmp := x) at 4 - | 5 => set (tmp := x) at 5 - end; - replace tmp with y by (unfold tmp; tac); - clear tmp). - -(* Word-shattering tactic *) -Ltac shatter a := - let H := fresh in - pose proof (shatter_word a) as H; simpl in H; - try rewrite H in *; clear H. - -Section Misc. - Local Open Scope nword_scope. - - Lemma word_replace: forall n m, n = m -> word n = word m. - Proof. intros; subst; intuition. Qed. - - Lemma of_nat_lt: forall x b, (x < b)%nat <-> (N.of_nat x < N.of_nat b)%N. - Proof. - intros x b; split; intro H. - - - unfold N.lt; rewrite N2Nat.inj_compare. - repeat rewrite Nat2N.id. - apply nat_compare_lt in H. - intuition. - - - unfold N.lt in H; rewrite N2Nat.inj_compare in H. - repeat rewrite Nat2N.id in H. - apply nat_compare_lt in H. - intuition. - Qed. - - Lemma to_nat_lt: forall x b, (x < b)%N <-> (N.to_nat x < N.to_nat b)%nat. - Proof. - intros x b; split; intro H. - - - unfold N.lt in H; rewrite N2Nat.inj_compare in H. - apply nat_compare_lt in H. - intuition. - - - unfold N.lt; rewrite N2Nat.inj_compare. - apply nat_compare_lt. - intuition. - Qed. - - Lemma to_nat_le: forall x b, (x <= b)%N <-> (N.to_nat x <= N.to_nat b)%nat. - Proof. - intros x b; split; intro H. - - - unfold N.le in H; rewrite N2Nat.inj_compare in H. - apply nat_compare_le in H. - intuition. - - - unfold N.le; rewrite N2Nat.inj_compare. - apply nat_compare_le. - intuition. - Qed. - - Lemma word_size_bound : forall {n} (w: word n), (&w < Npow2 n)%N. - Proof. - intros; pose proof (wordToNat_bound w) as B; - rewrite of_nat_lt in B; - rewrite <- Npow2_nat in B; - rewrite N2Nat.id in B; - rewrite <- wordToN_nat in B; - assumption. - Qed. - - Lemma ge_to_le: forall (x y: N), (x >= y)%N <-> (y <= x)%N. - Proof. - intros x y; split; intro H; - unfold N.ge, N.le in *; - intro H0; contradict H; - rewrite N.compare_antisym; - rewrite H0; simpl; intuition. - Qed. - - Lemma N_ge_0: forall x: N, (0 <= x)%N. - Proof. - intro x0; unfold N.le. - pose proof (N.compare_0_r x0) as H. - rewrite N.compare_antisym in H. - induction x0; simpl in *; - intro V; inversion V. - Qed. - - Lemma Pos_ge_1: forall p, (1 <= N.pos p)%N. - Proof. - intro. - replace (N.pos p) with (N.succ (N.pos p - 1)%N) by ( - induction p; simpl; - try rewrite Pos.succ_pred_double; - try reflexivity). - unfold N.succ. - apply N.le_pred_le_succ. - replace (N.pred 1%N) with 0%N by (simpl; intuition). - apply N_ge_0. - Qed. - - Lemma testbit_wones_false: forall n k, - (k >= N.of_nat n)%N - -> false = N.testbit (& wones n) k. - Proof. - induction n; try abstract (simpl; intuition). - induction k; try abstract ( - intro H; destruct H; simpl; intuition). - - intro H. - assert (N.pos p - 1 >= N.of_nat n)%N as Z. - apply ge_to_le; - apply ge_to_le in H; - apply (N.add_le_mono_r _ _ 1%N); - replace (N.of_nat n + 1)%N with (N.of_nat (S n)); - replace (N.pos p - 1 + 1)%N with (N.pos p); - try rewrite N.sub_add; - try assumption; - try nomega; - apply Pos_ge_1. - - rewrite (IHn (N.pos p - 1)%N Z) at 1. - - assert (N.pos p = N.succ (N.pos p - 1)) as Hp by ( - rewrite <- N.pred_sub; - rewrite N.succ_pred; - try abstract intuition; - intro H0; inversion H0). - - symmetry. - rewrite Hp at 1. - rewrite Hp in H. - - revert H; clear IHn Hp Z; - generalize (N.pos p - 1)%N as x; - intros x H. - - replace (& wones (S n)) with (2 * & (wones n) + N.b2n true)%N - by (simpl; rewrite ?N.succ_double_spec; simpl; nomega). - - rewrite N.testbit_succ_r; reflexivity. - Qed. - - Lemma testbit_wones_true: forall n k, - (k < N.of_nat n)%N - -> true = N.testbit (& wones n) k. - Proof. - induction n; intros k H; try nomega. - destruct (N.eq_dec k (N.of_nat n)). - - - clear IHn H; subst. - induction n. - - + simpl; intuition. - - + replace (& (wones (S (S n)))) - with (2 * (& (wones (S n))) + N.b2n true)%N - by (simpl; rewrite ?N.succ_double_spec; simpl; nomega). - rewrite Nat2N.inj_succ. - rewrite N.testbit_succ_r. - assumption. - - - induction k. - - + replace (& (wones (S n))) with (2 * (& (wones n)) + N.b2n true)%N - by (simpl; rewrite ?N.succ_double_spec; simpl; nomega). - rewrite N.testbit_0_r. - reflexivity. - - + assert (N.pos p < N.of_nat n)%N as IH by ( - rewrite Nat2N.inj_succ in H; - nomega). - apply N.lt_lt_pred in IH. - apply IHn in IH. - replace (N.pos p) with (N.succ (N.pred (N.pos p))) by ( - induction p; simpl; - try rewrite Pos.succ_pred_double; - intuition). - replace (& (wones (S n))) with (2 * (& (wones n)) + N.b2n true)%N - by (simpl; rewrite ?N.succ_double_spec; simpl; nomega). - rewrite N.testbit_succ_r. - assumption. - Qed. - - - Lemma plus_le: forall {n} (x y: word n), - (& (x ^+ y) <= &x + &y)%N. - Proof. - intros. - unfold wplus, wordBin. - rewrite wordToN_nat. - rewrite NToWord_nat. - pose proof (wordToNat_natToWord n (N.to_nat (& x + & y))) as H. - destruct H as [k H]. - destruct H as [Heq Hk]. - rewrite Heq. - rewrite Nat2N.inj_sub. - rewrite N2Nat.id. - generalize (&x + &y)%N; intro a. - generalize (N.of_nat (k * pow2 n))%N; intro b. - clear Heq Hk; clear x y k; clear n. - replace a with (a - 0)%N by nomega. - replace' (a - 0)%N with a at 1 by nomega. - apply N.sub_le_mono_l. - apply N_ge_0. - Qed. - - Lemma mult_le: forall {n} (x y: word n), - (& (x ^* y) <= &x * &y)%N. - Proof. - intros. - unfold wmult, wordBin. - rewrite wordToN_nat. - rewrite NToWord_nat. - pose proof (wordToNat_natToWord n (N.to_nat (& x * & y))) as H. - destruct H as [k H]. - destruct H as [Heq Hk]. - rewrite Heq. - rewrite Nat2N.inj_sub. - rewrite N2Nat.id. - generalize (&x * &y)%N; intro a. - generalize (N.of_nat (k * pow2 n))%N; intro b. - clear Heq Hk; clear x y k; clear n. - replace a with (a - 0)%N by nomega. - replace' (a - 0)%N with a at 1 by nomega. - apply N.sub_le_mono_l. - apply N_ge_0. - Qed. - - Lemma log2_conv: forall z, Z.log2 z = Z.of_N (N.log2 (Z.to_N z)). - Proof. - intro z; induction z as [| |p]; auto. - induction p; auto. - Qed. -End Misc. - -Section Exp. - Local Open Scope nword_scope. - - Lemma pow2_inv : forall n m, pow2 n = pow2 m -> n = m. - Proof. - induction n; intros; simpl in *; - induction m; simpl in *; try omega. - f_equal; apply IHn. - omega. - Qed. - - Lemma pow2_gt0 : forall n, (pow2 n > O)%nat. - Proof. induction n; simpl; omega. Qed. - - Lemma pow2_N_bound: forall n j, - (j < pow2 n)%nat -> (N.of_nat j < Npow2 n)%N. - Proof. - intros. - rewrite <- Npow2_nat in H. - unfold N.lt. - rewrite N2Nat.inj_compare. - rewrite Nat2N.id. - apply nat_compare_lt in H. - assumption. - Qed. - - Lemma Npow2_gt0 : forall x, (0 < Npow2 x)%N. - Proof. - intros; induction x. - - - simpl; apply N.lt_1_r; intuition. - - - replace (Npow2 (S x)) with (2 * (Npow2 x))%N by intuition. - apply (N.lt_0_mul 2 (Npow2 x)); left; split; apply N.neq_0_lt_0. - - + intuition; inversion H. - - + apply N.neq_0_lt_0 in IHx; intuition. - Qed. - - Lemma Npow2_ge1 : forall x, (1 <= Npow2 x)%N. - Proof. - intro x. - pose proof (Npow2_gt0 x) as Z. - apply N.lt_pred_le; simpl. - assumption. - Qed. - - Lemma Npow2_split: forall a b, - (Npow2 (a + b) = (Npow2 a) * (Npow2 b))%N. - Proof. - intros; revert a. - induction b. - - - intros; simpl; replace (a + 0) with a; try nomega. - rewrite N.mul_1_r; intuition. - - - intros. - replace (a + S b) with (S a + b) by omega. - rewrite (IHb (S a)); simpl; clear IHb. - induction (Npow2 a), (Npow2 b); simpl; intuition. - rewrite Pos.mul_xO_r; intuition. - Qed. - - Lemma Npow2_N: forall n, Npow2 n = (2 ^ N.of_nat n)%N. - Proof. - induction n. - - - simpl; intuition. - - - rewrite Nat2N.inj_succ. - rewrite N.pow_succ_r; try apply N_ge_0. - rewrite <- IHn. - simpl; intuition. - Qed. - - Lemma Npow2_succ: forall n, (Npow2 (S n) = 2 * (Npow2 n))%N. - Proof. intros; simpl; induction (Npow2 n); intuition. Qed. - - Lemma Npow2_ordered: forall n m, (n <= m)%nat -> (Npow2 n <= Npow2 m)%N. - Proof. - induction n; intros m H; try rewrite Npow2_succ. - - - simpl; apply Npow2_ge1. - - - induction m; try rewrite Npow2_succ. - - + inversion H. - - + assert (n <= m)%nat as H0 by omega. - apply IHn in H0. - apply N.mul_le_mono_l. - assumption. - Qed. -End Exp. - -Section Conversions. - Local Open Scope nword_scope. - - Lemma NToWord_wordToN: forall sz x, NToWord sz (wordToN x) = x. - Proof. - intros. - rewrite NToWord_nat. - rewrite wordToN_nat. - rewrite Nat2N.id. - rewrite natToWord_wordToNat. - intuition. - Qed. - - Lemma NToWord_equal: forall n (x y: word n), - wordToN x = wordToN y -> x = y. - Proof. - intros. - rewrite <- (NToWord_wordToN _ x). - rewrite <- (NToWord_wordToN _ y). - rewrite H; reflexivity. - Qed. - - Lemma wordToN_NToWord: forall sz x, (x < Npow2 sz)%N -> wordToN (NToWord sz x) = x. - Proof. - intros. - rewrite NToWord_nat. - rewrite wordToN_nat. - rewrite <- (N2Nat.id x). - apply Nat2N.inj_iff. - rewrite Nat2N.id. - apply natToWord_inj with (sz:=sz); - try rewrite natToWord_wordToNat; - intuition. - - - apply wordToNat_bound. - - rewrite <- Npow2_nat; apply to_nat_lt; assumption. - Qed. - - Lemma Npow2_ignore: forall {n} (x: word n), - x = NToWord _ (& x + Npow2 n). - Proof. - intros. - rewrite <- (NToWord_wordToN n x) at 1. - repeat rewrite NToWord_nat. - rewrite N2Nat.inj_add. - rewrite Npow2_nat. - replace' (N.to_nat (&x)) - with ((N.to_nat (&x) + pow2 n) - 1 * pow2 n) - at 1 by omega. - rewrite drop_sub; [intuition|omega]. - Qed. -End Conversions. - -Section SpecialFunctions. - Local Open Scope nword_scope. - - Lemma convS_id: forall n x p, (@convS n n x p) = x. - Proof. - intros; unfold convS; vm_compute. - replace (convS_subproof n n x p) - with (eq_refl (word n)) by (apply proof_irrelevance). - reflexivity. - Qed. - - Lemma wordToN_convS: forall {n m} x p, - wordToN (@convS n m x p) = wordToN x. - Proof. - intros. - revert x. - rewrite p. - intro x. - rewrite convS_id. - reflexivity. - Qed. - - Lemma wordToN_zext: forall {n m} (x: word n), - wordToN (@zext n x m) = wordToN x. - Proof. - intros; induction x; simpl; intuition. - - - unfold zext, Word.combine. - rewrite wordToN_nat. - unfold wzero. - rewrite (@wordToNat_natToWord_idempotent m 0); simpl; intuition. - apply Npow2_gt0. - - - unfold zext in IHx; rewrite IHx; clear IHx; - destruct b; intuition. - Qed. - - Lemma wordToN_div2: forall {n} (x: word (S n)), - N.div2 (&x) = & (wtl x). - Proof. - intros. - pose proof (shatter_word x) as Hx; simpl in Hx; rewrite Hx; simpl. - destruct (whd x). - replace (match & wtl x with - | 0%N => 0%N - | N.pos q => N.pos (xO q) - end) - with (N.double (& (wtl x))) - by (induction (& (wtl x)); simpl; intuition). - - - rewrite N.div2_succ_double. - reflexivity. - - - induction (& (wtl x)); simpl; intuition. - Qed. - - Fixpoint wbit {n} (x: word n) (k: nat): bool := - match n as n' return word n' -> bool with - | O => fun _ => false - | S m => fun x' => - match k with - | O => (whd x') - | S k' => wbit (wtl x') k' - end - end x. - - Lemma wbit_wtl: forall {n} (x: word (S n)) k, - wbit x (S k) = wbit (wtl x) k. - Proof. - intros. - pose proof (shatter_word x) as Hx; - simpl in Hx; rewrite Hx; simpl. - reflexivity. - Qed. - - Lemma wordToN_testbit: forall {n} (x: word n) k, - N.testbit (& x) k = wbit x (N.to_nat k). - Proof. - assert (forall x: N, match x with - | 0%N => 0%N - | N.pos q => N.pos (q~0)%positive - end = N.double x) as kill_match by ( - induction x; simpl; intuition). - - induction n; intros. - - - shatter x; simpl; intuition. - - - revert IHn; rewrite <- (N2Nat.id k). - generalize (N.to_nat k) as k'; intros; clear k. - rewrite Nat2N.id in *. - - induction k'. - - + clear IHn; induction x; simpl; intuition. - destruct (& x), b; simpl; intuition. - - + clear IHk'. - shatter x; simpl. - - rewrite N.succ_double_spec; simpl. - - rewrite kill_match. - replace (N.pos (Pos.of_succ_nat k')) - with (N.succ (N.of_nat k')) - by (rewrite <- Nat2N.inj_succ; - simpl; intuition). - - rewrite N.double_spec. - replace (N.succ (2 * & wtl x)) - with (2 * & wtl x + 1)%N - by nomega. - - destruct (whd x); - try rewrite N.testbit_odd_succ; - try rewrite N.testbit_even_succ; - try abstract ( - unfold N.le; simpl; - induction (N.of_nat k'); intuition; - try inversion H); - rewrite IHn; - rewrite Nat2N.id; - reflexivity. - Qed. - - Lemma wordToN_split1: forall {n m} x, - & (@split1 n m x) = N.land (& x) (& (wones n)). - Proof. - intros. - - pose proof (Word.combine_split _ _ x) as C; revert C. - generalize (split1 n m x) as a, (split2 n m x) as b. - intros a b C; rewrite <- C; clear C x. - - apply N.bits_inj_iff; unfold N.eqf; intro x. - rewrite N.land_spec. - repeat rewrite wordToN_testbit. - revert x a b. - - induction n, m; intros; - shatter a; shatter b; - induction (N.to_nat x) as [|n0]; - try rewrite <- (Nat2N.id n0); - try rewrite andb_false_r; - try rewrite andb_true_r; - simpl; intuition. - Qed. - - Lemma wordToN_split2: forall {n m} x, - & (@split2 n m x) = N.shiftr (& x) (N.of_nat n). - Proof. - intros. - - pose proof (Word.combine_split _ _ x) as C; revert C. - generalize (split1 n m x) as a, (split2 n m x) as b. - intros a b C. - rewrite <- C; clear C x. - - apply N.bits_inj_iff; unfold N.eqf; intro x; - rewrite N.shiftr_spec; - repeat rewrite wordToN_testbit; - try apply N_ge_0. - - revert x a b. - induction n, m; intros; - shatter a; - try apply N_ge_0. - - - simpl; intuition. - - - replace (x + N.of_nat 0)%N with x by nomega. - simpl; intuition. - - - rewrite (IHn x (wtl a) b). - rewrite <- (N2Nat.id x). - repeat rewrite <- Nat2N.inj_add. - repeat rewrite Nat2N.id; simpl. - replace (N.to_nat x + S n) with (S (N.to_nat x + n)) by omega. - reflexivity. - - - rewrite (IHn x (wtl a) b). - rewrite <- (N2Nat.id x). - repeat rewrite <- Nat2N.inj_add. - repeat rewrite Nat2N.id; simpl. - replace (N.to_nat x + S n) with (S (N.to_nat x + n)) by omega. - reflexivity. - Qed. - - Lemma wordToN_combine: forall {n m} a b, - & (@Word.combine n a m b) = N.lxor (N.shiftl (& b) (N.of_nat n)) (& a). - Proof. - intros; symmetry. - - replace' a with (Word.split1 _ _ (Word.combine a b)) at 1 - by (apply Word.split1_combine). - - replace' b with (Word.split2 _ _ (Word.combine a b)) at 1 - by (apply Word.split2_combine). - - generalize (Word.combine a b); intro x; clear a b. - - rewrite wordToN_split1, wordToN_split2. - generalize (&x); clear x; intro x. - apply N.bits_inj_iff; unfold N.eqf; intro k. - - rewrite N.lxor_spec. - destruct (Nge_dec k (N.of_nat n)). - - - rewrite N.shiftl_spec_high; try apply N_ge_0; - try (apply ge_to_le; assumption). - rewrite N.shiftr_spec; try apply N_ge_0. - replace (k - N.of_nat n + N.of_nat n)%N with k by nomega. - rewrite N.land_spec. - induction (N.testbit x k); - replace (N.testbit (& wones n) k) with false; - simpl; intuition; - try apply testbit_wones_false; - try assumption. - - - rewrite N.shiftl_spec_low; try assumption; try apply N_ge_0. - rewrite N.land_spec. - induction (N.testbit x k); - replace (N.testbit (& wones n) k) with true; - simpl; intuition; - try apply testbit_wones_true; - try assumption. - Qed. - - Lemma wordToN_wones: forall x, & (wones x) = N.ones (N.of_nat x). - Proof. - induction x. - - - simpl; intuition. - - - rewrite Nat2N.inj_succ. - replace (& wones (S x)) with (2 * & (wones x) + N.b2n true)%N - by (simpl; rewrite ?N.succ_double_spec; simpl; nomega). - replace (N.ones (N.succ _)) - with (2 * N.ones (N.of_nat x) + N.b2n true)%N. - - + rewrite IHx; nomega. - - + replace (N.succ (N.of_nat x)) with (1 + (N.of_nat x))%N by ( - rewrite N.add_comm; nomega). - rewrite N.ones_add. - replace (N.ones 1) with 1%N by ( - unfold N.ones; simpl; intuition). - simpl. - reflexivity. - Qed. - - Lemma wordToN_zero: forall w, wordToN (wzero w) = 0%N. - Proof. - intros. - unfold wzero; rewrite wordToN_nat. - rewrite wordToNat_natToWord_idempotent; simpl; intuition. - apply Npow2_gt0. - Qed. - - Lemma NToWord_zero: forall w, NToWord w 0%N = wzero w. - Proof. - intros. - unfold wzero; rewrite NToWord_nat. - f_equal. - Qed. - - Ltac propagate_wordToN := - unfold extend, low, high, break; - repeat match goal with - | [|- context[@wordToN _ (@convS _ _ _ _)] ] => - rewrite wordToN_convS - | [|- context[@wordToN _ (@split1 _ _ _)] ] => - rewrite wordToN_split1 - | [|- context[@wordToN _ (@split2 _ _ _)] ] => - rewrite wordToN_split2 - | [|- context[@wordToN _ (@combine _ _ _ _)] ] => - rewrite wordToN_combine - | [|- context[@wordToN _ (@zext _ _ _)] ] => - rewrite wordToN_zext - | [|- context[@wordToN _ (@wones _)] ] => - rewrite wordToN_wones - end. - - Lemma break_spec: forall (m n: nat) (x: word n) low high, - (low, high) = break m x - -> &x = (&high * Npow2 m + &low)%N. - Proof. - intros m n x low high H. - unfold break in H. - destruct (le_dec m n). - - - inversion H; subst; clear H. - propagate_wordToN. - rewrite N.land_ones. - rewrite N.shiftr_div_pow2. - replace (n - (n - m)) with m by omega. - rewrite N.mul_comm. - rewrite Npow2_N. - rewrite <- (N.div_mod' (& x) (2 ^ (N.of_nat m))%N). - reflexivity. - - - inversion H; subst; clear H. - propagate_wordToN; simpl; nomega. - Qed. - - Lemma extend_bound: forall k n (p: (k <= n)%nat) (w: word k), - (& (extend p w) < Npow2 k)%N. - Proof. - intros. - propagate_wordToN. - apply word_size_bound. - Qed. - - Lemma mask_spec : forall (n: nat) (x: word n) m, - & (mask (N.to_nat m) x) = (N.land (& x) (N.ones m)). - Proof. - intros; unfold mask. - destruct (le_dec (N.to_nat m) n). - - - propagate_wordToN. - rewrite N2Nat.id. - reflexivity. - - - rewrite N.land_ones. - rewrite N.mod_small; try reflexivity. - rewrite <- (N2Nat.id m). - rewrite <- Npow2_N. - apply (N.lt_le_trans _ (Npow2 n) _); try apply word_size_bound. - apply Npow2_ordered. - omega. - Qed. - - Lemma mask_bound : forall (n: nat) (x: word n) m, - (& (mask m x) < Npow2 m)%N. - Proof. - intros; unfold mask. - destruct (le_dec m n). - - - apply extend_bound. - - - apply (N.lt_le_trans _ (Npow2 n) _); try apply word_size_bound. - apply Npow2_ordered. - omega. - Qed. - -End SpecialFunctions. - -Section TopLevel. - Local Open Scope nword_scope. - - Coercion ind : bool >-> N. - - Lemma wordize_plus: forall {n} (x y: word n), - (&x + &y < Npow2 n)%N - -> (&x + &y)%N = & (x ^+ y). - Proof. - intros n x y H. - pose proof (word_size_bound x) as Hbx. - pose proof (word_size_bound y) as Hby. - - unfold wplus, wordBin. - rewrite wordToN_NToWord; intuition. - Qed. - - Lemma wordize_awc: forall {n} (x y: word n) (c: bool), - (&x + &y + c < Npow2 n)%N - -> (&x + &y + c)%N = &(addWithCarry x y c). - Proof. - intros n x y c H. - unfold wplus, wordBin, addWithCarry. - destruct c; simpl in *. - - - replace 1%N with (wordToN (natToWord n 1)) in * by ( - rewrite wordToN_nat; - rewrite wordToNat_natToWord_idempotent; - nomega). - - rewrite <- N.add_assoc. - rewrite wordize_plus; try nomega. - rewrite wordize_plus; try nomega. - - + rewrite wplus_assoc. - reflexivity. - - + apply (N.le_lt_trans _ (& x + & y + & natToWord n 1)%N _); - try assumption. - rewrite <- N.add_assoc. - apply N.add_le_mono. - - * apply N.eq_le_incl; reflexivity. - - * apply plus_le. - - - rewrite wplus_comm. - rewrite wplus_unit. - rewrite N.add_0_r in *. - apply wordize_plus; assumption. - Qed. - - Lemma wordize_minus: forall {n} (x y: word n), - (&x >= &y)%N -> (&x - &y)%N = &(x ^- y). - Proof. - intros n x y H. - - destruct (Nge_dec 0%N (&y)). { - unfold wminus, wneg. - replace (& y) with 0%N in * by nomega. - replace (Npow2 n - 0)%N with (& (wzero n) + Npow2 n)%N - by (rewrite wordToN_zero; nomega). - rewrite <- Npow2_ignore. - rewrite wplus_comm. - rewrite wplus_unit. - nomega. - } - - assert (& x - & y < Npow2 n)%N. { - transitivity (wordToN x); - try apply word_size_bound; - apply N.sub_lt; - [apply N.ge_le|]; assumption. - } - - assert (& x - & y + & y < Npow2 n)%N. { - replace (& x - & y + & y)%N - with (wordToN x) by nomega; - apply word_size_bound. - } - - assert (x = NToWord n (wordToN x - wordToN y) ^+ y) as Hv. { - apply NToWord_equal. - rewrite <- wordize_plus; rewrite wordToN_NToWord; try assumption. - nomega. - } - - symmetry. - rewrite Hv at 1. - unfold wminus. - repeat rewrite <- wplus_assoc. - rewrite wminus_inv. - rewrite wplus_comm. - rewrite wplus_unit. - rewrite wordToN_NToWord; try assumption. - reflexivity. - Qed. - - Lemma wordize_mult: forall {n} (x y: word n), - (&x * &y < Npow2 n)%N - -> (&x * &y)%N = &(x ^* y). - Proof. - intros n x y H. - pose proof (word_size_bound x) as Hbx. - pose proof (word_size_bound y) as Hby. - - unfold wmult, wordBin. - rewrite wordToN_NToWord; intuition. - Qed. - - Lemma wordize_shiftr: forall {n} (x: word n) (k: nat), - (N.shiftr_nat (&x) k) = & (shiftr x k). - Proof. - intros n x k. - unfold shiftr, extend, high. - destruct (le_dec k n). - - - repeat first [ - rewrite wordToN_convS - | rewrite wordToN_zext - | rewrite wordToN_split2 ]. - rewrite <- Nshiftr_equiv_nat. - reflexivity. - - - rewrite (wordToN_nat (wzero n)); unfold wzero. - destruct (Nat.eq_dec n O); subst. - - + rewrite (shatter_word_0 x); simpl; intuition. - rewrite <- Nshiftr_equiv_nat. - rewrite N.shiftr_0_l. - reflexivity. - - + rewrite wordToNat_natToWord_idempotent; - try nomega. - - * pose proof (word_size_bound x). - rewrite <- Nshiftr_equiv_nat. - rewrite N.shiftr_eq_0_iff. - destruct (N.eq_dec (&x) 0%N) as [E|E]; - try rewrite E in *; - try abstract (left; reflexivity). - - right; split; try nomega. - apply (N.le_lt_trans _ (N.log2 (Npow2 n)) _). { - apply N.log2_le_mono. - apply N.lt_le_incl. - assumption. - } - - rewrite Npow2_N. - rewrite N.log2_pow2; try nomega. - apply N_ge_0. - - * simpl; apply Npow2_gt0. - Qed. - - Lemma wordize_and: forall {n} (x y: word n), - & (wand x y) = N.land (&x) (&y). - Proof. - intros. - apply N.bits_inj_iff; unfold N.eqf; intro k. - rewrite N.land_spec. - repeat rewrite wordToN_testbit. - revert x y. - generalize (N.to_nat k) as k'; clear k. - induction n; intros; shatter x; shatter y; simpl; [reflexivity|]. - induction k'; [reflexivity|]. - fold wand. - rewrite IHn. - reflexivity. - Qed. - - Lemma wordize_or: forall {n} (x y: word n), - & (wor x y) = N.lor (&x) (&y). - Proof. - intros. - apply N.bits_inj_iff; unfold N.eqf; intro k. - rewrite N.lor_spec. - repeat rewrite wordToN_testbit. - revert x y. - generalize (N.to_nat k) as k'; clear k. - induction n; intros; shatter x; shatter y; simpl; [reflexivity|]. - induction k'; [reflexivity|]. - rewrite IHn. - reflexivity. - Qed. - - Lemma conv_mask: forall {n} (x: word n) (k: nat), - (k <= n)%nat -> - mask k x = x ^& (NToWord _ (N.ones (N.of_nat k))). - Proof. - intros n x k H. - apply NToWord_equal. - - rewrite <- (Nat2N.id k). - rewrite mask_spec. - apply N.bits_inj_iff; unfold N.eqf; intro m. - rewrite N.land_spec. - repeat rewrite wordToN_testbit. - rewrite <- (N2Nat.id m). - rewrite <- wordToN_wones. - repeat rewrite wordToN_testbit. - repeat rewrite N2Nat.id. - rewrite <- wordToN_wones. - - assert (forall n (a b: word n) k, - wbit (a ^& b) k = andb (wbit a k) (wbit b k)) as Hwand. { - intros n0 a b. - induction n0 as [|n1]; - shatter a; shatter b; - simpl; try reflexivity. - - intro k0; induction k0 as [|k0]; - simpl; try reflexivity. - - fold wand. - rewrite IHn1. - reflexivity. - } - - rewrite Hwand; clear Hwand. - induction (wbit x (N.to_nat m)); - repeat rewrite andb_false_l; - repeat rewrite andb_true_l; - try reflexivity. - - repeat rewrite <- wordToN_testbit. - rewrite wordToN_NToWord; try reflexivity. - apply (N.lt_le_trans _ (Npow2 k) _). - - + apply word_size_bound. - - + apply Npow2_ordered. - omega. - Qed. - - Close Scope nword_scope. -End TopLevel. diff --git a/src/BaseSystem.v b/src/BaseSystem.v deleted file mode 100644 index 5d48c0977..000000000 --- a/src/BaseSystem.v +++ /dev/null @@ -1,212 +0,0 @@ -Require Import Coq.Lists.List. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zdiv. -Require Import Coq.omega.Omega Coq.Numbers.Natural.Peano.NPeano Coq.Arith.Arith. -Require Import Crypto.Util.ListUtil Crypto.Util.CaseUtil Crypto.Util.ZUtil. -Require Import Crypto.Util.Notations. -Require Export Crypto.Util.FixCoqMistakes. -Import Nat. - -Local Open Scope Z. - -Class BaseVector (base : list Z):= { - base_positive : forall b, In b base -> b > 0; (* nonzero would probably work too... *) - b0_1 : forall x, nth_default x base 0 = 1; (** TODO(jadep,jgross): change to [nth_error base 0 = Some 1], then use [nth_error_value_eq_nth_default] to prove a [forall x, nth_default x base 0 = 1] as a lemma *) - base_good : - forall i j, (i+j < length base)%nat -> - let b := nth_default 0 base in - let r := (b i * b j) / b (i+j)%nat in - b i * b j = r * b (i+j)%nat -}. - -Section BaseSystem. - Context (base : list Z). - (** [BaseSystem] implements an constrained positional number system. - A wide variety of bases are supported: the base coefficients are not - required to be powers of 2, and it is NOT necessarily the case that - $b_{i+j} = b_i b_j$. Implementations of addition and multiplication are - provided, with focus on near-optimal multiplication performance on - non-trivial but small operands: maybe 10 32-bit integers or so. This - module does not handle carries automatically: if no restrictions are put - on the use of a [BaseSystem], each digit is unbounded. This has nothing - to do with modular arithmetic either. - *) - Definition digits : Type := list Z. - - Definition accumulate p acc := fst p * snd p + acc. - Definition decode' bs u := fold_right accumulate 0 (combine u bs). - Definition decode := decode' base. - - (* i is current index, counts down *) - Fixpoint encode' z max i : digits := - match i with - | O => nil - | S i' => let b := nth_default max base in - encode' z max i' ++ ((z mod (b i)) / (b i')) :: nil - end. - - (* max must be greater than input; this is used to truncate last digit *) - Definition encode z max := encode' z max (length base). - - Lemma decode'_truncate : forall bs us, decode' bs us = decode' bs (firstn (length bs) us). - Proof using Type. - unfold decode'; intros; f_equal; apply combine_truncate_l. - Qed. - - Fixpoint add (us vs:digits) : digits := - match us,vs with - | u::us', v::vs' => u+v :: add us' vs' - | _, nil => us - | _, _ => vs - end. - Infix ".+" := add. - - Hint Extern 1 (@eq Z _ _) => ring. - - Definition mul_each u := map (Z.mul u). - Fixpoint sub (us vs:digits) : digits := - match us,vs with - | u::us', v::vs' => u-v :: sub us' vs' - | _, nil => us - | nil, v::vs' => (0-v)::sub nil vs' - end. - - Definition crosscoef i j : Z := - let b := nth_default 0 base in - (b(i) * b(j)) / b(i+j)%nat. - Hint Unfold crosscoef. - - Fixpoint zeros n := match n with O => nil | S n' => 0::zeros n' end. - - (* mul' is multiplication with the SECOND ARGUMENT REVERSED and OUTPUT REVERSED *) - Fixpoint mul_bi' (i:nat) (vsr:digits) := - match vsr with - | v::vsr' => v * crosscoef i (length vsr') :: mul_bi' i vsr' - | nil => nil - end. - Definition mul_bi (i:nat) (vs:digits) : digits := - zeros i ++ rev (mul_bi' i (rev vs)). - - (* mul' is multiplication with the FIRST ARGUMENT REVERSED *) - Fixpoint mul' (usr vs:digits) : digits := - match usr with - | u::usr' => - mul_each u (mul_bi (length usr') vs) .+ mul' usr' vs - | _ => nil - end. - Definition mul us := mul' (rev us). - -End BaseSystem. - -(* Example : polynomial base system *) -Section PolynomialBaseCoefs. - Context (b1 : positive) (baseLength : nat) (baseLengthNonzero : ltb 0 baseLength = true). - (** PolynomialBaseCoefs generates base vectors for [BaseSystem]. *) - Definition bi i := (Zpos b1)^(Z.of_nat i). - Definition poly_base := map bi (seq 0 baseLength). - - Lemma poly_b0_1 : forall x, nth_default x poly_base 0 = 1. - Proof using baseLengthNonzero. - - unfold poly_base, bi, nth_default. - case_eq baseLength; intros. { - assert ((0 < baseLength)%nat) by - (rewrite <-ltb_lt; apply baseLengthNonzero). - subst; omega. - } - auto. - Qed. - - Lemma poly_base_positive : forall b, In b poly_base -> b > 0. - Proof using Type. - unfold poly_base. - intros until 0; intro H. - rewrite in_map_iff in *. - destruct H; destruct H. - subst. - apply Z.pos_pow_nat_pos. - Qed. - - Lemma poly_base_defn : forall i, (i < length poly_base)%nat -> - nth_default 0 poly_base i = bi i. - Proof using Type. - unfold poly_base, nth_default; nth_tac. - Qed. - - Lemma poly_base_succ : - forall i, ((S i) < length poly_base)%nat -> - let b := nth_default 0 poly_base in - let r := (b (S i) / b i) in - b (S i) = r * b i. - Proof using Type. - intros; subst b; subst r. - repeat rewrite poly_base_defn in * by omega. - unfold bi. - replace (Z.pos b1 ^ Z.of_nat (S i)) - with (Z.pos b1 * (Z.pos b1 ^ Z.of_nat i)) by - (rewrite Nat2Z.inj_succ; rewrite <- Z.pow_succ_r; intuition auto with zarith). - replace (Z.pos b1 * Z.pos b1 ^ Z.of_nat i / Z.pos b1 ^ Z.of_nat i) - with (Z.pos b1); auto. - rewrite Z_div_mult_full; auto. - apply Z.pow_nonzero; intuition auto with lia. - Qed. - - Lemma poly_base_good: - forall i j, (i + j < length poly_base)%nat -> - let b := nth_default 0 poly_base in - let r := (b i * b j) / b (i+j)%nat in - b i * b j = r * b (i+j)%nat. - Proof using Type. - unfold poly_base, nth_default; nth_tac. - - clear. - unfold bi. - rewrite Nat2Z.inj_add, Zpower_exp by - (replace 0 with (Z.of_nat 0) by auto; rewrite <- Nat2Z.inj_ge; omega). - rewrite Z_div_same_full; try ring. - rewrite <- Z.neq_mul_0. - split; apply Z.pow_nonzero; try apply Zle_0_nat; try solve [intro H; inversion H]. - Qed. - - Instance PolyBaseVector : BaseVector poly_base := { - base_positive := poly_base_positive; - b0_1 := poly_b0_1; - base_good := poly_base_good - }. - -End PolynomialBaseCoefs. - -Import ListNotations. - -Section BaseSystemExample. - Definition baseLength := 32%nat. - Lemma baseLengthNonzero : ltb 0 baseLength = true. - compute; reflexivity. - Qed. - Definition base2 := poly_base 2 baseLength. - - Example three_times_two : mul base2 [1;1;0] [0;1;0] = [0;1;1;0;0]. - Proof. - reflexivity. - Qed. - - (* python -c "e = lambda x: '['+''.join(reversed(bin(x)[2:])).replace('1','1;').replace('0','0;')[:-1]+']'; print(e(19259)); print(e(41781))" *) - Definition a := [1;1;0;1;1;1;0;0;1;1;0;1;0;0;1]. - Definition b := [1;0;1;0;1;1;0;0;1;1;0;0;0;1;0;1]. - Example da : decode base2 a = 19259. - Proof. - reflexivity. - Qed. - Example db : decode base2 b = 41781. - Proof. - reflexivity. - Qed. - Example encoded_ab : - mul base2 a b =[1;1;1;2;2;4;2;2;4;5;3;3;3;6;4;2;5;3;4;3;2;1;2;2;2;0;1;1;0;1]. - Proof. - reflexivity. - Qed. - Example dab : decode base2 (mul base2 a b) = 804660279. - Proof. - reflexivity. - Qed. -End BaseSystemExample. diff --git a/src/BaseSystemProofs.v b/src/BaseSystemProofs.v deleted file mode 100644 index 409d8b7db..000000000 --- a/src/BaseSystemProofs.v +++ /dev/null @@ -1,710 +0,0 @@ -Require Import Coq.Lists.List Coq.micromega.Psatz. -Require Import Crypto.Util.ListUtil Crypto.Util.CaseUtil Crypto.Util.ZUtil. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zdiv. -Require Import Coq.omega.Omega Coq.Numbers.Natural.Peano.NPeano Coq.Arith.Arith. -Require Import Crypto.BaseSystem. -Require Import Crypto.Util.Notations. -Import Morphisms. -Local Open Scope Z. - -Local Infix ".+" := add. - -Local Hint Extern 1 (@eq Z _ _) => ring. - -Section BaseSystemProofs. - Context `(base_vector : BaseVector). - - Lemma decode'_truncate : forall bs us, decode' bs us = decode' bs (firstn (length bs) us). - Proof using Type. - unfold decode'; intros; f_equal; apply combine_truncate_l. - Qed. - - Lemma decode'_splice : forall xs ys bs, - decode' bs (xs ++ ys) = - decode' (firstn (length xs) bs) xs + decode' (skipn (length xs) bs) ys. - Proof using Type. - unfold decode'. - induction xs; destruct ys, bs; boring. - + rewrite combine_truncate_r. - do 2 rewrite Z.add_0_r; auto. - + unfold accumulate. - apply Z.add_assoc. - Qed. - - Lemma add_rep : forall bs us vs, decode' bs (add us vs) = decode' bs us + decode' bs vs. - Proof using Type. - unfold decode', accumulate; induction bs; destruct us, vs; boring; ring. - Qed. - - Lemma decode_nil : forall bs, decode' bs nil = 0. - Proof using Type. - - auto. - Qed. - Hint Rewrite decode_nil. - - Lemma decode_base_nil : forall us, decode' nil us = 0. - Proof using Type. - intros; rewrite decode'_truncate; auto. - Qed. - - Hint Rewrite decode_base_nil. - - Lemma mul_each_rep : forall bs u vs, - decode' bs (mul_each u vs) = u * decode' bs vs. - Proof using Type. - unfold decode', accumulate; induction bs; destruct vs; boring; ring. - Qed. - - Lemma base_eq_1cons: base = 1 :: skipn 1 base. - Proof using Type*. - pose proof (b0_1 0) as H. - destruct base; compute in H; try discriminate; boring. - Qed. - - Lemma decode'_cons : forall x1 x2 xs1 xs2, - decode' (x1 :: xs1) (x2 :: xs2) = x1 * x2 + decode' xs1 xs2. - Proof using Type. - unfold decode', accumulate; boring; ring. - Qed. - Hint Rewrite decode'_cons. - - Lemma decode_cons : forall x us, - decode base (x :: us) = x + decode base (0 :: us). - Proof using Type*. - unfold decode; intros. - rewrite base_eq_1cons. - autorewrite with core; ring_simplify; auto. - Qed. - - Lemma decode'_map_mul : forall v xs bs, - decode' (map (Z.mul v) bs) xs = - Z.mul v (decode' bs xs). - Proof using Type. - unfold decode'. - induction xs; destruct bs; boring. - unfold accumulate; simpl; nia. - Qed. - - Lemma decode_map_mul : forall v xs, - decode (map (Z.mul v) base) xs = - Z.mul v (decode base xs). - Proof using Type. - unfold decode; intros; apply decode'_map_mul. - Qed. - - Lemma sub_rep : forall bs us vs, decode' bs (sub us vs) = decode' bs us - decode' bs vs. - Proof using Type. - induction bs; destruct us; destruct vs; boring; ring. - Qed. - - Lemma nth_default_base_nonzero : forall d, d <> 0 -> - forall i, nth_default d base i <> 0. - Proof using Type*. - intros. - rewrite nth_default_eq. - destruct (nth_in_or_default i base d). - + auto using Z.positive_is_nonzero, base_positive. - + congruence. - Qed. - - Lemma nth_default_base_pos : forall d, 0 < d -> - forall i, 0 < nth_default d base i. - Proof using Type*. - intros. - rewrite nth_default_eq. - destruct (nth_in_or_default i base d). - + apply Z.gt_lt; auto using base_positive. - + congruence. - Qed. - - Lemma mul_each_base : forall us bs c, - decode' bs (mul_each c us) = decode' (mul_each c bs) us. - Proof using Type. - induction us; destruct bs; boring; ring. - Qed. - - Hint Rewrite (@nth_default_nil Z). - Hint Rewrite (@firstn_nil Z). - Hint Rewrite (@skipn_nil Z). - - Lemma base_app : forall us low high, - decode' (low ++ high) us = decode' low (firstn (length low) us) + decode' high (skipn (length low) us). - Proof using Type. - induction us; destruct low; boring. - Qed. - - Lemma base_mul_app : forall low c us, - decode' (low ++ mul_each c low) us = decode' low (firstn (length low) us) + - c * decode' low (skipn (length low) us). - Proof using Type. - intros. - rewrite base_app; f_equal. - rewrite <- mul_each_rep. - rewrite mul_each_base. - reflexivity. - Qed. - - Lemma zeros_rep : forall bs n, decode' bs (zeros n) = 0. - Proof using Type. - - induction bs; destruct n; boring. - Qed. - Lemma length_zeros : forall n, length (zeros n) = n. - Proof using Type. - - induction n; boring. - Qed. - Hint Rewrite length_zeros. - - Lemma app_zeros_zeros : forall n m, zeros n ++ zeros m = zeros (n + m)%nat. - Proof using Type. - induction n; boring. - Qed. - Hint Rewrite app_zeros_zeros. - - Lemma zeros_app0 : forall m, zeros m ++ 0 :: nil = zeros (S m). - Proof using Type. - induction m; boring. - Qed. - Hint Rewrite zeros_app0. - - Lemma nth_default_zeros : forall n i, nth_default 0 (BaseSystem.zeros n) i = 0. - Proof using Type. - induction n; intros; [ cbv [BaseSystem.zeros]; apply nth_default_nil | ]. - rewrite <-zeros_app0, nth_default_app. - rewrite length_zeros. - destruct (lt_dec i n); auto. - destruct (eq_nat_dec i n); subst. - + rewrite Nat.sub_diag; apply nth_default_cons. - + apply nth_default_out_of_bounds. - cbv [length]; omega. - Qed. - - Lemma rev_zeros : forall n, rev (zeros n) = zeros n. - Proof using Type. - induction n; boring. - Qed. - Hint Rewrite rev_zeros. - - Hint Unfold nth_default. - - Lemma decode_single : forall n bs x, - decode' bs (zeros n ++ x :: nil) = nth_default 0 bs n * x. - Proof using Type. - induction n; destruct bs; boring. - Qed. - Hint Rewrite decode_single. - - Lemma peel_decode : forall xs ys x y, decode' (x::xs) (y::ys) = x*y + decode' xs ys. - Proof using Type. - boring. - Qed. - Hint Rewrite zeros_rep peel_decode. - - Lemma decode_Proper : Proper (Logic.eq ==> (Forall2 Logic.eq) ==> Logic.eq) decode'. - Proof using Type. - repeat intro; subst. - revert y y0 H0; induction x0; intros. - + inversion H0. rewrite !decode_nil. - reflexivity. - + inversion H0; subst. - destruct y as [|y0 y]; [rewrite !decode_base_nil; reflexivity | ]. - specialize (IHx0 y _ H4). - rewrite !peel_decode. - f_equal; auto. - Qed. - - Lemma decode_highzeros : forall xs bs n, decode' bs (xs ++ zeros n) = decode' bs xs. - Proof using Type. - induction xs; destruct bs; boring. - Qed. - - Lemma mul_bi'_zeros : forall n m, mul_bi' base n (zeros m) = zeros m. - Proof using Type. - - induction m; boring. - Qed. - Hint Rewrite mul_bi'_zeros. - - Lemma nth_error_base_nonzero : forall n x, - nth_error base n = Some x -> x <> 0. - Proof using Type*. - eauto using (@nth_error_value_In Z), Z.gt0_neq0, base_positive. - Qed. - - Hint Rewrite plus_0_r. - - Lemma mul_bi_single : forall m n x, - (n + m < length base)%nat -> - decode base (mul_bi base n (zeros m ++ x :: nil)) = nth_default 0 base m * x * nth_default 0 base n. - Proof using Type*. - unfold mul_bi, decode. - destruct m; simpl; simpl_list; simpl; intros. { - pose proof nth_error_base_nonzero as nth_nonzero. - case_eq base; [intros; boring | intros z l base_eq]. - specialize (b0_1 0); intro b0_1'. - rewrite base_eq in *. - rewrite nth_default_cons in b0_1'. - rewrite b0_1' in *. - unfold crosscoef. - autounfold; autorewrite with core. - unfold nth_default. - nth_tac. - rewrite Z.mul_1_r. - rewrite Z_div_same_full. - destruct x; ring. - eapply nth_nonzero; eauto. - } { - ssimpl_list. - autorewrite with core. - rewrite app_assoc. - autorewrite with core. - unfold crosscoef; simpl; ring_simplify. - rewrite Nat.add_1_r. - rewrite base_good by auto. - rewrite Z_div_mult by (apply base_positive; rewrite nth_default_eq; apply nth_In; auto). - rewrite <- Z.mul_assoc. - rewrite <- Z.mul_comm. - rewrite <- Z.mul_assoc. - rewrite <- Z.mul_assoc. - destruct (Z.eq_dec x 0); subst; try ring. - rewrite Z.mul_cancel_l by auto. - rewrite <- base_good by auto. - ring. - } - Qed. - - Lemma set_higher' : forall vs x, vs++x::nil = vs .+ (zeros (length vs) ++ x :: nil). - Proof using Type. - - induction vs; boring; f_equal; ring. - Qed. - - Lemma set_higher : forall bs vs x, - decode' bs (vs++x::nil) = decode' bs vs + nth_default 0 bs (length vs) * x. - Proof using Type. - intros. - rewrite set_higher'. - rewrite add_rep. - f_equal. - apply decode_single. - Qed. - - Lemma zeros_plus_zeros : forall n, zeros n = zeros n .+ zeros n. - Proof using Type. - - induction n; auto. - simpl; f_equal; auto. - Qed. - - Lemma mul_bi'_n_nil : forall n, mul_bi' base n nil = nil. - Proof using Type. - unfold mul_bi; auto. - Qed. - Hint Rewrite mul_bi'_n_nil. - - Lemma add_nil_l : forall us, nil .+ us = us. - Proof using Type. - - induction us; auto. - Qed. - Hint Rewrite add_nil_l. - - Lemma add_nil_r : forall us, us .+ nil = us. - Proof using Type. - - induction us; auto. - Qed. - Hint Rewrite add_nil_r. - - Lemma add_first_terms : forall us vs a b, - (a :: us) .+ (b :: vs) = (a + b) :: (us .+ vs). - Proof using Type. - - auto. - Qed. - Hint Rewrite add_first_terms. - - Lemma mul_bi'_cons : forall n x us, - mul_bi' base n (x :: us) = x * crosscoef base n (length us) :: mul_bi' base n us. - Proof using Type. - unfold mul_bi'; auto. - Qed. - - Lemma add_same_length : forall us vs l, (length us = l) -> (length vs = l) -> - length (us .+ vs) = l. - Proof using Type. - induction us, vs; boring. - erewrite (IHus vs (pred l)); boring. - Qed. - - Hint Rewrite app_nil_l. - Hint Rewrite app_nil_r. - - Lemma add_snoc_same_length : forall l us vs a b, - (length us = l) -> (length vs = l) -> - (us ++ a :: nil) .+ (vs ++ b :: nil) = (us .+ vs) ++ (a + b) :: nil. - Proof using Type. - induction l, us, vs; boring; discriminate. - Qed. - - Lemma mul_bi'_add : forall us n vs l - (Hlus: length us = l) - (Hlvs: length vs = l), - mul_bi' base n (rev (us .+ vs)) = - mul_bi' base n (rev us) .+ mul_bi' base n (rev vs). - Proof using Type. - (* TODO(adamc): please help prettify this *) - induction us using rev_ind; - try solve [destruct vs; boring; congruence]. - destruct vs using rev_ind; boring; clear IHvs; simpl_list. - erewrite (add_snoc_same_length (pred l) us vs _ _); simpl_list. - repeat rewrite mul_bi'_cons; rewrite add_first_terms; simpl_list. - rewrite (IHus n vs (pred l)). - replace (length us) with (pred l). - replace (length vs) with (pred l). - rewrite (add_same_length us vs (pred l)). - f_equal; ring. - - erewrite length_snoc; eauto. - erewrite length_snoc; eauto. - erewrite length_snoc; eauto. - erewrite length_snoc; eauto. - erewrite length_snoc; eauto. - erewrite length_snoc; eauto. - erewrite length_snoc; eauto. - erewrite length_snoc; eauto. - Qed. - - Lemma zeros_cons0 : forall n, 0 :: zeros n = zeros (S n). - Proof using Type. - - auto. - Qed. - - Lemma add_leading_zeros : forall n us vs, - (zeros n ++ us) .+ (zeros n ++ vs) = zeros n ++ (us .+ vs). - Proof using Type. - induction n; boring. - Qed. - - Lemma rev_add_rev : forall us vs l, (length us = l) -> (length vs = l) -> - (rev us) .+ (rev vs) = rev (us .+ vs). - Proof using Type. - induction us, vs; boring; try solve [subst; discriminate]. - rewrite (add_snoc_same_length (pred l) _ _ _ _) by (subst; simpl_list; omega). - rewrite (IHus vs (pred l)) by omega; auto. - Qed. - Hint Rewrite rev_add_rev. - - Lemma mul_bi'_length : forall us n, length (mul_bi' base n us) = length us. - Proof using Type. - induction us, n; boring. - Qed. - Hint Rewrite mul_bi'_length. - - Lemma add_comm : forall us vs, us .+ vs = vs .+ us. - Proof using Type. - induction us, vs; boring; f_equal; auto. - Qed. - - Hint Rewrite rev_length. - - Lemma mul_bi_add_same_length : forall n us vs l, - (length us = l) -> (length vs = l) -> - mul_bi base n (us .+ vs) = mul_bi base n us .+ mul_bi base n vs. - Proof using Type. - unfold mul_bi; boring. - rewrite add_leading_zeros. - erewrite mul_bi'_add; boring. - erewrite rev_add_rev; boring. - Qed. - - Lemma add_zeros_same_length : forall us, us .+ (zeros (length us)) = us. - Proof using Type. - induction us; boring; f_equal; omega. - Qed. - - Hint Rewrite add_zeros_same_length. - Hint Rewrite minus_diag. - - Lemma add_trailing_zeros : forall us vs, (length us >= length vs)%nat -> - us .+ vs = us .+ (vs ++ (zeros (length us - length vs)%nat)). - Proof using Type. - induction us, vs; boring; f_equal; boring. - Qed. - - Lemma length_add_ge : forall us vs, (length us >= length vs)%nat -> - (length (us .+ vs) <= length us)%nat. - Proof using Type. - intros. - rewrite add_trailing_zeros by trivial. - erewrite add_same_length by (pose proof app_length; boring); omega. - Qed. - - Lemma add_length_le_max : forall us vs, - (length (us .+ vs) <= max (length us) (length vs))%nat. - Proof using Type. - intros; case_max; (rewrite add_comm; apply length_add_ge; omega) || - (apply length_add_ge; omega) . - Qed. - - Lemma sub_nil_length: forall us : digits, length (sub nil us) = length us. - Proof using Type. - induction us; boring. - Qed. - - Lemma sub_length : forall us vs, - (length (sub us vs) = max (length us) (length vs))%nat. - Proof using Type. - induction us, vs; boring. - rewrite sub_nil_length; auto. - Qed. - - Lemma mul_bi_length : forall us n, length (mul_bi base n us) = (length us + n)%nat. - Proof using Type. - pose proof mul_bi'_length; unfold mul_bi. - destruct us; repeat progress (simpl_list; boring). - Qed. - Hint Rewrite mul_bi_length. - - Lemma mul_bi_trailing_zeros : forall m n us, - mul_bi base n us ++ zeros m = mul_bi base n (us ++ zeros m). - Proof using Type. - unfold mul_bi. - induction m; intros; try solve [boring]. - rewrite <- zeros_app0. - rewrite app_assoc. - repeat progress (boring; rewrite rev_app_distr). - Qed. - - Lemma mul_bi_add_longer : forall n us vs, - (length us >= length vs)%nat -> - mul_bi base n (us .+ vs) = mul_bi base n us .+ mul_bi base n vs. - Proof using Type. - boring. - rewrite add_trailing_zeros by auto. - rewrite (add_trailing_zeros (mul_bi base n us) (mul_bi base n vs)) - by (repeat (rewrite mul_bi_length); omega). - erewrite mul_bi_add_same_length by - (eauto; simpl_list; rewrite length_zeros; omega). - rewrite mul_bi_trailing_zeros. - repeat (f_equal; boring). - Qed. - - Lemma mul_bi_add : forall n us vs, - mul_bi base n (us .+ vs) = (mul_bi base n us) .+ (mul_bi base n vs). - Proof using Type. - intros; pose proof mul_bi_add_longer. - destruct (le_ge_dec (length us) (length vs)). { - rewrite add_comm. - rewrite (add_comm (mul_bi base n us)). - boring. - } { - boring. - } - Qed. - - Lemma mul_bi_rep : forall i vs, - (i + length vs < length base)%nat -> - decode base (mul_bi base i vs) = decode base vs * nth_default 0 base i. - Proof using Type*. - unfold decode. - induction vs using rev_ind; intros; try solve [unfold mul_bi; boring]. - assert (i + length vs < length base)%nat by - (rewrite app_length in *; boring). - - rewrite set_higher. - ring_simplify. - rewrite <- IHvs by auto; clear IHvs. - rewrite <- mul_bi_single by auto. - rewrite <- add_rep. - rewrite <- mul_bi_add. - rewrite set_higher'. - auto. - Qed. - - Local Notation mul' := (mul' base). - Local Notation mul := (mul base). - - Lemma mul'_rep : forall us vs, - (length us + length vs <= length base)%nat -> - decode base (mul' (rev us) vs) = decode base us * decode base vs. - Proof using Type*. - unfold decode. - induction us using rev_ind; boring. - - assert (length us + length vs < length base)%nat by - (rewrite app_length in *; boring). - - ssimpl_list. - rewrite add_rep. - boring. - rewrite set_higher. - rewrite mul_each_rep. - rewrite mul_bi_rep by auto. - unfold decode; ring. - Qed. - - Lemma mul_rep : forall us vs, - (length us + length vs <= length base)%nat -> - decode base (mul us vs) = decode base us * decode base vs. - Proof using Type*. - exact mul'_rep. - Qed. - - Lemma mul'_length: forall us vs, - (length (mul' us vs) <= length us + length vs)%nat. - Proof using Type. - pose proof add_length_le_max. - induction us; boring. - unfold mul_each. - simpl_list; case_max; boring; omega. - Qed. - - Lemma mul_length: forall us vs, - (length (mul us vs) <= length us + length vs)%nat. - Proof using Type. - intros; unfold BaseSystem.mul. - rewrite mul'_length. - rewrite rev_length; omega. - Qed. - - Lemma add_length_exact : forall us vs, - length (us .+ vs) = max (length us) (length vs). - Proof using Type. - induction us; destruct vs; boring. - Qed. - - Hint Rewrite add_length_exact : distr_length. - - Lemma mul'_length_exact_full: forall us vs, - (length (mul' us vs) = match length us with - | 0 => 0%nat - | _ => pred (length us + length vs) - end)%nat. - Proof using Type. - induction us; intros; try solve [boring]. - unfold BaseSystem.mul'; fold mul'. - unfold mul_each. - rewrite add_length_exact, map_length, mul_bi_length, length_cons. - destruct us. - + rewrite Max.max_0_r. simpl; omega. - + rewrite Max.max_l; [ omega | ]. - rewrite IHus by ( congruence || simpl in *; omega). - simpl; omega. - Qed. - - Hint Rewrite mul'_length_exact_full : distr_length. - - (* TODO(@jadephilipoom, from jgross): one of these conditions isn't - needed. Should it be dropped, or was there a reason to keep it? *) - Lemma mul'_length_exact: forall us vs, - (length us <= length vs)%nat -> us <> nil -> - (length (mul' us vs) = pred (length us + length vs))%nat. - Proof using Type. - intros; rewrite mul'_length_exact_full; destruct us; simpl; congruence. - Qed. - - Lemma mul_length_exact_full: forall us vs, - (length (mul us vs) = match length us with - | 0 => 0 - | _ => pred (length us + length vs) - end)%nat. - Proof using Type. - intros; unfold BaseSystem.mul; autorewrite with distr_length; reflexivity. - Qed. - - Hint Rewrite mul_length_exact_full : distr_length. - - (* TODO(@jadephilipoom, from jgross): one of these conditions isn't - needed. Should it be dropped, or was there a reason to keep it? *) - Lemma mul_length_exact: forall us vs, - (length us <= length vs)%nat -> us <> nil -> - (length (mul us vs) = pred (length us + length vs))%nat. - Proof using Type. - intros; unfold BaseSystem.mul. - rewrite mul'_length_exact; rewrite ?rev_length; try omega. - intro rev_nil. - match goal with H : us <> nil |- _ => apply H end. - apply length0_nil; rewrite <-rev_length, rev_nil. - reflexivity. - Qed. - Definition encode'_zero z max : encode' base z max 0%nat = nil := eq_refl. - Definition encode'_succ z max i : encode' base z max (S i) = - encode' base z max i ++ ((z mod (nth_default max base (S i))) / (nth_default max base i)) :: nil := eq_refl. - Opaque encode'. - Hint Resolve encode'_zero encode'_succ. - - Lemma encode'_length : forall z max i, length (encode' base z max i) = i. - Proof using Type. - induction i; auto. - rewrite encode'_succ, app_length, IHi. - cbv [length]. - omega. - Qed. - - (* States that each element of the base is a positive integer multiple of the previous - element, and that max is a positive integer multiple of the last element. Ideally this - would have a better name. *) - Definition base_max_succ_divide max := forall i, (S i <= length base)%nat -> - Z.divide (nth_default max base i) (nth_default max base (S i)). - - Lemma encode'_spec : forall z max, 0 < max -> - base_max_succ_divide max -> forall i, (i <= length base)%nat -> - decode' base (encode' base z max i) = z mod (nth_default max base i). - Proof using Type*. - induction i; intros. - + rewrite encode'_zero, b0_1, Z.mod_1_r. - apply decode_nil. - + rewrite encode'_succ, set_higher. - rewrite IHi by omega. - rewrite encode'_length, (Z.add_comm (z mod nth_default max base i)). - replace (nth_default 0 base i) with (nth_default max base i) by - (rewrite !nth_default_eq; apply nth_indep; omega). - match goal with H1 : base_max_succ_divide _, H2 : (S i <= length base)%nat, H3 : 0 < max |- _ => - specialize (H1 i H2); - rewrite (Znumtheory.Zmod_div_mod _ _ _ (nth_default_base_pos _ H _) - (nth_default_base_pos _ H _) H0) end. - rewrite <-Z.div_mod by (apply Z.positive_is_nonzero, Z.lt_gt; auto using nth_default_base_pos). - reflexivity. - Qed. - - Lemma encode_rep : forall z max, 0 <= z < max -> - base_max_succ_divide max -> decode base (encode base z max) = z. - Proof using Type*. - unfold encode; intros. - rewrite encode'_spec, nth_default_out_of_bounds by (omega || auto). - apply Z.mod_small; omega. - Qed. - -End BaseSystemProofs. - -Hint Rewrite @add_length_exact @mul'_length_exact_full @mul_length_exact_full @encode'_length @sub_length : distr_length. - -Section MultiBaseSystemProofs. - Context base0 (base_vector0 : @BaseVector base0) base1 (base_vector1 : @BaseVector base1). - - Lemma decode_short_initial : forall (us : digits), - (firstn (length us) base0 = firstn (length us) base1) - -> decode base0 us = decode base1 us. - Proof using Type. - intros us H. - unfold decode, decode'. - rewrite (combine_truncate_r us base0), (combine_truncate_r us base1), H. - reflexivity. - Qed. - - Lemma mul_rep_two_base : forall (us vs : digits), - (length us + length vs <= length base1)%nat - -> firstn (length us) base0 = firstn (length us) base1 - -> firstn (length vs) base0 = firstn (length vs) base1 - -> (decode base0 us) * (decode base0 vs) = decode base1 (mul base1 us vs). - Proof using base_vector1. - intros. - rewrite mul_rep by trivial. - apply f_equal2; apply decode_short_initial; assumption. - Qed. - -End MultiBaseSystemProofs. diff --git a/src/BoundedArithmetic/Double/Repeated/Core.v b/src/BoundedArithmetic/Double/Repeated/Core.v deleted file mode 100644 index e19b702aa..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Core.v +++ /dev/null @@ -1,127 +0,0 @@ -(*** Implementing Large Bounded Arithmetic via pairs *) -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.ListUtil. -Require Import Crypto.Util.Notations. - -Local Open Scope nat_scope. -Local Open Scope Z_scope. -Local Open Scope type_scope. - -Local Coercion Z.of_nat : nat >-> Z. - -Fixpoint repeated_tuple W (base : nat) (exp : nat) - := match exp with - | O => W - | S exp' => tuple (repeated_tuple W base exp') base - end. - -Local Arguments Z.mul !_ !_. -Local Opaque tuple_decoder. - -Section decode. - Context {n W} - {decode : decoder n W} - {base : nat}. - - Fixpoint repeated_tuple_decoder {exp : nat} - : decoder (base^exp * n) (repeated_tuple W base exp) - := {| Interface.decode - := match exp return repeated_tuple W base exp -> Z with - | O => decode - | S exp' => Interface.decode : tuple (repeated_tuple W base exp') base -> Z - end |}. - Global Existing Instance repeated_tuple_decoder. -End decode. - -Section all. - Context {n W} - {decode : decoder n W} - {ldi : load_immediate W} - {shrd : shift_right_doubleword_immediate W} - {sprl : spread_left_immediate W} - {shl : shift_left_immediate W} - {shr : shift_right_immediate W} - {mkl : mask_keep_low W} - {and : bitwise_and W} - {or : bitwise_or W} - {adc : add_with_carry W} - {subc : sub_with_carry W} - {mul : multiply W} - {mulhwll : multiply_low_low W} - {mulhwhl : multiply_high_low W} - {mulhwhh : multiply_high_high W} - {muldw : multiply_double W} - {selc : select_conditional W} - {addm : add_modulo W}. - - Local Notation repeated_tuple_cls cls exp - := (match exp%nat as exp0 return cls (repeated_tuple W 2 exp0) with - | O => _ : cls W - | S exp' => _ : cls (tuple (repeated_tuple W 2 exp') 2) - end) (only parsing). - - Fixpoint load_immediate_repeated_double {exp : nat} - := repeated_tuple_cls load_immediate exp. - Global Existing Instance load_immediate_repeated_double. - Fixpoint shift_right_doubleword_immediate_repeated_double {exp : nat} - := repeated_tuple_cls shift_right_doubleword_immediate exp. - Global Existing Instance shift_right_doubleword_immediate_repeated_double. - (*Fixpoint spread_left_immediate_repeated_double {exp : nat} - := repeated_tuple_cls spread_left_immediate exp. - Global Existing Instance spread_left_immediate_repeated_double.*) - Fixpoint bitwise_or_repeated_double {exp : nat} - := repeated_tuple_cls bitwise_or exp. - Global Existing Instance bitwise_or_repeated_double. - Local Hint Extern 1 => - match goal with - | [ H : forall n, (_ * _)%type |- _ ] - => pose proof (fun n => fst (H n)); - pose proof (fun n => snd (H n)); - clear H - end : typeclass_instances. - Fixpoint shlr_repeated_double {exp : nat} : (shift_left_immediate (repeated_tuple W 2 exp) * shift_right_immediate (repeated_tuple W 2 exp))%type. - Proof. - refine (repeated_tuple_cls (fun T => shift_left_immediate T * shift_right_immediate T)%type exp); - split; exact _. - Defined. - Global Instance shift_left_immediate_repeated_double {exp : nat} : shift_left_immediate (repeated_tuple W 2 exp) - := fst (@shlr_repeated_double exp). - Global Instance shift_right_immediate_repeated_double {exp : nat} : shift_right_immediate (repeated_tuple W 2 exp) - := snd (@shlr_repeated_double exp). - (*Fixpoint mask_keep_low_repeated_double {exp : nat} - := repeated_tuple_cls mask_keep_low exp. - Global Existing Instance mask_keep_low_repeated_double.*) - Fixpoint bitwise_and_repeated_double {exp : nat} - := repeated_tuple_cls bitwise_and exp. - Global Existing Instance bitwise_and_repeated_double. - Fixpoint add_with_carry_repeated_double {exp : nat} - := repeated_tuple_cls add_with_carry exp. - Global Existing Instance add_with_carry_repeated_double. - Fixpoint sub_with_carry_repeated_double {exp : nat} - := repeated_tuple_cls sub_with_carry exp. - Global Existing Instance sub_with_carry_repeated_double. - (*Fixpoint multiply_repeated_double {exp : nat} - := repeated_tuple_cls multiply exp. - Global Existing Instance multiply_repeated_double.*) - Fixpoint multiply_double_repeated_double {exp : nat} - := repeated_tuple_cls multiply_double exp. - Global Existing Instance multiply_double_repeated_double. - Fixpoint multiply_low_low_repeated_double {exp : nat} - := repeated_tuple_cls multiply_low_low exp. - Global Existing Instance multiply_low_low_repeated_double. - Fixpoint multiply_high_low_repeated_double {exp : nat} - := repeated_tuple_cls multiply_high_low exp. - Global Existing Instance multiply_high_low_repeated_double. - Fixpoint multiply_high_high_repeated_double {exp : nat} - := repeated_tuple_cls multiply_high_high exp. - Global Existing Instance multiply_high_high_repeated_double. - Fixpoint select_conditional_repeated_double {exp : nat} - := repeated_tuple_cls select_conditional exp. - Global Existing Instance select_conditional_repeated_double. - (*Fixpoint add_modulo_repeated_double {exp : nat} - := repeated_tuple_cls add_modulo exp. - Global Existing Instance add_modulo_repeated_double.*) -End all. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/BitwiseOr.v b/src/BoundedArithmetic/Double/Repeated/Proofs/BitwiseOr.v deleted file mode 100644 index 7996dbca5..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/BitwiseOr.v +++ /dev/null @@ -1,26 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.BitwiseOr. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.Util.ZUtil. - -Local Open Scope Z_scope. -Local Arguments Z.mul !_ !_. -Local Arguments Z.pow : simpl never. -Local Arguments Z.of_nat : simpl never. -Local Opaque tuple_decoder. - -Section bitwise_or. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {or : bitwise_or W} - {is_or : is_bitwise_or or}. - - Fixpoint is_bitwise_or_repeated_double {exp : nat} : is_bitwise_or (bitwise_or_repeated_double (exp:=exp)). - Proof. is_cls_fixpoint_t decode n exp is_or (@is_bitwise_or_repeated_double). Qed. - Global Existing Instance is_bitwise_or_repeated_double. -End bitwise_or. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/Decode.v b/src/BoundedArithmetic/Double/Repeated/Proofs/Decode.v deleted file mode 100644 index 230a7d27f..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/Decode.v +++ /dev/null @@ -1,114 +0,0 @@ -Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.Util.ZUtil. - -Local Arguments Z.mul !_ !_. -Local Opaque tuple_decoder. -Local Coercion Z.of_nat : nat >-> Z. -Local Open Scope Z_scope. - -Fixpoint project_repeated_tuple {W base exp} : repeated_tuple W base exp -> match base, exp with - | S _, _ => W - | O, O => W - | O, S _ => unit - end - := match exp, base - return repeated_tuple W base exp -> match base, exp with - | S _, _ => W - | O, O => W - | O, S _ => unit - end - with - | O, O - | O, S _ - => fun x => x - | S exp', S O => @project_repeated_tuple W (S O) exp' - | S exp', S (S base') => fun x => @project_repeated_tuple W (S (S base')) exp' (snd x) - | S _, O => fun _ => tt - end. - -Lemma mul_1_l_decode {W} (P : forall n, decoder n W -> Prop) - {n} (decode : decoder n W) - : P n decode -> P (1 * n) {| Interface.decode := @Interface.decode n W decode |}. -Proof. - pose proof (Z.mul_1_l n). - set (n' := 1 * n) in *; clearbody n'. - induction H. - destruct decode. - exact (fun x => x). -Qed. - -Section decode. - Context {n W} - {decode : decoder n W} - {isdecode : is_decode decode} - {base : nat}. - - Fixpoint is_repeated_tuple_decode {exp : nat} - : is_decode (@repeated_tuple_decoder n W decode base exp). - Proof. - refine match exp return is_decode (repeated_tuple_decoder (exp:=exp)) with - | O => fun x => _ - | S exp' => fun x => _ - end. - { clear is_repeated_tuple_decode. - simpl; rewrite Z.mul_1_l; apply isdecode. } - { specialize (is_repeated_tuple_decode exp'). - change (base^S exp') with (base^(1 + exp')%nat) at 3. - rewrite (Nat2Z.inj_add 1 exp'), Z.pow_add_r, Z.pow_1_r by omega. - simpl. - destruct base as [|[| base' ]]; autorewrite with simpl_tuple_decoder. - { simpl; omega. } - { apply is_repeated_tuple_decode. } - { assert (0 <= n) by exact (decode_exponent_nonnegative _ (project_repeated_tuple x)). - assert (0 <= S (S base') ^ exp' * n) by zero_bounds. - assert (0 <= (S base' * (S (S base') ^ exp' * n))) by zero_bounds. - rewrite <- Z.mul_assoc. - change (2 ^ (S (S base') * (S (S base') ^ exp' * n))) - with (2 ^ (((1 + S base')%nat) * (S (S base') ^ exp' * n))). - rewrite (Nat2Z.inj_add 1 (S base')), Z.mul_add_distr_r, Z.mul_1_l, Z.pow_add_r by omega. - autorewrite with simpl_tuple_decoder Zshift_to_pow; generalize_decode; nia. } } - Qed. - Global Existing Instance is_repeated_tuple_decode. -End decode. - -Ltac is_cls_fixpoint_t_gen decode n exp generalize_is_clsv IH := - let exp' := fresh exp in - destruct exp as [|exp']; - [ clear IH; - destruct decode; generalize_is_clsv (); - simpl; - change (Z.of_nat 2 ^ Z.of_nat 0) with 1; - generalize (Z.mul_1_l n); generalize (1 * n); - intro; clear; induction 1; - intros; repeat apply pair; try assumption - | specialize (IH exp'); revert IH; - repeat match goal with - | [ |- (_ * _)%type -> _ ] - => let x := fresh in - let y := fresh in - intros [x y]; revert x y - | [ |- _ -> _ ] - => intro - end; - simpl @repeated_tuple_decoder; simpl; - change (Z.of_nat (S exp')) with (Z.of_nat (1 + exp')); - rewrite (Nat2Z.inj_add 1 exp'), Z.pow_add_r, Z.pow_1_r, <- !Z.mul_assoc, <- decoder_eta by omega; - repeat apply pair; - try exact _ ]. - -Ltac is_cls_fixpoint_t decode n exp is_clsv IH := - is_cls_fixpoint_t_gen decode n exp ltac:(fun _ => generalize is_clsv) IH. - -Ltac is_cls_fixpoint_t2 decode n exp is_clsv1 is_clsv2 IH := - is_cls_fixpoint_t_gen decode n exp ltac:(fun _ => generalize is_clsv1, is_clsv2) IH. - -Ltac is_cls_fixpoint_t3 decode n exp is_clsv1 is_clsv2 is_clsv3 IH := - is_cls_fixpoint_t_gen decode n exp ltac:(fun _ => generalize is_clsv1, is_clsv2, is_clsv3) IH. - -Ltac is_cls_fixpoint_t4 decode n exp is_clsv1 is_clsv2 is_clsv3 is_clsv4 IH := - is_cls_fixpoint_t_gen decode n exp ltac:(fun _ => generalize is_clsv1, is_clsv2, is_clsv3, is_clsv4) IH. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/LoadImmediate.v b/src/BoundedArithmetic/Double/Repeated/Proofs/LoadImmediate.v deleted file mode 100644 index 91b0c3ce7..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/LoadImmediate.v +++ /dev/null @@ -1,26 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.LoadImmediate. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.Util.ZUtil. - -Local Open Scope Z_scope. -Local Arguments Z.mul !_ !_. -Local Arguments Z.pow : simpl never. -Local Arguments Z.of_nat : simpl never. -Local Opaque tuple_decoder. - -Section load_immediate. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {ldi : load_immediate W} - {is_ldi : is_load_immediate ldi}. - - Fixpoint is_load_immediate_repeated_double {exp : nat} : is_load_immediate (load_immediate_repeated_double (exp:=exp)). - Proof. is_cls_fixpoint_t decode n exp is_ldi (@is_load_immediate_repeated_double). Qed. - Global Existing Instance is_load_immediate_repeated_double. -End load_immediate. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/Multiply.v b/src/BoundedArithmetic/Double/Repeated/Proofs/Multiply.v deleted file mode 100644 index a00e0c891..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/Multiply.v +++ /dev/null @@ -1,96 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Multiply. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.LoadImmediate. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.RippleCarryAddSub. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.ShiftLeftRight. -Require Import Crypto.Util.ZUtil. - -Local Open Scope Z_scope. -Local Arguments Z.mul !_ !_. -Local Arguments Z.pow : simpl never. -Local Arguments Z.of_nat : simpl never. -Local Opaque tuple_decoder. - -Section multiply_double. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {ldi : load_immediate W} - {isldi : is_load_immediate ldi} - {shl : shift_left_immediate W} - {isshl : is_shift_left_immediate shl} - {shr : shift_right_immediate W} - {isshr : is_shift_right_immediate shr} - {or : bitwise_or W} - {isor : is_bitwise_or or} - {adc : add_with_carry W} - {isadc : is_add_with_carry adc} - {muldw : multiply_double W} - {ismuldw : is_mul_double muldw}. - - Fixpoint is_multiply_double_repeated_double {exp : nat} : is_mul_double (multiply_double_repeated_double (exp:=exp)). - Proof. is_cls_fixpoint_t decode n exp ismuldw (@is_multiply_double_repeated_double). Qed. - Global Existing Instance is_multiply_double_repeated_double. -End multiply_double. - -Section multiply. - Context {n_over_two W} - {decode : decoder (2 * n_over_two) W} - {is_decode : is_decode decode} - {ldi : load_immediate W} - {isldi : is_load_immediate ldi} - {shl : shift_left_immediate W} - {isshl : is_shift_left_immediate shl} - {shr : shift_right_immediate W} - {isshr : is_shift_right_immediate shr} - {or : bitwise_or W} - {isor : is_bitwise_or or} - {adc : add_with_carry W} - {isadc : is_add_with_carry adc} - {mulhwll : multiply_low_low W} - {mulhwhl : multiply_high_low W} - {mulhwhh : multiply_high_high W} - {ismulhwll : is_mul_low_low n_over_two mulhwll} - {ismulhwhl : is_mul_high_low n_over_two mulhwhl} - {ismulhwhh : is_mul_high_high n_over_two mulhwhh}. - - Fixpoint is_multi_multiply_repeated_double {exp : nat} - : (is_mul_low_low (Z.of_nat 2^Z.of_nat exp * n_over_two) (multiply_low_low_repeated_double (exp:=exp)) - * is_mul_high_low (Z.of_nat 2^Z.of_nat exp * n_over_two) (multiply_high_low_repeated_double (exp:=exp)) - * is_mul_high_high (Z.of_nat 2^Z.of_nat exp * n_over_two) (multiply_high_high_repeated_double (exp:=exp)))%type. - Proof using Type*. - destruct exp as [|exp']; [ clear is_multi_multiply_repeated_double | specialize (is_multi_multiply_repeated_double exp') ]. - { destruct decode; generalize ismulhwll, ismulhwhl, ismulhwhh. - simpl. - change (Z.of_nat 2 ^ Z.of_nat 0) with 1. - generalize (eq_sym (Z.mul_1_l (2 * n_over_two))); generalize (1 * (2 * n_over_two)). - intro; clear; induction 1. - generalize (eq_sym (Z.mul_1_l (n_over_two))); generalize (1 * (n_over_two)). - intro; clear; induction 1. - intros; repeat apply pair; assumption. } - { destruct is_multi_multiply_repeated_double as [ [ ? ? ] ? ]. - simpl @repeated_tuple_decoder; simpl; - change (Z.of_nat (S exp')) with (Z.of_nat (1 + exp')). - rewrite (Nat2Z.inj_add 1 exp'), Z.pow_add_r, Z.pow_1_r, (*!Z.mul_assoc, <- !(Z.mul_comm 2),*) <- !Z.mul_assoc by omega. - rewrite <- decoder_eta by omega. - rewrite (Z.mul_assoc (Z.of_nat 2) (_^_) n_over_two), (Z.mul_comm (Z.of_nat 2) (_^_)), <- (Z.mul_assoc (_^_) (Z.of_nat 2) n_over_two) by omega. - repeat apply pair; - try exact _. } - Qed. - - Global Instance is_multiply_low_low_repeated_double {exp : nat} - : is_mul_low_low (Z.of_nat 2^Z.of_nat exp * n_over_two) (multiply_low_low_repeated_double (exp:=exp)) - := fst (fst (@is_multi_multiply_repeated_double exp)). - Global Instance is_multiply_high_low_repeated_double {exp : nat} - : is_mul_high_low (Z.of_nat 2^Z.of_nat exp * n_over_two) (multiply_high_low_repeated_double (exp:=exp)) - := snd (fst (@is_multi_multiply_repeated_double exp)). - Global Instance is_multiply_high_high_repeated_double {exp : nat} - : is_mul_high_high (Z.of_nat 2^Z.of_nat exp * n_over_two) (multiply_high_high_repeated_double (exp:=exp)) - := snd (@is_multi_multiply_repeated_double exp). -End multiply. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/RippleCarryAddSub.v b/src/BoundedArithmetic/Double/Repeated/Proofs/RippleCarryAddSub.v deleted file mode 100644 index 07bc65c84..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/RippleCarryAddSub.v +++ /dev/null @@ -1,38 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.RippleCarryAddSub. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.Util.ZUtil. - -Local Open Scope Z_scope. -Local Arguments Z.mul !_ !_. -Local Arguments Z.pow : simpl never. -Local Arguments Z.of_nat : simpl never. -Local Opaque tuple_decoder. - -Section add_with_carry. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {adc : add_with_carry W} - {is_adc : is_add_with_carry adc}. - - Fixpoint is_add_with_carry_repeated_double {exp : nat} : is_add_with_carry (add_with_carry_repeated_double (exp:=exp)). - Proof. is_cls_fixpoint_t decode n exp is_adc (@is_add_with_carry_repeated_double). Qed. - Global Existing Instance is_add_with_carry_repeated_double. -End add_with_carry. - -Section sub_with_carry. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {subc : sub_with_carry W} - {is_subc : is_sub_with_carry subc}. - - Fixpoint is_sub_with_carry_repeated_double {exp : nat} : is_sub_with_carry (sub_with_carry_repeated_double (exp:=exp)). - Proof. is_cls_fixpoint_t decode n exp is_subc (@is_sub_with_carry_repeated_double). Qed. - Global Existing Instance is_sub_with_carry_repeated_double. -End sub_with_carry. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/SelectConditional.v b/src/BoundedArithmetic/Double/Repeated/Proofs/SelectConditional.v deleted file mode 100644 index 05ff40cd3..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/SelectConditional.v +++ /dev/null @@ -1,26 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.SelectConditional. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.Util.ZUtil. - -Local Open Scope Z_scope. -Local Arguments Z.mul !_ !_. -Local Arguments Z.pow : simpl never. -Local Arguments Z.of_nat : simpl never. -Local Opaque tuple_decoder. - -Section select_conditional. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {selc : select_conditional W} - {is_selc : is_select_conditional selc}. - - Fixpoint is_select_conditional_repeated_double {exp : nat} : is_select_conditional (select_conditional_repeated_double (exp:=exp)). - Proof. is_cls_fixpoint_t decode n exp is_selc (@is_select_conditional_repeated_double). Qed. - Global Existing Instance is_select_conditional_repeated_double. -End select_conditional. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/ShiftLeftRight.v b/src/BoundedArithmetic/Double/Repeated/Proofs/ShiftLeftRight.v deleted file mode 100644 index acda67158..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/ShiftLeftRight.v +++ /dev/null @@ -1,42 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.ShiftLeft. -Require Import Crypto.BoundedArithmetic.Double.Proofs.ShiftRight. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.LoadImmediate. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.BitwiseOr. -Require Import Crypto.Util.ZUtil. - -Local Open Scope Z_scope. -Local Arguments Z.mul !_ !_. -Local Arguments Z.pow : simpl never. -Local Arguments Z.of_nat : simpl never. -Local Opaque tuple_decoder. - -Section shift_left_right. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {ldi : load_immediate W} - {is_ldi : is_load_immediate ldi} - {shl : shift_left_immediate W} - {is_shl : is_shift_left_immediate shl} - {shr : shift_right_immediate W} - {is_shr : is_shift_right_immediate shr} - {or : bitwise_or W} - {is_or : is_bitwise_or or}. - - Fixpoint is_shift_left_right_immediate_repeated_double {exp : nat} - : (is_shift_left_immediate (shift_left_immediate_repeated_double (exp:=exp)) - * is_shift_right_immediate (shift_right_immediate_repeated_double (exp:=exp)))%type. - Proof using Type*. is_cls_fixpoint_t2 decode n exp is_shl is_shr (@is_shift_left_right_immediate_repeated_double). Qed. - Global Instance is_shift_left_immediate_repeated_double {exp : nat} - : is_shift_left_immediate (shift_left_immediate_repeated_double (exp:=exp)) - := fst (@is_shift_left_right_immediate_repeated_double exp). - Global Instance is_shift_right_immediate_repeated_double {exp : nat} - : is_shift_right_immediate (shift_right_immediate_repeated_double (exp:=exp)) - := snd (@is_shift_left_right_immediate_repeated_double exp). -End shift_left_right. diff --git a/src/BoundedArithmetic/Double/Repeated/Proofs/ShiftRightDoubleWordImmediate.v b/src/BoundedArithmetic/Double/Repeated/Proofs/ShiftRightDoubleWordImmediate.v deleted file mode 100644 index 00d41c57f..000000000 --- a/src/BoundedArithmetic/Double/Repeated/Proofs/ShiftRightDoubleWordImmediate.v +++ /dev/null @@ -1,30 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.ShiftRightDoubleWordImmediate. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.LoadImmediate. -Require Import Crypto.Util.ZUtil. - -Local Open Scope Z_scope. -Local Arguments Z.mul !_ !_. -Local Arguments Z.pow : simpl never. -Local Arguments Z.of_nat : simpl never. -Local Opaque tuple_decoder. - -Section shift_right_doubleword_immediate. - Context {n W} - {decode : decoder n W} - {is_decode : is_decode decode} - {ldi : load_immediate W} - {is_ldi : is_load_immediate ldi} - {shrd : shift_right_doubleword_immediate W} - {is_shrd : is_shift_right_doubleword_immediate shrd}. - - Fixpoint is_shift_right_doubleword_immediate_repeated_double {exp : nat} - : is_shift_right_doubleword_immediate (shift_right_doubleword_immediate_repeated_double (exp:=exp)). - Proof. is_cls_fixpoint_t decode n exp is_shrd (@is_shift_right_doubleword_immediate_repeated_double). Qed. - Global Existing Instance is_shift_right_doubleword_immediate_repeated_double. -End shift_right_doubleword_immediate. diff --git a/src/BoundedArithmetic/Eta.v b/src/BoundedArithmetic/Eta.v deleted file mode 100644 index b48b8cff1..000000000 --- a/src/BoundedArithmetic/Eta.v +++ /dev/null @@ -1,70 +0,0 @@ -(** * Bounded arithmetic η expansion *) -(** This is useful for allowing us to refold the projections. *) -Require Import Crypto.BoundedArithmetic.Interface. - -Definition eta_decode {n W} (x : decoder n W) : decoder n W := {| decode := decode |}. -Section InstructionGallery. - Context {n W} {Wdecoder : decoder n W}. - Definition eta_ldi (x : load_immediate W) := {| ldi := ldi |}. - Definition eta_shrd (x : shift_right_doubleword_immediate W) := {| shrd := shrd |}. - Definition eta_shrdf (x : shift_right_doubleword_immediate_with_CF W) := {| shrdf := shrdf |}. - Definition eta_shl (x : shift_left_immediate W) := {| shl := shl |}. - Definition eta_shlf (x : shift_left_immediate_with_CF W) := {| shlf := shlf |}. - Definition eta_shr (x : shift_right_immediate W) := {| shr := shr |}. - Definition eta_shrf (x : shift_right_immediate_with_CF W) := {| shrf := shrf |}. - Definition eta_sprl (x : spread_left_immediate W) := {| sprl := sprl |}. - Definition eta_mkl (x : mask_keep_low W) := {| mkl := mkl |}. - Definition eta_and (x : bitwise_and W) := {| and := and |}. - Definition eta_andf (x : bitwise_and_with_CF W) := {| andf := andf |}. - Definition eta_or (x : bitwise_or W) := {| or := or |}. - Definition eta_orf (x : bitwise_or_with_CF W) := {| orf := orf |}. - Definition eta_adc (x : add_with_carry W) := {| adc := adc |}. - Definition eta_subc (x : sub_with_carry W) := {| subc := subc |}. - Definition eta_mul (x : multiply W) := {| mul := mul |}. - Definition eta_mulhwll (x : multiply_low_low W) := {| mulhwll := mulhwll |}. - Definition eta_mulhwhl (x : multiply_high_low W) := {| mulhwhl := mulhwhl |}. - Definition eta_mulhwhh (x : multiply_high_high W) := {| mulhwhh := mulhwhh |}. - Definition eta_muldw (x : multiply_double W) := {| muldw := muldw |}. - Definition eta_muldwf (x : multiply_double_with_CF W) := {| muldwf := muldwf |}. - Definition eta_selc (x : select_conditional W) := {| selc := selc |}. - Definition eta_addm (x : add_modulo W) := {| addm := addm |}. -End InstructionGallery. - -Declare Reduction unfold_eta_bounded_instructions - := cbv [eta_decode eta_ldi eta_shrd eta_shrdf eta_shl eta_shlf eta_shr eta_shrf eta_sprl eta_mkl eta_and eta_andf eta_or eta_orf eta_adc eta_subc eta_mul eta_mulhwll eta_mulhwhl eta_mulhwhh eta_muldw eta_muldwf eta_selc eta_addm]. - -Module fancy_machine. - Import Interface.fancy_machine. - Definition eta_instructions {n} (x : fancy_machine.instructions n) : fancy_machine.instructions n - := Eval unfold_eta_bounded_instructions in - {| W := W; - decode := eta_decode decode; - ldi := eta_ldi ldi; - shrd := eta_shrd shrd; - shl := eta_shl shl; - shr := eta_shr shr; - adc := eta_adc adc; - subc := eta_subc subc; - mulhwll := eta_mulhwll mulhwll; - mulhwhl := eta_mulhwhl mulhwhl; - mulhwhh := eta_mulhwhh mulhwhh; - selc := eta_selc selc; - addm := eta_addm addm |}. -End fancy_machine. - -Module x86. - Import Interface.x86. - Definition eta_instructions {n} (x : x86.instructions n) : x86.instructions n - := Eval unfold_eta_bounded_instructions in - {| W := W; - decode := eta_decode decode; - ldi := eta_ldi ldi; - shrdf := eta_shrdf shrdf; - shlf := eta_shlf shlf; - shrf := eta_shrf shrf; - adc := eta_adc adc; - subc := eta_subc subc; - muldwf := eta_muldwf muldwf; - selc := eta_selc selc; - orf := eta_orf orf |}. -End x86. diff --git a/src/BoundedArithmetic/StripCF.v b/src/BoundedArithmetic/StripCF.v deleted file mode 100644 index f44b1b7f7..000000000 --- a/src/BoundedArithmetic/StripCF.v +++ /dev/null @@ -1,74 +0,0 @@ -(** * Strip CF for Interface for bounded arithmetic *) -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. - -Local Open Scope type_scope. -Local Open Scope Z_scope. - -Section strip_CF. - Context (n : Z) (* bit-width of width of [W] *) - {W : Type} (* bounded type, [W] for word *) - (Wdecoder : decoder n W). - Local Notation imm := Z (only parsing). (* immediate (compile-time) argument *) - - Global Instance shift_right_doubleword_immediate_strip_CF - {shrdf : shift_right_doubleword_immediate_with_CF W} - : shift_right_doubleword_immediate W - := { shrd x y z := snd (shrdf x y z) }. - Global Instance is_shift_right_doubleword_immediate_strip_CF - {shrdf : shift_right_doubleword_immediate_with_CF W} - {shift_right_doubleword_immediate_with_CF : is_shift_right_doubleword_immediate_with_CF shrdf} - : is_shift_right_doubleword_immediate shift_right_doubleword_immediate_strip_CF - := shift_right_doubleword_immediate_with_CF. - - Global Instance shift_left_immediate_strip_CF - {shlf : shift_left_immediate_with_CF W} - : shift_left_immediate W - := { shl x y := snd (shlf x y) }. - Global Instance is_shift_left_immediate_strip_CF - {shlf : shift_left_immediate_with_CF W} - {shift_left_immediate_with_CF : is_shift_left_immediate_with_CF shlf} - : is_shift_left_immediate shift_left_immediate_strip_CF - := shift_left_immediate_with_CF. - - Global Instance shift_right_immediate_strip_CF - {shrf : shift_right_immediate_with_CF W} - : shift_right_immediate W - := { shr x y := snd (shrf x y) }. - Global Instance is_shift_right_immediate_strip_CF - {shrf : shift_right_immediate_with_CF W} - {shift_right_immediate_with_CF : is_shift_right_immediate_with_CF shrf} - : is_shift_right_immediate shift_right_immediate_strip_CF - := shift_right_immediate_with_CF. - - Global Instance bitwise_and_strip_CF - {andf : bitwise_and_with_CF W} - : bitwise_and W - := { and x y := snd (andf x y) }. - Global Instance is_bitwise_and_strip_CF - {andf : bitwise_and_with_CF W} - {bitwise_and_with_CF : is_bitwise_and_with_CF andf} - : is_bitwise_and bitwise_and_strip_CF - := { decode_bitwise_and := @decode_snd_bitwise_and_with_CF _ _ _ _ bitwise_and_with_CF }. - - Global Instance bitwise_or_strip_CF - {orf : bitwise_or_with_CF W} - : bitwise_or W - := { or x y := snd (orf x y) }. - Global Instance is_bitwise_or_strip_CF - {orf : bitwise_or_with_CF W} - {bitwise_or_with_CF : is_bitwise_or_with_CF orf} - : is_bitwise_or bitwise_or_strip_CF - := { decode_bitwise_or := @decode_snd_bitwise_or_with_CF _ _ _ _ bitwise_or_with_CF }. - - Global Instance multiply_double_strip_CF - {muldwf : multiply_double_with_CF W} - : multiply_double W - := { muldw x y := snd (muldwf x y) }. - Global Instance is_mul_double_strip_CF - {muldwf : multiply_double_with_CF W} - {multiply_double_with_CF : is_mul_double_with_CF muldwf} - : is_mul_double multiply_double_strip_CF - := { decode_fst_mul_double := @decode_fst_mul_double_with_CF _ _ _ _ multiply_double_with_CF; - decode_snd_mul_double := @decode_snd_mul_double_with_CF _ _ _ _ multiply_double_with_CF}. -End strip_CF. diff --git a/src/BoundedArithmetic/X86ToZLike.v b/src/BoundedArithmetic/X86ToZLike.v deleted file mode 100644 index 29e777c0e..000000000 --- a/src/BoundedArithmetic/X86ToZLike.v +++ /dev/null @@ -1,73 +0,0 @@ -(*** Implementing ℤ-Like via Architecture *) -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.StripCF. -Require Import Crypto.ModularArithmetic.ZBounded. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.LetIn. -Import NPeano. - -Local Open Scope Z_scope. -Local Coercion Z.of_nat : nat >-> Z. - -Section x86_gen_barrett_foundation. - Context (full_width : nat) (n : nat) (ops : x86.instructions n) (modulus : Z). - Local Notation W := (repeated_tuple x86.W 2 (Nat.log2 (full_width / n))). (* full_width-width words *) - - Local Instance ZLikeOps_of_x86_gen_Factored (smaller_bound_exp : Z) - (ldi_modulus ldi_0 : W) - : ZLikeOps (2^full_width) (2^smaller_bound_exp) modulus - := { LargeT := tuple W 2; - SmallT := W; - modulus_digits := ldi_modulus; - decode_large := decode; - decode_small := decode; - Mod_SmallBound v := fst v; - DivBy_SmallBound v := snd v; - DivBy_SmallerBound v := if smaller_bound_exp =? n - then snd v - else dlet v := v in shrd (snd v) (fst v) smaller_bound_exp; - Mul x y := muldw x y; - CarryAdd x y := adc x y false; - CarrySubSmall x y := subc x y false; - ConditionalSubtract b x := let v := selc b (ldi_modulus) (ldi_0) in snd (subc x v false); - ConditionalSubtractModulus y := dlet y := y in - let (CF, _) := subc y ldi_modulus false in - let maybe_modulus := ldi_0 in - let maybe_modulus := selc CF maybe_modulus ldi_modulus in - let (CF, y) := subc y maybe_modulus false in - y }. - - Local Instance ZLikeOps_of_x86_gen (smaller_bound_exp : Z) - : ZLikeOps (2^full_width) (2^smaller_bound_exp) modulus := - @ZLikeOps_of_x86_gen_Factored smaller_bound_exp (ldi modulus) (ldi 0). -End x86_gen_barrett_foundation. - -Section x86_64_barrett_foundation. - Local Notation n := 64%nat. - Context (ops : x86.instructions n) (modulus : Z). - Local Notation W := (tuple (tuple x86.W 2) 2) (* 256-bit words *). - - Local Instance ZLikeOps_of_x86_64_Factored (smaller_bound_exp : Z) - ldi_modulus ldi_0 - : ZLikeOps (2^256) (2^smaller_bound_exp) modulus - := @ZLikeOps_of_x86_gen_Factored 256 n ops modulus smaller_bound_exp ldi_modulus ldi_0. - Global Instance ZLikeOps_of_x86_64 (smaller_bound_exp : Z) - : ZLikeOps (2^256) (2^smaller_bound_exp) modulus := - @ZLikeOps_of_x86_64_Factored smaller_bound_exp (ldi modulus) (ldi 0). -End x86_64_barrett_foundation. -Section x86_32_barrett_foundation. - Local Notation n := 32%nat. - Context (ops : x86.instructions n) (modulus : Z). - Local Notation W := (tuple (tuple (tuple x86.W 2) 2) 2) (* 256-bit words *). - - Local Instance ZLikeOps_of_x86_32_Factored (smaller_bound_exp : Z) - ldi_modulus ldi_0 - : ZLikeOps (2^256) (2^smaller_bound_exp) modulus - := @ZLikeOps_of_x86_gen_Factored 256 n ops modulus smaller_bound_exp ldi_modulus ldi_0. - Global Instance ZLikeOps_of_x86_32 (smaller_bound_exp : Z) - : ZLikeOps (2^256) (2^smaller_bound_exp) modulus := - @ZLikeOps_of_x86_32_Factored smaller_bound_exp (ldi modulus) (ldi 0). -End x86_32_barrett_foundation. diff --git a/src/BoundedArithmetic/X86ToZLikeProofs.v b/src/BoundedArithmetic/X86ToZLikeProofs.v deleted file mode 100644 index 530c91dc9..000000000 --- a/src/BoundedArithmetic/X86ToZLikeProofs.v +++ /dev/null @@ -1,190 +0,0 @@ -(*** Implementing ℤ-Like via x86 *) -Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.RippleCarryAddSub. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Multiply. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.RippleCarryAddSub. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Proofs.Multiply. -Require Import Crypto.BoundedArithmetic.Double.Repeated.Core. -Require Import Crypto.BoundedArithmetic.StripCF. -Require Import Crypto.BoundedArithmetic.X86ToZLike. -Require Import Crypto.ModularArithmetic.ZBounded. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.Tactics.UniquePose. -Require Import Crypto.Util.LetIn. -Import NPeano. - -Local Open Scope Z_scope. -Local Coercion Z.of_nat : nat >-> Z. - -Section x86_gen_barrett_foundation. - Context {n_over_two : nat}. - Local Notation n := (2 * n_over_two)%nat. - Context (full_width : nat) (ops : x86.instructions n) (modulus : Z). - Local Notation W := (repeated_tuple x86.W 2 (Nat.log2 (full_width / n))). (* full_width-width words *) - - Local Arguments Z.mul !_ !_. - Local Arguments BaseSystem.decode !_ !_ / . - Local Arguments BaseSystem.accumulate / _ _. - Local Arguments BaseSystem.decode' !_ !_ / . - - Local Ltac introduce_t_step := - match goal with - | [ |- forall x : bool, _ ] => intros [|] - | [ |- True -> _ ] => intros _ - | [ |- _ <= _ < _ -> _ ] => intro - | _ => let x := fresh "x" in - intro x; - try pose proof (decode_range (fst x)); - try pose proof (decode_range (snd x)); - pose proof (decode_range x) - end. - Local Ltac unfolder_t := - progress unfold LargeT, SmallT, modulus_digits, decode_large, decode_small, Mod_SmallBound, DivBy_SmallBound, DivBy_SmallerBound, Mul, CarryAdd, CarrySubSmall, ConditionalSubtract, ConditionalSubtractModulus, ZLikeOps_of_x86_gen_Factored, ZLikeOps_of_x86_gen in *. - Local Ltac saturate_context_step := - match goal with - | _ => unique assert (0 <= 2 * n_over_two) by solve [ eauto using decode_exponent_nonnegative with typeclass_instances | omega ] - | _ => unique assert (0 <= n_over_two) by solve [ eauto using decode_exponent_nonnegative with typeclass_instances | omega ] - | _ => unique assert (0 <= 2 * (2 * n_over_two)) by (eauto using decode_exponent_nonnegative with typeclass_instances) - | [ H : 0 <= ?x < _ |- _ ] => unique pose proof (proj1 H); unique pose proof (proj2 H) - end. - Local Ltac pre_t := - repeat first [ tauto - | introduce_t_step - | unfolder_t - | saturate_context_step ]. - Local Ltac post_t_step := - match goal with - | _ => reflexivity - | _ => progress subst - | _ => progress unfold Let_In - | _ => progress autorewrite with zsimplify_const - | [ |- fst ?x = (?a <=? ?b) :> bool ] - => cut (((if fst x then 1 else 0) = (if a <=? b then 1 else 0))%Z); - [ destruct (fst x), (a <=? b); intro; congruence | ] - | [ H : (_ =? _) = true |- _ ] => apply Z.eqb_eq in H; subst - | [ H : (_ =? _) = false |- _ ] => apply Z.eqb_neq in H - | _ => autorewrite with push_Zpow in *; solve [ reflexivity | assumption ] - | _ => autorewrite with pull_Zpow in *; pull_decode; reflexivity - | _ => progress push_decode - | _ => rewrite (Z.add_comm (_ << _) _); progress pull_decode - | [ |- context[if ?x =? ?y then _ else _] ] => destruct (x =? y) eqn:? - | _ => autorewrite with Zshift_to_pow; Z.rewrite_mod_small; reflexivity - end. - Local Ltac post_t := repeat post_t_step. - Axiom proof_admitted : False. - Tactic Notation "admit" := abstract case proof_admitted. - Local Ltac t := admit; pre_t; post_t. - - Global Instance ZLikeProperties_of_x86_gen_Factored - {arith : x86.arithmetic ops} - (ldi_modulus ldi_0 : W) - (Hldi_modulus : ldi_modulus = ldi modulus) - (Hldi_0 : ldi_0 = ldi 0) - (modulus_in_range : 0 <= modulus < 2^full_width) - (smaller_bound_exp : Z) - (smaller_bound_smaller : 0 <= smaller_bound_exp <= full_width) - (n_pos : 0 < n) - (full_width_pos : 0 < full_width) - : ZLikeProperties (@ZLikeOps_of_x86_gen_Factored full_width n ops modulus smaller_bound_exp ldi_modulus ldi_0) - := { large_valid v := True; - medium_valid v := 0 <= decode_large v < 2^full_width * 2^smaller_bound_exp; - small_valid v := True }. - Proof. - (* In 8.5: *) - (* par:t. *) - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - { abstract t. } - Defined. - - Global Instance ZLikeProperties_of_x86_gen - {arith : x86.arithmetic ops} - (modulus_in_range : 0 <= modulus < 2^full_width) - (smaller_bound_exp : Z) - (smaller_bound_smaller : 0 <= smaller_bound_exp <= full_width) - (n_pos : 0 < n) - (full_width_pos : 0 < full_width) - : ZLikeProperties (@ZLikeOps_of_x86_gen _ _ ops modulus smaller_bound_exp) - := ZLikeProperties_of_x86_gen_Factored _ _ eq_refl eq_refl modulus_in_range _ smaller_bound_smaller n_pos full_width_pos. -End x86_gen_barrett_foundation. - -Section x86_64_barrett_foundation. - Local Notation n := 64%nat. - Context (ops : x86.instructions n) (modulus : Z). - Local Notation W := (tuple (tuple x86.W 2) 2) (* 256-bit words *). - - Global Instance ZLikeProperties_of_x86_64_Factored - {arith : x86.arithmetic ops} - (ldi_modulus ldi_0 : W) - (Hldi_modulus : ldi_modulus = ldi modulus) - (Hldi_0 : ldi_0 = ldi 0) - (modulus_in_range : 0 <= modulus < 2^256) - (smaller_bound_exp : Z) - (smaller_bound_smaller : 0 <= smaller_bound_exp <= 256) - (n_pos : 0 < n) - : ZLikeProperties (@ZLikeOps_of_x86_64_Factored ops modulus smaller_bound_exp ldi_modulus ldi_0) - := @ZLikeProperties_of_x86_gen_Factored 32 256 _ _ arith _ _ Hldi_modulus Hldi_0 modulus_in_range _ smaller_bound_smaller n_pos _. - Proof. clear; simpl; abstract omega. Defined. - Global Instance ZLikeProperties_of_x86_64 - {arith : x86.arithmetic ops} - (modulus_in_range : 0 <= modulus < 2^256) - (smaller_bound_exp : Z) - (smaller_bound_smaller : 0 <= smaller_bound_exp <= 256) - (n_pos : 0 < n) - : ZLikeProperties (@ZLikeOps_of_x86_64 ops modulus smaller_bound_exp) - := ZLikeProperties_of_x86_64_Factored _ _ eq_refl eq_refl modulus_in_range _ smaller_bound_smaller n_pos. -End x86_64_barrett_foundation. - -Section x86_32_barrett_foundation. - Local Notation n := 32%nat. - Context (ops : x86.instructions n) (modulus : Z). - Local Notation W := (tuple (tuple (tuple x86.W 2) 2) 2) (* 256-bit words *). - - Global Instance ZLikeProperties_of_x86_32_Factored - {arith : x86.arithmetic ops} - (ldi_modulus ldi_0 : W) - (Hldi_modulus : ldi_modulus = ldi modulus) - (Hldi_0 : ldi_0 = ldi 0) - (modulus_in_range : 0 <= modulus < 2^256) - (smaller_bound_exp : Z) - (smaller_bound_smaller : 0 <= smaller_bound_exp <= 256) - (n_pos : 0 < n) - : ZLikeProperties (@ZLikeOps_of_x86_32_Factored ops modulus smaller_bound_exp ldi_modulus ldi_0) - := @ZLikeProperties_of_x86_gen_Factored 16 256 _ _ arith _ _ Hldi_modulus Hldi_0 modulus_in_range _ smaller_bound_smaller n_pos _. - Proof. clear; simpl; abstract omega. Defined. - Global Instance ZLikeProperties_of_x86_32 - {arith : x86.arithmetic ops} - (modulus_in_range : 0 <= modulus < 2^256) - (smaller_bound_exp : Z) - (smaller_bound_smaller : 0 <= smaller_bound_exp <= 256) - (n_pos : 0 < n) - : ZLikeProperties (@ZLikeOps_of_x86_32 ops modulus smaller_bound_exp) - := ZLikeProperties_of_x86_32_Factored _ _ eq_refl eq_refl modulus_in_range _ smaller_bound_smaller n_pos. -End x86_32_barrett_foundation. diff --git a/src/Reflection/BoundByCast.v b/src/Compilers/BoundByCast.v index d65e67919..3a7bf143a 100644 --- a/src/Reflection/BoundByCast.v +++ b/src/Compilers/BoundByCast.v @@ -1,11 +1,11 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartBound. -Require Import Crypto.Reflection.InlineCast. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.Inline. -Require Import Crypto.Reflection.Linearize. -Require Import Crypto.Reflection.MapCast. -Require Import Crypto.Reflection.Eta. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartBound. +Require Import Crypto.Compilers.InlineCast. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.Inline. +Require Import Crypto.Compilers.Linearize. +Require Import Crypto.Compilers.MapCast. +Require Import Crypto.Compilers.Eta. Local Open Scope expr_scope. Local Open Scope ctype_scope. diff --git a/src/Reflection/BoundByCastInterp.v b/src/Compilers/BoundByCastInterp.v index 46a50fd42..77496659b 100644 --- a/src/Reflection/BoundByCastInterp.v +++ b/src/Compilers/BoundByCastInterp.v @@ -1,20 +1,20 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.InterpWfRel. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.BoundByCast. -Require Import Crypto.Reflection.SmartBound. -Require Import Crypto.Reflection.SmartBoundInterp. -Require Import Crypto.Reflection.SmartBoundWf. -Require Import Crypto.Reflection.InlineCastInterp. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.InlineInterp. -Require Import Crypto.Reflection.LinearizeInterp. -Require Import Crypto.Reflection.LinearizeWf. -Require Import Crypto.Reflection.MapCastInterp. -Require Import Crypto.Reflection.MapCastWf. -Require Import Crypto.Reflection.EtaInterp. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.InterpWfRel. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.BoundByCast. +Require Import Crypto.Compilers.SmartBound. +Require Import Crypto.Compilers.SmartBoundInterp. +Require Import Crypto.Compilers.SmartBoundWf. +Require Import Crypto.Compilers.InlineCastInterp. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.InlineInterp. +Require Import Crypto.Compilers.LinearizeInterp. +Require Import Crypto.Compilers.LinearizeWf. +Require Import Crypto.Compilers.MapCastInterp. +Require Import Crypto.Compilers.MapCastWf. +Require Import Crypto.Compilers.EtaInterp. Local Open Scope expr_scope. Local Open Scope ctype_scope. diff --git a/src/Reflection/BoundByCastWf.v b/src/Compilers/BoundByCastWf.v index cc60f14b1..d03ec1359 100644 --- a/src/Reflection/BoundByCastWf.v +++ b/src/Compilers/BoundByCastWf.v @@ -1,11 +1,11 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.BoundByCast. -Require Import Crypto.Reflection.EtaWf. -Require Import Crypto.Reflection.InlineCastWf. -Require Import Crypto.Reflection.LinearizeWf. -Require Import Crypto.Reflection.SmartBoundWf. -Require Import Crypto.Reflection.MapCastWf. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.BoundByCast. +Require Import Crypto.Compilers.EtaWf. +Require Import Crypto.Compilers.InlineCastWf. +Require Import Crypto.Compilers.LinearizeWf. +Require Import Crypto.Compilers.SmartBoundWf. +Require Import Crypto.Compilers.MapCastWf. Local Open Scope expr_scope. Local Open Scope ctype_scope. diff --git a/src/Reflection/CommonSubexpressionElimination.v b/src/Compilers/CommonSubexpressionElimination.v index 6d3921aa6..73df034a6 100644 --- a/src/Reflection/CommonSubexpressionElimination.v +++ b/src/Compilers/CommonSubexpressionElimination.v @@ -1,7 +1,7 @@ (** * Common Subexpression Elimination for PHOAS Syntax *) Require Import Coq.Lists.List. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. Require Import (*Crypto.Util.Tactics*) Crypto.Util.Bool. Local Open Scope list_scope. diff --git a/src/Reflection/Conversion.v b/src/Compilers/Conversion.v index bd0f4f695..29874c96f 100644 --- a/src/Reflection/Conversion.v +++ b/src/Compilers/Conversion.v @@ -1,6 +1,6 @@ (** * Convert between interpretations of types *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Map. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Map. Require Import Crypto.Util.Notations. Require Import Crypto.Util.Tactics.RewriteHyp. diff --git a/src/Reflection/CountLets.v b/src/Compilers/CountLets.v index 64c46d58a..4810162c8 100644 --- a/src/Reflection/CountLets.v +++ b/src/Compilers/CountLets.v @@ -1,6 +1,6 @@ (** * Counts how many binders there are *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. Local Open Scope ctype_scope. Section language. diff --git a/src/Reflection/Equality.v b/src/Compilers/Equality.v index ad642fe2d..8e2b44de8 100644 --- a/src/Reflection/Equality.v +++ b/src/Compilers/Equality.v @@ -1,4 +1,4 @@ -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.FixCoqMistakes. diff --git a/src/Reflection/Eta.v b/src/Compilers/Eta.v index d40267858..9ca778f15 100644 --- a/src/Reflection/Eta.v +++ b/src/Compilers/Eta.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.ExprInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.ExprInversion. Section language. Context {base_type_code : Type} diff --git a/src/Reflection/EtaInterp.v b/src/Compilers/EtaInterp.v index deb551d7d..f59024b98 100644 --- a/src/Reflection/EtaInterp.v +++ b/src/Compilers/EtaInterp.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Eta. -Require Import Crypto.Reflection.ExprInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Eta. +Require Import Crypto.Compilers.ExprInversion. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.DestructHead. diff --git a/src/Reflection/EtaWf.v b/src/Compilers/EtaWf.v index 240f5a1e3..e8dd2f846 100644 --- a/src/Reflection/EtaWf.v +++ b/src/Compilers/EtaWf.v @@ -1,9 +1,9 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Eta. -Require Import Crypto.Reflection.EtaInterp. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.WfInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Eta. +Require Import Crypto.Compilers.EtaInterp. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.WfInversion. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.SplitInContext. diff --git a/src/Reflection/ExprInversion.v b/src/Compilers/ExprInversion.v index 645555cb5..a1d2587f5 100644 --- a/src/Reflection/ExprInversion.v +++ b/src/Compilers/ExprInversion.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeInversion. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Option. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/FilterLive.v b/src/Compilers/FilterLive.v index 68144c0f7..5f3f0156d 100644 --- a/src/Reflection/FilterLive.v +++ b/src/Compilers/FilterLive.v @@ -1,8 +1,8 @@ (** * Computes a list of live variables *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Named.NameUtil. -Require Import Crypto.Reflection.CountLets. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Named.NameUtil. +Require Import Crypto.Compilers.CountLets. Require Import Crypto.Util.ListUtil. Local Notation eta x := (fst x, snd x). diff --git a/src/Reflection/FoldTypes.v b/src/Compilers/FoldTypes.v index d5d62a3aa..0b923fcc9 100644 --- a/src/Reflection/FoldTypes.v +++ b/src/Compilers/FoldTypes.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.SmartMap. Section language. Context {base_type_code} {op : flat_type base_type_code -> flat_type base_type_code -> Type}. diff --git a/src/Reflection/Inline.v b/src/Compilers/Inline.v index 74abeef10..d2aa44520 100644 --- a/src/Reflection/Inline.v +++ b/src/Compilers/Inline.v @@ -1,6 +1,6 @@ (** * Inline: Remove some [Let] expressions *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. Local Open Scope ctype_scope. Section language. diff --git a/src/Reflection/InlineCast.v b/src/Compilers/InlineCast.v index d3e85d02d..675835760 100644 --- a/src/Reflection/InlineCast.v +++ b/src/Compilers/InlineCast.v @@ -1,7 +1,7 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartCast. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.Inline. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartCast. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.Inline. Require Import Crypto.Util.Notations. Local Open Scope expr_scope. diff --git a/src/Reflection/InlineCastInterp.v b/src/Compilers/InlineCastInterp.v index f885fbd16..2b2e08b4d 100644 --- a/src/Reflection/InlineCastInterp.v +++ b/src/Compilers/InlineCastInterp.v @@ -1,14 +1,14 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.InlineCast. -Require Import Crypto.Reflection.InlineInterp. -Require Import Crypto.Reflection.SmartCast. -Require Import Crypto.Reflection.SmartCastInterp. -Require Import Crypto.Reflection.Inline. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.InlineCast. +Require Import Crypto.Compilers.InlineInterp. +Require Import Crypto.Compilers.SmartCast. +Require Import Crypto.Compilers.SmartCastInterp. +Require Import Crypto.Compilers.Inline. Require Import Crypto.Util.Option. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.DestructHead. diff --git a/src/Reflection/InlineCastWf.v b/src/Compilers/InlineCastWf.v index a61455c4f..f2d3cc84f 100644 --- a/src/Reflection/InlineCastWf.v +++ b/src/Compilers/InlineCastWf.v @@ -1,13 +1,13 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.WfInversion. -Require Import Crypto.Reflection.InlineCast. -Require Import Crypto.Reflection.InlineWf. -Require Import Crypto.Reflection.SmartCast. -Require Import Crypto.Reflection.SmartCastWf. -Require Import Crypto.Reflection.Inline. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.WfInversion. +Require Import Crypto.Compilers.InlineCast. +Require Import Crypto.Compilers.InlineWf. +Require Import Crypto.Compilers.SmartCast. +Require Import Crypto.Compilers.SmartCastWf. +Require Import Crypto.Compilers.Inline. Require Import Crypto.Util.Option. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.DestructHead. diff --git a/src/Reflection/InlineInterp.v b/src/Compilers/InlineInterp.v index cb9276d9a..5ec549054 100644 --- a/src/Reflection/InlineInterp.v +++ b/src/Compilers/InlineInterp.v @@ -1,10 +1,10 @@ (** * Inline: Remove some [Let] expressions *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.InlineWf. -Require Import Crypto.Reflection.InterpProofs. -Require Import Crypto.Reflection.Inline. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.InlineWf. +Require Import Crypto.Compilers.InterpProofs. +Require Import Crypto.Compilers.Inline. Require Import Crypto.Util.Sigma Crypto.Util.Prod. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.SpecializeBy. diff --git a/src/Reflection/InlineWf.v b/src/Compilers/InlineWf.v index 20ae25010..a0d77471c 100644 --- a/src/Reflection/InlineWf.v +++ b/src/Compilers/InlineWf.v @@ -1,11 +1,11 @@ (** * Inline: Remove some [Let] expressions *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.WfProofs. -Require Import Crypto.Reflection.WfInversion. -Require Import Crypto.Reflection.Inline. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.WfProofs. +Require Import Crypto.Compilers.WfInversion. +Require Import Crypto.Compilers.Inline. Require Import Crypto.Util.Tactics.SpecializeBy Crypto.Util.Tactics.DestructHead Crypto.Util.Sigma Crypto.Util.Prod. Require Import Crypto.Util.Option. Require Import Crypto.Util.Tactics.BreakMatch. diff --git a/src/Reflection/InputSyntax.v b/src/Compilers/InputSyntax.v index 123e4f851..22f7cdd61 100644 --- a/src/Reflection/InputSyntax.v +++ b/src/Compilers/InputSyntax.v @@ -1,9 +1,9 @@ (** * PHOAS Representation of Gallina which allows exact denotation *) Require Import Coq.Strings.String. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.InterpProofs. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.InterpProofs. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.Tactics.RewriteHyp. Require Import Crypto.Util.Notations. diff --git a/src/Reflection/InterpByIso.v b/src/Compilers/InterpByIso.v index a971b8e88..a2263364b 100644 --- a/src/Reflection/InterpByIso.v +++ b/src/Compilers/InterpByIso.v @@ -1,7 +1,7 @@ (** * PHOAS interpretation function for any retract of [var:=interp_base_type] *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.SmartMap. Section language. Context {base_type_code : Type} diff --git a/src/Reflection/InterpByIsoProofs.v b/src/Compilers/InterpByIsoProofs.v index 07ad8ed62..98e700738 100644 --- a/src/Reflection/InterpByIsoProofs.v +++ b/src/Compilers/InterpByIsoProofs.v @@ -1,10 +1,10 @@ (** * PHOAS interpretation function for any retract of [var:=interp_base_type] *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.InterpByIso. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfProofs. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.InterpByIso. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfProofs. +Require Import Crypto.Compilers.SmartMap. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Prod. Require Import Crypto.Util.Tactics.RewriteHyp. diff --git a/src/Reflection/InterpProofs.v b/src/Compilers/InterpProofs.v index 5d8322441..5ea1a99a4 100644 --- a/src/Reflection/InterpProofs.v +++ b/src/Compilers/InterpProofs.v @@ -1,7 +1,7 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.WfProofs. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.WfProofs. Require Import Crypto.Util.LetIn. Require Import Crypto.Util.Sigma Crypto.Util.Prod. Require Import Crypto.Util.Tactics.RewriteHyp. diff --git a/src/Reflection/InterpWf.v b/src/Compilers/InterpWf.v index 5f76e0791..e1572ceed 100644 --- a/src/Reflection/InterpWf.v +++ b/src/Compilers/InterpWf.v @@ -1,7 +1,7 @@ Require Import Coq.Strings.String Coq.Classes.RelationClasses. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Relations. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Relations. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/InterpWfRel.v b/src/Compilers/InterpWfRel.v index 40288232a..46be4220d 100644 --- a/src/Reflection/InterpWfRel.v +++ b/src/Compilers/InterpWfRel.v @@ -1,7 +1,7 @@ Require Import Coq.Strings.String Coq.Classes.RelationClasses. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Relations. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Relations. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/Linearize.v b/src/Compilers/Linearize.v index 9fc45c798..fc6957bf4 100644 --- a/src/Reflection/Linearize.v +++ b/src/Compilers/Linearize.v @@ -1,6 +1,6 @@ (** * Linearize: Place all and only operations in let binders *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. (*Require Import Crypto.Util.Tactics.*) Local Open Scope ctype_scope. diff --git a/src/Reflection/LinearizeInterp.v b/src/Compilers/LinearizeInterp.v index 293d80a34..6451431fa 100644 --- a/src/Reflection/LinearizeInterp.v +++ b/src/Compilers/LinearizeInterp.v @@ -1,10 +1,10 @@ (** * Linearize: Place all and only operations in let binders *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.LinearizeWf. -Require Import Crypto.Reflection.InterpProofs. -Require Import Crypto.Reflection.Linearize. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.LinearizeWf. +Require Import Crypto.Compilers.InterpProofs. +Require Import Crypto.Compilers.Linearize. Require Import Crypto.Util.Sigma Crypto.Util.Prod. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.SpecializeBy. diff --git a/src/Reflection/LinearizeWf.v b/src/Compilers/LinearizeWf.v index b12e83b56..073137fd4 100644 --- a/src/Reflection/LinearizeWf.v +++ b/src/Compilers/LinearizeWf.v @@ -1,8 +1,8 @@ (** * Linearize: Place all and only operations in let binders *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfProofs. -Require Import Crypto.Reflection.Linearize. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfProofs. +Require Import Crypto.Compilers.Linearize. Require Import (*Crypto.Util.Tactics*) Crypto.Util.Sigma. Local Open Scope ctype_scope. diff --git a/src/Reflection/Map.v b/src/Compilers/Map.v index 9faa69eb9..9fe9f7011 100644 --- a/src/Reflection/Map.v +++ b/src/Compilers/Map.v @@ -1,4 +1,4 @@ -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Section language. Context {base_type_code : Type} diff --git a/src/Reflection/MapCast.v b/src/Compilers/MapCast.v index 56736fa20..0cb453b00 100644 --- a/src/Reflection/MapCast.v +++ b/src/Compilers/MapCast.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.ExprInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.ExprInversion. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Prod. Require Import Crypto.Util.Option. diff --git a/src/Reflection/MapCastByDeBruijn.v b/src/Compilers/MapCastByDeBruijn.v index 68eb06a54..0964847a6 100644 --- a/src/Reflection/MapCastByDeBruijn.v +++ b/src/Compilers/MapCastByDeBruijn.v @@ -1,11 +1,11 @@ -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.MapCast. -Require Import Crypto.Reflection.Named.InterpretToPHOAS. -Require Import Crypto.Reflection.Named.Compile. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.Named.PositiveContext.Defaults. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.MapCast. +Require Import Crypto.Compilers.Named.InterpretToPHOAS. +Require Import Crypto.Compilers.Named.Compile. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.Named.PositiveContext.Defaults. +Require Import Crypto.Compilers.Syntax. (** N.B. This procedure only works when there are no nested lets, i.e., nothing like [let x := let y := z in w] in the PHOAS syntax diff --git a/src/Reflection/MapCastByDeBruijnInterp.v b/src/Compilers/MapCastByDeBruijnInterp.v index 90cbad00c..5d8156f09 100644 --- a/src/Reflection/MapCastByDeBruijnInterp.v +++ b/src/Compilers/MapCastByDeBruijnInterp.v @@ -1,18 +1,18 @@ -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.MapCastInterp. -Require Import Crypto.Reflection.Named.MapCastWf. -Require Import Crypto.Reflection.Named.InterpretToPHOASInterp. -Require Import Crypto.Reflection.Named.CompileInterp. -Require Import Crypto.Reflection.Named.CompileWf. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.Named.PositiveContext.Defaults. -Require Import Crypto.Reflection.Named.PositiveContext.DefaultsProperties. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.MapCastByDeBruijn. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.MapCastInterp. +Require Import Crypto.Compilers.Named.MapCastWf. +Require Import Crypto.Compilers.Named.InterpretToPHOASInterp. +Require Import Crypto.Compilers.Named.CompileInterp. +Require Import Crypto.Compilers.Named.CompileWf. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.Named.PositiveContext.Defaults. +Require Import Crypto.Compilers.Named.PositiveContext.DefaultsProperties. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.MapCastByDeBruijn. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.Option. Require Import Crypto.Util.Sigma. diff --git a/src/Reflection/MapCastByDeBruijnWf.v b/src/Compilers/MapCastByDeBruijnWf.v index 4fd3975f7..7bc58042f 100644 --- a/src/Reflection/MapCastByDeBruijnWf.v +++ b/src/Compilers/MapCastByDeBruijnWf.v @@ -1,16 +1,16 @@ -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.MapCastWf. -Require Import Crypto.Reflection.Named.InterpretToPHOASWf. -Require Import Crypto.Reflection.Named.CompileWf. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.Named.PositiveContext.Defaults. -Require Import Crypto.Reflection.Named.PositiveContext.DefaultsProperties. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.MapCastByDeBruijn. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.MapCastWf. +Require Import Crypto.Compilers.Named.InterpretToPHOASWf. +Require Import Crypto.Compilers.Named.CompileWf. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.Named.PositiveContext.Defaults. +Require Import Crypto.Compilers.Named.PositiveContext.DefaultsProperties. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.MapCastByDeBruijn. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.Option. Require Import Crypto.Util.Sigma. diff --git a/src/Reflection/MapCastInterp.v b/src/Compilers/MapCastInterp.v index 528e69e12..bbf4581b5 100644 --- a/src/Reflection/MapCastInterp.v +++ b/src/Compilers/MapCastInterp.v @@ -1,11 +1,11 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.MapCast. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.WfProofs. -Require Import Crypto.Reflection.WfInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.MapCast. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.WfProofs. +Require Import Crypto.Compilers.WfInversion. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Prod. Require Import Crypto.Util.Option. diff --git a/src/Reflection/MapCastWf.v b/src/Compilers/MapCastWf.v index 54e8d0020..2961b9426 100644 --- a/src/Reflection/MapCastWf.v +++ b/src/Compilers/MapCastWf.v @@ -1,10 +1,10 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.MapCast. -Require Import Crypto.Reflection.WfProofs. -Require Import Crypto.Reflection.WfInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.MapCast. +Require Import Crypto.Compilers.WfProofs. +Require Import Crypto.Compilers.WfInversion. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Prod. Require Import Crypto.Util.Option. diff --git a/src/Reflection/MultiSizeTest.v b/src/Compilers/MultiSizeTest.v index 2c7975113..fab0c65d8 100644 --- a/src/Reflection/MultiSizeTest.v +++ b/src/Compilers/MultiSizeTest.v @@ -1,5 +1,5 @@ Require Import Coq.omega.Omega. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.SmartMap. Set Implicit Arguments. Set Asymmetric Patterns. diff --git a/src/Reflection/MultiSizeTest2.v b/src/Compilers/MultiSizeTest2.v index 4bac3d14c..eac196510 100644 --- a/src/Reflection/MultiSizeTest2.v +++ b/src/Compilers/MultiSizeTest2.v @@ -1,7 +1,7 @@ Require Import Coq.omega.Omega. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.BoundByCast. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.BoundByCast. (** * Preliminaries: bounded and unbounded number types *) diff --git a/src/Reflection/Named/Compile.v b/src/Compilers/Named/Compile.v index 55f4aba70..bee71cea5 100644 --- a/src/Reflection/Named/Compile.v +++ b/src/Compilers/Named/Compile.v @@ -1,7 +1,7 @@ (** * PHOAS → Named Representation of Gallina *) -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.NameUtil. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.NameUtil. +Require Import Crypto.Compilers.Syntax. Local Notation eta x := (fst x, snd x). diff --git a/src/Reflection/Named/CompileInterp.v b/src/Compilers/Named/CompileInterp.v index 100d53aa3..1c7e42258 100644 --- a/src/Reflection/Named/CompileInterp.v +++ b/src/Compilers/Named/CompileInterp.v @@ -1,13 +1,13 @@ (** * PHOAS → Named Representation of Gallina *) -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.NameUtil. -Require Import Crypto.Reflection.Named.NameUtilProperties. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.ContextProperties.NameUtil. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Named.Compile. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.NameUtil. +Require Import Crypto.Compilers.Named.NameUtilProperties. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.ContextProperties.NameUtil. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Named.Compile. Require Import Crypto.Util.PointedProp. Require Import Crypto.Util.Option. Require Import Crypto.Util.Decidable. diff --git a/src/Reflection/Named/CompileProperties.v b/src/Compilers/Named/CompileProperties.v index 357004197..9803946b2 100644 --- a/src/Reflection/Named/CompileProperties.v +++ b/src/Compilers/Named/CompileProperties.v @@ -1,11 +1,11 @@ Require Import Coq.omega.Omega. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.NameUtil. -Require Import Crypto.Reflection.Named.NameUtilProperties. -Require Import Crypto.Reflection.Named.Compile. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.CountLets. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.NameUtil. +Require Import Crypto.Compilers.Named.NameUtilProperties. +Require Import Crypto.Compilers.Named.Compile. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.CountLets. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.SpecializeBy. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/Named/CompileWf.v b/src/Compilers/Named/CompileWf.v index 5fb17b18d..aea8cb2b1 100644 --- a/src/Reflection/Named/CompileWf.v +++ b/src/Compilers/Named/CompileWf.v @@ -1,14 +1,14 @@ (** * PHOAS → Named Representation of Gallina *) -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.Wf. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.ContextProperties.NameUtil. -Require Import Crypto.Reflection.Named.NameUtil. -Require Import Crypto.Reflection.Named.NameUtilProperties. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Named.Compile. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.Wf. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.ContextProperties.NameUtil. +Require Import Crypto.Compilers.Named.NameUtil. +Require Import Crypto.Compilers.Named.NameUtilProperties. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Named.Compile. Require Import Crypto.Util.PointedProp. Require Import Crypto.Util.Option. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/Named/ContextDefinitions.v b/src/Compilers/Named/ContextDefinitions.v index c63142de6..6e1a3e64a 100644 --- a/src/Reflection/Named/ContextDefinitions.v +++ b/src/Compilers/Named/ContextDefinitions.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Decidable. diff --git a/src/Reflection/Named/ContextOn.v b/src/Compilers/Named/ContextOn.v index d32911283..6c06d3fbe 100644 --- a/src/Reflection/Named/ContextOn.v +++ b/src/Compilers/Named/ContextOn.v @@ -1,5 +1,5 @@ (** * Transfer [Context] across an injection *) -Require Import Crypto.Reflection.Named.Syntax. +Require Import Crypto.Compilers.Named.Syntax. Section language. Context {base_type_code Name1 Name2 : Type} diff --git a/src/Reflection/Named/ContextProperties.v b/src/Compilers/Named/ContextProperties.v index c031d0af2..c2a9ca828 100644 --- a/src/Reflection/Named/ContextProperties.v +++ b/src/Compilers/Named/ContextProperties.v @@ -1,7 +1,7 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties.Tactics. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties.Tactics. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.Tactics.BreakMatch. diff --git a/src/Reflection/Named/ContextProperties/NameUtil.v b/src/Compilers/Named/ContextProperties/NameUtil.v index 4853f9a41..96653ac99 100644 --- a/src/Reflection/Named/ContextProperties/NameUtil.v +++ b/src/Compilers/Named/ContextProperties/NameUtil.v @@ -1,13 +1,13 @@ Require Import Coq.omega.Omega. Require Import Crypto.Util.FixCoqMistakes. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.NameUtil. -Require Import Crypto.Reflection.Named.NameUtilProperties. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.ContextProperties.Tactics. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.NameUtil. +Require Import Crypto.Compilers.Named.NameUtilProperties. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.ContextProperties.Tactics. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.ListUtil. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/Named/ContextProperties/SmartMap.v b/src/Compilers/Named/ContextProperties/SmartMap.v index 89d0d1c5d..7cf761a34 100644 --- a/src/Reflection/Named/ContextProperties/SmartMap.v +++ b/src/Compilers/Named/ContextProperties/SmartMap.v @@ -1,10 +1,10 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.ContextProperties.Tactics. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.ContextProperties.Tactics. Require Import Crypto.Util.Decidable. Section with_context. diff --git a/src/Reflection/Named/ContextProperties/Tactics.v b/src/Compilers/Named/ContextProperties/Tactics.v index 91d6d20d2..9616725d6 100644 --- a/src/Reflection/Named/ContextProperties/Tactics.v +++ b/src/Compilers/Named/ContextProperties/Tactics.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.Option. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/Named/DeadCodeElimination.v b/src/Compilers/Named/DeadCodeElimination.v index d97c36742..312370834 100644 --- a/src/Reflection/Named/DeadCodeElimination.v +++ b/src/Compilers/Named/DeadCodeElimination.v @@ -1,12 +1,12 @@ (** * PHOAS → Named Representation of Gallina *) Require Import Coq.PArith.BinPos Coq.Lists.List. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.Compile. -Require Import Crypto.Reflection.Named.RegisterAssign. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.Named.EstablishLiveness. -Require Import Crypto.Reflection.CountLets. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.Compile. +Require Import Crypto.Compilers.Named.RegisterAssign. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.Named.EstablishLiveness. +Require Import Crypto.Compilers.CountLets. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.ListUtil. Require Import Crypto.Util.LetIn. diff --git a/src/Reflection/Named/EstablishLiveness.v b/src/Compilers/Named/EstablishLiveness.v index 7509d5f7a..5d1255af3 100644 --- a/src/Reflection/Named/EstablishLiveness.v +++ b/src/Compilers/Named/EstablishLiveness.v @@ -1,9 +1,9 @@ (** * Compute a list of liveness values for each binding *) Require Import Coq.Lists.List. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.CountLets. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.CountLets. Require Import Crypto.Util.ListUtil. Local Notation eta x := (fst x, snd x). diff --git a/src/Reflection/Named/FMapContext.v b/src/Compilers/Named/FMapContext.v index e01186f2c..1ea45cbbe 100644 --- a/src/Reflection/Named/FMapContext.v +++ b/src/Compilers/Named/FMapContext.v @@ -1,8 +1,8 @@ Require Import Coq.Bool.Sumbool. Require Import Coq.FSets.FMapInterface. Require Import Coq.FSets.FMapFacts. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Equality. diff --git a/src/Reflection/Named/IdContext.v b/src/Compilers/Named/IdContext.v index c2a6936f8..5ed1e7cf2 100644 --- a/src/Reflection/Named/IdContext.v +++ b/src/Compilers/Named/IdContext.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. Section language. Context {base_type_code Name} diff --git a/src/Reflection/Named/InterpretToPHOAS.v b/src/Compilers/Named/InterpretToPHOAS.v index a9a44a93f..dc737a38d 100644 --- a/src/Reflection/Named/InterpretToPHOAS.v +++ b/src/Compilers/Named/InterpretToPHOAS.v @@ -1,7 +1,7 @@ -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.PointedProp. Local Notation eta_and x := (conj (let (a, b) := x in a) (let (a, b) := x in b)). diff --git a/src/Reflection/Named/InterpretToPHOASInterp.v b/src/Compilers/Named/InterpretToPHOASInterp.v index 4f66e94d4..0772721f6 100644 --- a/src/Reflection/Named/InterpretToPHOASInterp.v +++ b/src/Compilers/Named/InterpretToPHOASInterp.v @@ -1,10 +1,10 @@ -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.Wf. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.InterpretToPHOAS. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.Wf. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.InterpretToPHOAS. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. Require Import Crypto.Util.PointedProp. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.Option. diff --git a/src/Reflection/Named/InterpretToPHOASWf.v b/src/Compilers/Named/InterpretToPHOASWf.v index daab24b62..c0e59d10e 100644 --- a/src/Reflection/Named/InterpretToPHOASWf.v +++ b/src/Compilers/Named/InterpretToPHOASWf.v @@ -1,11 +1,11 @@ -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.Wf. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.ContextProperties.SmartMap. -Require Import Crypto.Reflection.Named.InterpretToPHOAS. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.Wf. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.ContextProperties.SmartMap. +Require Import Crypto.Compilers.Named.InterpretToPHOAS. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. Require Import Crypto.Util.PointedProp. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.Option. diff --git a/src/Reflection/Named/MapCast.v b/src/Compilers/Named/MapCast.v index a0b161a0a..83c477765 100644 --- a/src/Reflection/Named/MapCast.v +++ b/src/Compilers/Named/MapCast.v @@ -1,7 +1,7 @@ Require Import Coq.Bool.Sumbool. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. Local Open Scope nexpr_scope. Section language. diff --git a/src/Reflection/Named/MapCastInterp.v b/src/Compilers/Named/MapCastInterp.v index b7afa1494..f3842e691 100644 --- a/src/Reflection/Named/MapCastInterp.v +++ b/src/Compilers/Named/MapCastInterp.v @@ -1,13 +1,13 @@ Require Import Coq.Bool.Sumbool. Require Import Coq.Logic.Eqdep_dec. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.ContextProperties.SmartMap. -Require Import Crypto.Reflection.Named.MapCast. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.ContextProperties.SmartMap. +Require Import Crypto.Compilers.Named.MapCast. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Bool. Require Import Crypto.Util.Option. diff --git a/src/Reflection/Named/MapCastWf.v b/src/Compilers/Named/MapCastWf.v index f05df34c1..cd8a2e720 100644 --- a/src/Reflection/Named/MapCastWf.v +++ b/src/Compilers/Named/MapCastWf.v @@ -1,14 +1,14 @@ Require Import Coq.Bool.Sumbool. Require Import Coq.Logic.Eqdep_dec. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.ContextDefinitions. -Require Import Crypto.Reflection.Named.ContextProperties. -Require Import Crypto.Reflection.Named.ContextProperties.SmartMap. -Require Import Crypto.Reflection.Named.Wf. -Require Import Crypto.Reflection.Named.MapCast. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.ContextDefinitions. +Require Import Crypto.Compilers.Named.ContextProperties. +Require Import Crypto.Compilers.Named.ContextProperties.SmartMap. +Require Import Crypto.Compilers.Named.Wf. +Require Import Crypto.Compilers.Named.MapCast. Require Import Crypto.Util.PointedProp. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Bool. diff --git a/src/Reflection/Named/NameUtil.v b/src/Compilers/Named/NameUtil.v index 5356cd132..8b099ffdf 100644 --- a/src/Reflection/Named/NameUtil.v +++ b/src/Compilers/Named/NameUtil.v @@ -1,5 +1,5 @@ Require Import Coq.Lists.List. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Local Open Scope core_scope. Local Notation eta x := (fst x, snd x). diff --git a/src/Reflection/Named/NameUtilProperties.v b/src/Compilers/Named/NameUtilProperties.v index 9a52ff49d..d2791a5ea 100644 --- a/src/Reflection/Named/NameUtilProperties.v +++ b/src/Compilers/Named/NameUtilProperties.v @@ -1,9 +1,9 @@ Require Import Coq.omega.Omega. Require Import Coq.Arith.Arith. Require Import Coq.Lists.List. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.CountLets. -Require Import Crypto.Reflection.Named.NameUtil. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.CountLets. +Require Import Crypto.Compilers.Named.NameUtil. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.RewriteHyp. Require Import Crypto.Util.Tactics.SplitInContext. diff --git a/src/Reflection/Named/PositiveContext.v b/src/Compilers/Named/PositiveContext.v index 4356a174a..8291c8acf 100644 --- a/src/Reflection/Named/PositiveContext.v +++ b/src/Compilers/Named/PositiveContext.v @@ -1,6 +1,6 @@ Require Import Coq.FSets.FMapPositive. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.FMapContext. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.FMapContext. Module PositiveContext := FMapContext PositiveMap. Notation PositiveContext := PositiveContext.FMapContext. diff --git a/src/Reflection/Named/PositiveContext/Defaults.v b/src/Compilers/Named/PositiveContext/Defaults.v index 34ce169f2..7e0c011f1 100644 --- a/src/Reflection/Named/PositiveContext/Defaults.v +++ b/src/Compilers/Named/PositiveContext/Defaults.v @@ -1,8 +1,8 @@ Require Import Coq.Lists.List. Require Import Coq.Numbers.BinNums. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.CountLets. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.CountLets. Section language. Context {base_type_code : Type} diff --git a/src/Reflection/Named/PositiveContext/DefaultsProperties.v b/src/Compilers/Named/PositiveContext/DefaultsProperties.v index 435a4c74c..2b46de136 100644 --- a/src/Reflection/Named/PositiveContext/DefaultsProperties.v +++ b/src/Compilers/Named/PositiveContext/DefaultsProperties.v @@ -1,10 +1,10 @@ Require Import Coq.Lists.List. Require Import Coq.Numbers.BinNums. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.CountLets. -Require Import Crypto.Reflection.Named.NameUtil. -Require Import Crypto.Reflection.Named.PositiveContext.Defaults. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.CountLets. +Require Import Crypto.Compilers.Named.NameUtil. +Require Import Crypto.Compilers.Named.PositiveContext.Defaults. Require Import Crypto.Util.ListUtil. Require Import Crypto.Util.Option. Require Import Crypto.Util.NatUtil. diff --git a/src/Reflection/Named/RegisterAssign.v b/src/Compilers/Named/RegisterAssign.v index 18e15519a..d1e871fd0 100644 --- a/src/Reflection/Named/RegisterAssign.v +++ b/src/Compilers/Named/RegisterAssign.v @@ -1,8 +1,8 @@ (** * Reassign registers *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.NameUtil. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.NameUtil. Require Import Crypto.Util.Decidable. Local Notation eta x := (fst x, snd x). diff --git a/src/Reflection/Named/SmartMap.v b/src/Compilers/Named/SmartMap.v index 3cacf7a1b..76b2eec58 100644 --- a/src/Reflection/Named/SmartMap.v +++ b/src/Compilers/Named/SmartMap.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Named.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Named.Syntax. Module Export Named. Section language. diff --git a/src/Reflection/Named/Syntax.v b/src/Compilers/Named/Syntax.v index b4846be9a..c58fcc9d1 100644 --- a/src/Reflection/Named/Syntax.v +++ b/src/Compilers/Named/Syntax.v @@ -1,7 +1,7 @@ (** * Named Representation of Gallina *) Require Import Coq.Classes.RelationClasses. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. Require Import Crypto.Util.PointedProp. Require Import Crypto.Util.Tuple. (*Require Import Crypto.Util.Tactics.*) diff --git a/src/Reflection/Named/Wf.v b/src/Compilers/Named/Wf.v index 6b1e68e65..df2213b21 100644 --- a/src/Reflection/Named/Wf.v +++ b/src/Compilers/Named/Wf.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. Require Import Crypto.Util.PointedProp. Module Export Named. diff --git a/src/Reflection/Named/WfInterp.v b/src/Compilers/Named/WfInterp.v index c5fe2bb3a..b44811b06 100644 --- a/src/Reflection/Named/WfInterp.v +++ b/src/Compilers/Named/WfInterp.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.Wf. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.Wf. Require Import Crypto.Util.PointedProp. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.SpecializeBy. diff --git a/src/Reflection/Reify.v b/src/Compilers/Reify.v index adc3feec8..bfe94d857 100644 --- a/src/Reflection/Reify.v +++ b/src/Compilers/Reify.v @@ -2,9 +2,9 @@ (** The reification procedure goes through [InputSyntax], which allows judgmental equality of the denotation of the reified term. *) Require Import Coq.Strings.String. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.InputSyntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.InputSyntax. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.Tactics.DebugPrint. (*Require Import Crypto.Util.Tactics.PrintContext.*) @@ -17,7 +17,7 @@ Require Import Crypto.Util.Tactics.TransparentAssert. more debugging. *) Ltac reify_debug_level := constr:(0). Module Import ReifyDebugNotations. - Export Reflection.Syntax.Notations. + Export Compilers.Syntax.Notations. Export Util.LetIn. Open Scope string_scope. End ReifyDebugNotations. diff --git a/src/Reflection/Relations.v b/src/Compilers/Relations.v index 9a927243d..27a101e4f 100644 --- a/src/Reflection/Relations.v +++ b/src/Compilers/Relations.v @@ -1,7 +1,7 @@ Require Import Coq.Lists.List Coq.Classes.RelationClasses Coq.Classes.Morphisms. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Wf. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Wf. Require Import Crypto.Util.Tactics.RewriteHyp. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.SplitInContext. diff --git a/src/Reflection/RenameBinders.v b/src/Compilers/RenameBinders.v index cd40e4366..7be603cbe 100644 --- a/src/Reflection/RenameBinders.v +++ b/src/Compilers/RenameBinders.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.ExprInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.ExprInversion. Ltac uncurry_f f := let t := type of f in diff --git a/src/Reflection/Rewriter.v b/src/Compilers/Rewriter.v index b53d0903d..a23627480 100644 --- a/src/Reflection/Rewriter.v +++ b/src/Compilers/Rewriter.v @@ -1,4 +1,4 @@ -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Section language. Context {base_type_code : Type} diff --git a/src/Reflection/RewriterInterp.v b/src/Compilers/RewriterInterp.v index 4a18c0a47..1f9fa5bed 100644 --- a/src/Reflection/RewriterInterp.v +++ b/src/Compilers/RewriterInterp.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Rewriter. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Rewriter. Require Import Crypto.Util.Tactics.RewriteHyp. Section language. diff --git a/src/Reflection/RewriterWf.v b/src/Compilers/RewriterWf.v index a7ac86851..0dfdbaab6 100644 --- a/src/Reflection/RewriterWf.v +++ b/src/Compilers/RewriterWf.v @@ -1,7 +1,7 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfInversion. -Require Import Crypto.Reflection.Rewriter. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfInversion. +Require Import Crypto.Compilers.Rewriter. Section language. Context {base_type_code : Type} diff --git a/src/Reflection/SmartBound.v b/src/Compilers/SmartBound.v index 56014c7b6..39fd34dd7 100644 --- a/src/Reflection/SmartBound.v +++ b/src/Compilers/SmartBound.v @@ -1,8 +1,8 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.SmartCast. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.SmartCast. +Require Import Crypto.Compilers.SmartMap. Require Import Crypto.Util.Notations. Local Open Scope expr_scope. diff --git a/src/Reflection/SmartBoundInterp.v b/src/Compilers/SmartBoundInterp.v index 0262ef615..bd43f36a8 100644 --- a/src/Reflection/SmartBoundInterp.v +++ b/src/Compilers/SmartBoundInterp.v @@ -1,20 +1,20 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.InterpWfRel. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.SmartMap. -(*Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.BoundByCast.*) -Require Import Crypto.Reflection.SmartBound. -Require Import Crypto.Reflection.ExprInversion. -(*Require Import Crypto.Reflection.SmartBoundWf. -Require Import Crypto.Reflection.InlineCastInterp. -Require Import Crypto.Reflection.InlineInterp. -Require Import Crypto.Reflection.LinearizeInterp. -Require Import Crypto.Reflection.LinearizeWf. -Require Import Crypto.Reflection.MapCastInterp. -Require Import Crypto.Reflection.MapCastWf. -Require Import Crypto.Reflection.EtaInterp.*) +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.InterpWfRel. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.SmartMap. +(*Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.BoundByCast.*) +Require Import Crypto.Compilers.SmartBound. +Require Import Crypto.Compilers.ExprInversion. +(*Require Import Crypto.Compilers.SmartBoundWf. +Require Import Crypto.Compilers.InlineCastInterp. +Require Import Crypto.Compilers.InlineInterp. +Require Import Crypto.Compilers.LinearizeInterp. +Require Import Crypto.Compilers.LinearizeWf. +Require Import Crypto.Compilers.MapCastInterp. +Require Import Crypto.Compilers.MapCastWf. +Require Import Crypto.Compilers.EtaInterp.*) Require Import Crypto.Util.Tactics.DestructHead. Local Open Scope expr_scope. diff --git a/src/Reflection/SmartBoundWf.v b/src/Compilers/SmartBoundWf.v index 72c5c1475..ae7f2c81f 100644 --- a/src/Reflection/SmartBoundWf.v +++ b/src/Compilers/SmartBoundWf.v @@ -1,12 +1,12 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfProofs. -Require Import Crypto.Reflection.SmartBound. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.SmartCastWf. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfProofs. +Require Import Crypto.Compilers.SmartBound. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.SmartCastWf. +Require Import Crypto.Compilers.SmartMap. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Notations. diff --git a/src/Reflection/SmartCast.v b/src/Compilers/SmartCast.v index ee3712954..237907e9c 100644 --- a/src/Reflection/SmartCast.v +++ b/src/Compilers/SmartCast.v @@ -1,6 +1,6 @@ Require Import Coq.Bool.Sumbool. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeUtil. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeUtil. Require Import Crypto.Util.Notations. Local Open Scope expr_scope. diff --git a/src/Reflection/SmartCastInterp.v b/src/Compilers/SmartCastInterp.v index 92ca265e1..e755cd168 100644 --- a/src/Reflection/SmartCastInterp.v +++ b/src/Compilers/SmartCastInterp.v @@ -1,7 +1,7 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.SmartCast. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.SmartCast. Require Import Crypto.Util.Notations. Local Open Scope expr_scope. diff --git a/src/Reflection/SmartCastWf.v b/src/Compilers/SmartCastWf.v index 4c5601669..8ff630b77 100644 --- a/src/Reflection/SmartCastWf.v +++ b/src/Compilers/SmartCastWf.v @@ -1,8 +1,8 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfProofs. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.SmartCast. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfProofs. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.SmartCast. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Option. Require Import Crypto.Util.Notations. diff --git a/src/Reflection/SmartMap.v b/src/Compilers/SmartMap.v index 934497f65..5dfa38a1a 100644 --- a/src/Reflection/SmartMap.v +++ b/src/Compilers/SmartMap.v @@ -1,5 +1,5 @@ Require Import Coq.Classes.Morphisms. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.Tactics.RewriteHyp. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Notations. diff --git a/src/Reflection/Syntax.v b/src/Compilers/Syntax.v index d8b88e560..d8b88e560 100644 --- a/src/Reflection/Syntax.v +++ b/src/Compilers/Syntax.v diff --git a/src/Reflection/TestCase.v b/src/Compilers/TestCase.v index dffa1631a..0db93721e 100644 --- a/src/Reflection/TestCase.v +++ b/src/Compilers/TestCase.v @@ -1,19 +1,18 @@ Require Import Coq.omega.Omega Coq.micromega.Psatz. Require Import Coq.PArith.BinPos Coq.Lists.List. -Require Import Crypto.Reflection.Named.Syntax. -Require Import Crypto.Reflection.Named.Compile. -Require Import Crypto.Reflection.Named.RegisterAssign. -Require Import Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfReflective. -Require Import Crypto.Reflection.Equality. -Require Export Crypto.Reflection.Reify. -Require Import Crypto.Reflection.InputSyntax. -Require Import Crypto.Reflection.CommonSubexpressionElimination. -Require Crypto.Reflection.Linearize Crypto.Reflection.Inline. -Require Import Crypto.Reflection.WfReflective. -Require Import Crypto.Reflection.Conversion. +Require Import Crypto.Compilers.Named.Syntax. +Require Import Crypto.Compilers.Named.Compile. +Require Import Crypto.Compilers.Named.RegisterAssign. +Require Import Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Equality. +Require Export Crypto.Compilers.Reify. +Require Import Crypto.Compilers.InputSyntax. +Require Import Crypto.Compilers.CommonSubexpressionElimination. +Require Crypto.Compilers.Linearize Crypto.Compilers.Inline. +Require Import Crypto.Compilers.WfReflective. +Require Import Crypto.Compilers.Conversion. Require Import Crypto.Util.NatUtil. Import ReifyDebugNotations. diff --git a/src/Reflection/Tuple.v b/src/Compilers/Tuple.v index 519325b82..0ee0d8ae2 100644 --- a/src/Reflection/Tuple.v +++ b/src/Compilers/Tuple.v @@ -1,5 +1,5 @@ Require Import Crypto.Util.Tuple. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Local Open Scope ctype_scope. Section language. diff --git a/src/Reflection/TypeInversion.v b/src/Compilers/TypeInversion.v index 2138a3788..ab00a1dc5 100644 --- a/src/Reflection/TypeInversion.v +++ b/src/Compilers/TypeInversion.v @@ -1,4 +1,4 @@ -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.FixCoqMistakes. Section language. diff --git a/src/Reflection/TypeUtil.v b/src/Compilers/TypeUtil.v index 8f7661bde..050374562 100644 --- a/src/Reflection/TypeUtil.v +++ b/src/Compilers/TypeUtil.v @@ -1,4 +1,4 @@ -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.Notations. Local Open Scope expr_scope. diff --git a/src/Reflection/Wf.v b/src/Compilers/Wf.v index 91a99b150..f3f653696 100644 --- a/src/Reflection/Wf.v +++ b/src/Compilers/Wf.v @@ -1,5 +1,5 @@ Require Import Coq.Lists.List. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.Notations. Create HintDb wf discriminated. diff --git a/src/Reflection/WfInversion.v b/src/Compilers/WfInversion.v index d76fd90f4..79869e554 100644 --- a/src/Reflection/WfInversion.v +++ b/src/Compilers/WfInversion.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.ExprInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.ExprInversion. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Option. Require Import Crypto.Util.Equality. diff --git a/src/Reflection/WfProofs.v b/src/Compilers/WfProofs.v index ca1f50478..ea06c8b89 100644 --- a/src/Reflection/WfProofs.v +++ b/src/Compilers/WfProofs.v @@ -1,8 +1,8 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfInversion. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.ExprInversion. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfInversion. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.ExprInversion. Require Import Crypto.Util.Sigma Crypto.Util.Prod. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.RewriteHyp. diff --git a/src/Reflection/WfReflective.v b/src/Compilers/WfReflective.v index c54537fa2..4ba6d7a53 100644 --- a/src/Reflection/WfReflective.v +++ b/src/Compilers/WfReflective.v @@ -48,10 +48,10 @@ -> reified_Prop] *) Require Import Coq.Arith.Arith Coq.Logic.Eqdep_dec. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.EtaWf. -Require Import Crypto.Reflection.WfReflectiveGen. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.EtaWf. +Require Import Crypto.Compilers.WfReflectiveGen. Require Import Crypto.Util.Notations Crypto.Util.Option Crypto.Util.Sigma Crypto.Util.Prod Crypto.Util.Decidable Crypto.Util.ListUtil. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.SpecializeBy. diff --git a/src/Reflection/WfReflectiveGen.v b/src/Compilers/WfReflectiveGen.v index 23cdd8691..4de378451 100644 --- a/src/Reflection/WfReflectiveGen.v +++ b/src/Compilers/WfReflectiveGen.v @@ -48,10 +48,10 @@ -> option pointed_Prop] *) Require Import Coq.Arith.Arith Coq.Logic.Eqdep_dec. -Require Import Crypto.Reflection.Syntax. +Require Import Crypto.Compilers.Syntax. Require Import Crypto.Util.Notations Crypto.Util.Option Crypto.Util.Sigma Crypto.Util.Prod Crypto.Util.Decidable Crypto.Util.ListUtil. Require Import Crypto.Util.Tactics.RewriteHyp. -Require Import Crypto.Reflection.Wf. +Require Import Crypto.Compilers.Wf. Require Export Crypto.Util.PartiallyReifiedProp. (* export for the [bool >-> reified_Prop] coercion *) Require Export Crypto.Util.FixCoqMistakes. diff --git a/src/Reflection/Z/ArithmeticSimplifier.v b/src/Compilers/Z/ArithmeticSimplifier.v index 4e5d6126e..b2621c625 100644 --- a/src/Reflection/Z/ArithmeticSimplifier.v +++ b/src/Compilers/Z/ArithmeticSimplifier.v @@ -1,8 +1,8 @@ (** * SimplifyArith: Remove things like (_ * 1), (_ + 0), etc *) Require Import Coq.ZArith.ZArith. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Rewriter. -Require Import Crypto.Reflection.Z.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Rewriter. +Require Import Crypto.Compilers.Z.Syntax. Section language. Local Notation exprf := (@exprf base_type op). @@ -175,9 +175,6 @@ Section language. | Lor _ _ _ as opc | OpConst _ _ as opc | Opp _ _ as opc - | Neg _ _ _ as opc - | Cmovne _ _ _ _ _ as opc - | Cmovle _ _ _ _ _ as opc => Op opc end. End with_var. diff --git a/src/Reflection/Z/ArithmeticSimplifierInterp.v b/src/Compilers/Z/ArithmeticSimplifierInterp.v index 0c77d8179..6eec2f2a4 100644 --- a/src/Reflection/Z/ArithmeticSimplifierInterp.v +++ b/src/Compilers/Z/ArithmeticSimplifierInterp.v @@ -1,14 +1,14 @@ Require Import Coq.micromega.Psatz. Require Import Coq.ZArith.ZArith. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.RewriterInterp. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.OpInversion. -Require Import Crypto.Reflection.Z.ArithmeticSimplifier. -Require Import Crypto.Reflection.Z.ArithmeticSimplifierUtil. -Require Import Crypto.Reflection.Z.Syntax.Equality. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.RewriterInterp. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.OpInversion. +Require Import Crypto.Compilers.Z.ArithmeticSimplifier. +Require Import Crypto.Compilers.Z.ArithmeticSimplifierUtil. +Require Import Crypto.Compilers.Z.Syntax.Equality. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Option. Require Import Crypto.Util.Prod. diff --git a/src/Reflection/Z/ArithmeticSimplifierUtil.v b/src/Compilers/Z/ArithmeticSimplifierUtil.v index 10cf87eaa..49d3a2257 100644 --- a/src/Reflection/Z/ArithmeticSimplifierUtil.v +++ b/src/Compilers/Z/ArithmeticSimplifierUtil.v @@ -1,5 +1,5 @@ -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.ArithmeticSimplifier. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.ArithmeticSimplifier. (** ** Equality for [inverted_expr] *) Section inverted_expr. diff --git a/src/Reflection/Z/ArithmeticSimplifierWf.v b/src/Compilers/Z/ArithmeticSimplifierWf.v index 70e47f24f..24a9b4d23 100644 --- a/src/Reflection/Z/ArithmeticSimplifierWf.v +++ b/src/Compilers/Z/ArithmeticSimplifierWf.v @@ -1,13 +1,13 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfInversion. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.ExprInversion. -Require Import Crypto.Reflection.RewriterWf. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.OpInversion. -Require Import Crypto.Reflection.Z.ArithmeticSimplifier. -Require Import Crypto.Reflection.Z.Syntax.Equality. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfInversion. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.ExprInversion. +Require Import Crypto.Compilers.RewriterWf. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.OpInversion. +Require Import Crypto.Compilers.Z.ArithmeticSimplifier. +Require Import Crypto.Compilers.Z.Syntax.Equality. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Option. Require Import Crypto.Util.Sum. diff --git a/src/Reflection/Z/BinaryNotationConstants.v b/src/Compilers/Z/BinaryNotationConstants.v index 80b9809bc..d1f782597 100644 --- a/src/Reflection/Z/BinaryNotationConstants.v +++ b/src/Compilers/Z/BinaryNotationConstants.v @@ -1,5 +1,5 @@ -Require Export Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.Syntax. +Require Export Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.Syntax. Require Export Bedrock.Word. Require Export Crypto.Util.Notations. diff --git a/src/Reflection/Z/Bounds/Interpretation.v b/src/Compilers/Z/Bounds/Interpretation.v index 3d6d65c98..b9880f097 100644 --- a/src/Reflection/Z/Bounds/Interpretation.v +++ b/src/Compilers/Z/Bounds/Interpretation.v @@ -1,12 +1,12 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Relations. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Relations. Require Import Crypto.Util.Notations. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.ZRange. Require Import Crypto.Util.Tactics.DestructHead. -Export Reflection.Syntax.Notations. +Export Compilers.Syntax.Notations. Local Notation eta x := (fst x, snd x). Local Notation eta3 x := (eta (fst x), snd x). @@ -140,9 +140,6 @@ Module Import Bounds. | Land _ _ T => fun xy => land (bit_width_of_base_type T) (fst xy) (snd xy) | Lor _ _ T => fun xy => lor (bit_width_of_base_type T) (fst xy) (snd xy) | Opp _ T => fun x => opp (bit_width_of_base_type T) x - | Neg _ T int_width => fun x => neg (bit_width_of_base_type T) int_width x - | Cmovne _ _ _ _ T => fun xyzw => let '(x, y, z, w) := eta4 xyzw in cmovne (bit_width_of_base_type T) x y z w - | Cmovle _ _ _ _ T => fun xyzw => let '(x, y, z, w) := eta4 xyzw in cmovle (bit_width_of_base_type T) x y z w end%bounds. Definition of_Z (z : Z) : t := ZToZRange z. diff --git a/src/Reflection/Z/Bounds/InterpretationLemmas.v b/src/Compilers/Z/Bounds/InterpretationLemmas.v index 0c7791a2f..7a1c2bc73 100644 --- a/src/Reflection/Z/Bounds/InterpretationLemmas.v +++ b/src/Compilers/Z/Bounds/InterpretationLemmas.v @@ -1,10 +1,10 @@ Require Import Coq.ZArith.ZArith. Require Import Coq.micromega.Psatz. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. -Require Import Crypto.Reflection.SmartMap. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.SmartMap. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Bool. Require Import Crypto.Util.FixedWordSizesEquality. @@ -241,20 +241,6 @@ Proof. | word_arith_t ]. Qed. -Local Ltac t_special_case_op_step := - first [ fin_t - | progress intros - | progress subst - | progress simpl in * - | progress split_andb - | progress Zarith_t_step - | specializer_t_step - | rewriter_t - | progress break_t_step - | progress split_min_max - | progress cbv [Bounds.neg' Bounds.cmovne' Bounds.cmovle' ModularBaseSystemListZOperations.neg ModularBaseSystemListZOperations.cmovne ModularBaseSystemListZOperations.cmovl] ]. -Local Ltac t_special_case_op := repeat t_special_case_op_step. - Local Arguments Z.pow : simpl never. Local Arguments Z.add !_ !_. Local Existing Instances Z.add_le_Proper Z.log2_up_le_Proper Z.pow_Zpos_le_Proper Z.sub_le_eq_Proper. @@ -310,9 +296,6 @@ Proof. | progress simpl in * | progress split_min_max | omega ]. } - { t_special_case_op. } - { t_special_case_op. } - { t_special_case_op. } Admitted. Local Arguments lift_op : simpl never. diff --git a/src/Reflection/Z/Bounds/MapCastByDeBruijn.v b/src/Compilers/Z/Bounds/MapCastByDeBruijn.v index d99133e51..45b084566 100644 --- a/src/Reflection/Z/Bounds/MapCastByDeBruijn.v +++ b/src/Compilers/Z/Bounds/MapCastByDeBruijn.v @@ -1,8 +1,8 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.MapCastByDeBruijn. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.MapCastByDeBruijn. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. Section language. Context {t : type base_type}. diff --git a/src/Reflection/Z/Bounds/MapCastByDeBruijnInterp.v b/src/Compilers/Z/Bounds/MapCastByDeBruijnInterp.v index a7dc016bd..46f472311 100644 --- a/src/Reflection/Z/Bounds/MapCastByDeBruijnInterp.v +++ b/src/Compilers/Z/Bounds/MapCastByDeBruijnInterp.v @@ -1,13 +1,13 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Z.MapCastByDeBruijnInterp. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. -Require Import Crypto.Reflection.Z.Bounds.InterpretationLemmas. -Require Import Crypto.Reflection.Z.Bounds.MapCastByDeBruijn. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Z.MapCastByDeBruijnInterp. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Z.Bounds.InterpretationLemmas. +Require Import Crypto.Compilers.Z.Bounds.MapCastByDeBruijn. Lemma MapCastCorrect {t} (e : Expr base_type op t) diff --git a/src/Reflection/Z/Bounds/MapCastByDeBruijnWf.v b/src/Compilers/Z/Bounds/MapCastByDeBruijnWf.v index 57b45f68a..04d1f964e 100644 --- a/src/Reflection/Z/Bounds/MapCastByDeBruijnWf.v +++ b/src/Compilers/Z/Bounds/MapCastByDeBruijnWf.v @@ -1,13 +1,13 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.Z.MapCastByDeBruijnWf. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. -Require Import Crypto.Reflection.Z.Bounds.InterpretationLemmas. -Require Import Crypto.Reflection.Z.Bounds.MapCastByDeBruijn. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.Z.MapCastByDeBruijnWf. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Z.Bounds.InterpretationLemmas. +Require Import Crypto.Compilers.Z.Bounds.MapCastByDeBruijn. Definition Wf_MapCast {t} (e : Expr base_type op t) diff --git a/src/Reflection/Z/Bounds/Pipeline.v b/src/Compilers/Z/Bounds/Pipeline.v index 11bce1444..6c9cda840 100644 --- a/src/Reflection/Z/Bounds/Pipeline.v +++ b/src/Compilers/Z/Bounds/Pipeline.v @@ -1,6 +1,6 @@ (** * Reflective Pipeline *) -Require Import Crypto.Reflection.Z.Bounds.Pipeline.Glue. -Require Import Crypto.Reflection.Z.Bounds.Pipeline.ReflectiveTactics. +Require Import Crypto.Compilers.Z.Bounds.Pipeline.Glue. +Require Import Crypto.Compilers.Z.Bounds.Pipeline.ReflectiveTactics. (** This file combines the various PHOAS modules in tactics, culminating in a tactic [refine_reflectively], which solves a goal of the form << diff --git a/src/Reflection/Z/Bounds/Pipeline/Definition.v b/src/Compilers/Z/Bounds/Pipeline/Definition.v index 98d3078c3..ae3401b78 100644 --- a/src/Reflection/Z/Bounds/Pipeline/Definition.v +++ b/src/Compilers/Z/Bounds/Pipeline/Definition.v @@ -1,7 +1,7 @@ (** * Reflective Pipeline: Main Pipeline Definition *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Bounds.Pipeline.OutputType. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Bounds.Pipeline.OutputType. (** This file contains the definitions of the assembling of the various transformations that are used in the pipeline. There are two stages to the reflective pipeline, with different @@ -24,10 +24,10 @@ Require Import Crypto.Reflection.Z.Bounds.Pipeline.OutputType. (** ** Pre-Wf Stage *) (** *** Pre-Wf Pipeline Imports *) -Require Import Crypto.Reflection.Eta. -Require Import Crypto.Reflection.EtaInterp. -Require Import Crypto.Reflection.Z.ArithmeticSimplifier. -Require Import Crypto.Reflection.Z.ArithmeticSimplifierInterp. +Require Import Crypto.Compilers.Eta. +Require Import Crypto.Compilers.EtaInterp. +Require Import Crypto.Compilers.Z.ArithmeticSimplifier. +Require Import Crypto.Compilers.Z.ArithmeticSimplifierInterp. (** *** Definition of the Pre-Wf Pipeline *) (** Do not change the name or the type of this definition *) @@ -51,17 +51,17 @@ Qed. (** ** Post-Wf Stage *) (** *** Post-Wf Pipeline Imports *) -Require Import Crypto.Reflection.Z.Bounds.Interpretation. -Require Import Crypto.Reflection.EtaWf. -Require Import Crypto.Reflection.Z.Inline. -Require Import Crypto.Reflection.Z.InlineInterp. -Require Import Crypto.Reflection.Z.InlineWf. -Require Import Crypto.Reflection.Linearize. -Require Import Crypto.Reflection.LinearizeInterp. -Require Import Crypto.Reflection.LinearizeWf. -Require Import Crypto.Reflection.Z.Bounds.MapCastByDeBruijn. -Require Import Crypto.Reflection.Z.Bounds.MapCastByDeBruijnInterp. -Require Import Crypto.Reflection.Z.Bounds.MapCastByDeBruijnWf. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.EtaWf. +Require Import Crypto.Compilers.Z.Inline. +Require Import Crypto.Compilers.Z.InlineInterp. +Require Import Crypto.Compilers.Z.InlineWf. +Require Import Crypto.Compilers.Linearize. +Require Import Crypto.Compilers.LinearizeInterp. +Require Import Crypto.Compilers.LinearizeWf. +Require Import Crypto.Compilers.Z.Bounds.MapCastByDeBruijn. +Require Import Crypto.Compilers.Z.Bounds.MapCastByDeBruijnInterp. +Require Import Crypto.Compilers.Z.Bounds.MapCastByDeBruijnWf. Require Import Crypto.Util.Sigma.MapProjections. (** *** Definition of the Post-Wf Pipeline *) @@ -85,10 +85,10 @@ Definition PostWfPipeline (** *** Correctness proof of the Pre-Wf Pipeline *) (** Do not change the statement of this lemma. *) -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.Equality. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Z.Syntax.Util. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.Equality. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Z.Syntax.Util. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Option. Require Import Crypto.Util.Sigma. diff --git a/src/Reflection/Z/Bounds/Pipeline/Glue.v b/src/Compilers/Z/Bounds/Pipeline/Glue.v index 28a6584a8..675d1d358 100644 --- a/src/Reflection/Z/Bounds/Pipeline/Glue.v +++ b/src/Compilers/Z/Bounds/Pipeline/Glue.v @@ -1,12 +1,12 @@ (** * Reflective Pipeline: Glue Code *) (** This file defines the tactics that transform a non-reflective goal into a goal the that the reflective machinery can handle. *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Reify. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Z.Reify. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Reify. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Z.Reify. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. Require Import Crypto.Util.Tactics.Head. Require Import Crypto.Util.Curry. Require Import Crypto.Util.FixedWordSizes. @@ -20,7 +20,7 @@ Require Import Crypto.Util.Tactics.PrintContext. Require Import Crypto.Util.Tactics.MoveLetIn. Module Export Exports. - Export Crypto.Reflection.Z.Reify. (* export for the tactic redefinitions *) + Export Crypto.Compilers.Z.Reify. (* export for the tactic redefinitions *) End Exports. (** ** [reassoc_sig_and_eexists] *) diff --git a/src/Reflection/Z/Bounds/Pipeline/OutputType.v b/src/Compilers/Z/Bounds/Pipeline/OutputType.v index 301ee9e9c..8205ef70c 100644 --- a/src/Reflection/Z/Bounds/Pipeline/OutputType.v +++ b/src/Compilers/Z/Bounds/Pipeline/OutputType.v @@ -1,10 +1,10 @@ (** * Definition of the output type of the post-Wf pipeline *) (** Do not change these definitions unless you're hacking on the entire reflective pipeline tactic automation. *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. Require Import Crypto.Util.Sigma. Require Import Crypto.Util.Prod. Local Notation pick_typeb := Bounds.bounds_to_base_type (only parsing). diff --git a/src/Reflection/Z/Bounds/Pipeline/ReflectiveTactics.v b/src/Compilers/Z/Bounds/Pipeline/ReflectiveTactics.v index 82203739f..a04f3505c 100644 --- a/src/Reflection/Z/Bounds/Pipeline/ReflectiveTactics.v +++ b/src/Compilers/Z/Bounds/Pipeline/ReflectiveTactics.v @@ -10,19 +10,19 @@ reflective machinery itself, or if you find bugs or slowness. *) (** ** Preamble *) Require Import Coq.ZArith.ZArith. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfReflective. -Require Import Crypto.Reflection.RenameBinders. -Require Import Crypto.Reflection.Eta. -Require Import Crypto.Reflection.EtaInterp. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. -Require Import Crypto.Reflection.Z.Bounds.Relax. -Require Import Crypto.Reflection.Reify. -Require Import Crypto.Reflection.Z.Reify. -Require Import Crypto.Reflection.Z.Bounds.Pipeline.Definition. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfReflective. +Require Import Crypto.Compilers.RenameBinders. +Require Import Crypto.Compilers.Eta. +Require Import Crypto.Compilers.EtaInterp. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Z.Bounds.Relax. +Require Import Crypto.Compilers.Reify. +Require Import Crypto.Compilers.Z.Reify. +Require Import Crypto.Compilers.Z.Bounds.Pipeline.Definition. Require Import Crypto.Util.Tactics.Head. Require Import Crypto.Util.Tactics.SubstLet. Require Import Crypto.Util.Tactics.UnifyAbstractReflexivity. @@ -44,9 +44,9 @@ Require Import Bedrock.Word. v)] which has been transformed by the reflective pipeline. *) Module Export Exports. - Export Crypto.Reflection.Reify. (* export for the instances for recursing under binders *) - Export Crypto.Reflection.Z.Reify. (* export for the tactic redefinitions *) - Export Crypto.Reflection.Z.Bounds.Pipeline.Definition.Exports. + Export Crypto.Compilers.Reify. (* export for the instances for recursing under binders *) + Export Crypto.Compilers.Z.Reify. (* export for the tactic redefinitions *) + Export Crypto.Compilers.Z.Bounds.Pipeline.Definition.Exports. End Exports. (** ** Reification *) @@ -129,21 +129,21 @@ Ltac unify_abstract_cbv_interp_rhs_reflexivity := and add extra equality hypotheses to minimize the work we have to do in Ltac. *) (** *** Gallina assembly imports *) -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.WfReflectiveGen. -Require Import Crypto.Reflection.WfReflective. -Require Import Crypto.Reflection.Eta. -Require Import Crypto.Reflection.EtaWf. -Require Import Crypto.Reflection.EtaInterp. -Require Import Crypto.Reflection.Z.Bounds.Pipeline.OutputType. -Require Import Crypto.Reflection.Z.Bounds.Pipeline.Definition. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Equality. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. -Require Import Crypto.Reflection.Z.Bounds.Relax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.WfReflectiveGen. +Require Import Crypto.Compilers.WfReflective. +Require Import Crypto.Compilers.Eta. +Require Import Crypto.Compilers.EtaWf. +Require Import Crypto.Compilers.EtaInterp. +Require Import Crypto.Compilers.Z.Bounds.Pipeline.OutputType. +Require Import Crypto.Compilers.Z.Bounds.Pipeline.Definition. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Equality. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Z.Bounds.Relax. Require Import Crypto.Util.PartiallyReifiedProp. Require Import Crypto.Util.Equality. diff --git a/src/Reflection/Z/Bounds/Relax.v b/src/Compilers/Z/Bounds/Relax.v index e77ef423a..40b678071 100644 --- a/src/Reflection/Z/Bounds/Relax.v +++ b/src/Compilers/Z/Bounds/Relax.v @@ -1,13 +1,13 @@ Require Import Coq.ZArith.ZArith. Require Import Coq.Classes.Morphisms. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Equality. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.Z.Bounds.Interpretation. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Equality. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.Z.Bounds.Interpretation. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.SpecializeBy. Require Import Crypto.Util.Tactics.BreakMatch. diff --git a/src/Reflection/Z/CNotations.v b/src/Compilers/Z/CNotations.v index 77220a7bf..8ec885db3 100644 --- a/src/Reflection/Z/CNotations.v +++ b/src/Compilers/Z/CNotations.v @@ -1,6 +1,6 @@ -Require Export Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.Syntax. -Require Export Crypto.Reflection.Z.HexNotationConstants. +Require Export Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.Syntax. +Require Export Crypto.Compilers.Z.HexNotationConstants. Require Export Crypto.Util.Notations. Reserved Notation "T x = A ; b" (at level 200, b at level 200, format "T x = A ; '//' b"). diff --git a/src/Reflection/Z/FoldTypes.v b/src/Compilers/Z/FoldTypes.v index 776f000f5..fc6aa9406 100644 --- a/src/Reflection/Z/FoldTypes.v +++ b/src/Compilers/Z/FoldTypes.v @@ -1,7 +1,7 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.FoldTypes. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.FoldTypes. Section min_or_max. Context (f : base_type -> base_type -> base_type) diff --git a/src/Reflection/Z/HexNotationConstants.v b/src/Compilers/Z/HexNotationConstants.v index cd6474f89..1fa48ad6a 100644 --- a/src/Reflection/Z/HexNotationConstants.v +++ b/src/Compilers/Z/HexNotationConstants.v @@ -1,6 +1,6 @@ Require Import Coq.ZArith.ZArith. -Require Export Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.Syntax. +Require Export Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.Syntax. Require Export Bedrock.Word. Require Export Crypto.Util.Notations. diff --git a/src/Compilers/Z/Inline.v b/src/Compilers/Z/Inline.v new file mode 100644 index 000000000..8a8bea98b --- /dev/null +++ b/src/Compilers/Z/Inline.v @@ -0,0 +1,7 @@ +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Inline. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Util. + +Definition InlineConst {t} (e : Expr base_type op t) : Expr base_type op t + := @InlineConst base_type op (is_const) t e. diff --git a/src/Reflection/Z/InlineInterp.v b/src/Compilers/Z/InlineInterp.v index e3fc9b45d..c02197331 100644 --- a/src/Reflection/Z/InlineInterp.v +++ b/src/Compilers/Z/InlineInterp.v @@ -1,8 +1,8 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.InlineInterp. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Inline. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.InlineInterp. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Inline. Definition InterpInlineConst {interp_base_type interp_op} {t} (e : Expr base_type op t) (Hwf : Wf e) : forall x, Interp interp_op (InlineConst e) x = Interp interp_op e x diff --git a/src/Compilers/Z/InlineWf.v b/src/Compilers/Z/InlineWf.v new file mode 100644 index 000000000..32b84aa1f --- /dev/null +++ b/src/Compilers/Z/InlineWf.v @@ -0,0 +1,11 @@ +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.InlineWf. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Inline. + +Definition Wf_InlineConst {t} (e : Expr base_type op t) (Hwf : Wf e) + : Wf (InlineConst e) + := @Wf_InlineConst _ _ _ t e Hwf. + +Hint Resolve Wf_InlineConst : wf. diff --git a/src/Reflection/Z/JavaNotations.v b/src/Compilers/Z/JavaNotations.v index 0a28387df..bab120b0a 100644 --- a/src/Reflection/Z/JavaNotations.v +++ b/src/Compilers/Z/JavaNotations.v @@ -1,6 +1,6 @@ -Require Export Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Z.Syntax. -Require Export Crypto.Reflection.Z.HexNotationConstants. +Require Export Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Z.Syntax. +Require Export Crypto.Compilers.Z.HexNotationConstants. Require Export Crypto.Util.Notations. Reserved Notation "T x = A ; b" (at level 200, b at level 200, format "T x = A ; '//' b"). diff --git a/src/Reflection/Z/MapCastByDeBruijn.v b/src/Compilers/Z/MapCastByDeBruijn.v index 4ccfe6d2d..1985653d4 100644 --- a/src/Reflection/Z/MapCastByDeBruijn.v +++ b/src/Compilers/Z/MapCastByDeBruijn.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.MapCastByDeBruijn. -Require Import Crypto.Reflection.Z.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.MapCastByDeBruijn. +Require Import Crypto.Compilers.Z.Syntax. Section language. Context {interp_base_type_bounds : base_type -> Type} diff --git a/src/Reflection/Z/MapCastByDeBruijnInterp.v b/src/Compilers/Z/MapCastByDeBruijnInterp.v index 6e57136ab..cd145c6fa 100644 --- a/src/Reflection/Z/MapCastByDeBruijnInterp.v +++ b/src/Compilers/Z/MapCastByDeBruijnInterp.v @@ -1,10 +1,10 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.MapCastByDeBruijnInterp. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.MapCastByDeBruijn. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.MapCastByDeBruijnInterp. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.MapCastByDeBruijn. Section language. Context {interp_base_type_bounds : base_type -> Type} diff --git a/src/Reflection/Z/MapCastByDeBruijnWf.v b/src/Compilers/Z/MapCastByDeBruijnWf.v index 1173d8186..cce16e5fe 100644 --- a/src/Reflection/Z/MapCastByDeBruijnWf.v +++ b/src/Compilers/Z/MapCastByDeBruijnWf.v @@ -1,10 +1,10 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Relations. -Require Import Crypto.Reflection.MapCastByDeBruijnWf. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.MapCastByDeBruijn. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Relations. +Require Import Crypto.Compilers.MapCastByDeBruijnWf. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.MapCastByDeBruijn. Section language. Context {interp_base_type_bounds : base_type -> Type} diff --git a/src/Reflection/Z/OpInversion.v b/src/Compilers/Z/OpInversion.v index 6b2cdd85b..58b00c538 100644 --- a/src/Reflection/Z/OpInversion.v +++ b/src/Compilers/Z/OpInversion.v @@ -1,6 +1,6 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.Z.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.Z.Syntax. Ltac invert_one_op e := preinvert_one_type e; diff --git a/src/Compilers/Z/Reify.v b/src/Compilers/Z/Reify.v new file mode 100644 index 000000000..44ac44a03 --- /dev/null +++ b/src/Compilers/Z/Reify.v @@ -0,0 +1,50 @@ +Require Import Coq.ZArith.ZArith. +Require Import Crypto.Compilers.InputSyntax. +Require Import Crypto.Compilers.Z.Syntax. +Require Import Crypto.Compilers.Z.Syntax.Equality. +Require Import Crypto.Compilers.Z.Syntax.Util. +Require Import Crypto.Compilers.WfReflective. +Require Import Crypto.Compilers.Reify. +Require Import Crypto.Compilers.Inline. +Require Import Crypto.Compilers.InlineInterp. +Require Import Crypto.Compilers.Linearize. +Require Import Crypto.Compilers.LinearizeInterp. +Require Import Crypto.Compilers.Eta. +Require Import Crypto.Compilers.EtaInterp. + +Ltac base_reify_op op op_head extra ::= + lazymatch op_head with + | @Z.add => constr:(reify_op op op_head 2 (Add TZ TZ TZ)) + | @Z.mul => constr:(reify_op op op_head 2 (Mul TZ TZ TZ)) + | @Z.sub => constr:(reify_op op op_head 2 (Sub TZ TZ TZ)) + | @Z.shiftl => constr:(reify_op op op_head 2 (Shl TZ TZ TZ)) + | @Z.shiftr => constr:(reify_op op op_head 2 (Shr TZ TZ TZ)) + | @Z.land => constr:(reify_op op op_head 2 (Land TZ TZ TZ)) + | @Z.lor => constr:(reify_op op op_head 2 (Lor TZ TZ TZ)) + | @Z.opp => constr:(reify_op op op_head 1 (Opp TZ TZ)) + end. +Ltac base_reify_type T ::= + lazymatch T with + | Z => TZ + end. +Ltac Reify' e := Compilers.Reify.Reify' base_type interp_base_type op e. +Ltac Reify e := + let v := Compilers.Reify.Reify base_type interp_base_type op make_const e in + constr:(ExprEta v). +Ltac prove_ExprEta_Compile_correct := + fun _ + => intros; + rewrite ?InterpExprEta; + prove_compile_correct_using ltac:(fun _ => apply make_const_correct) (). + +Ltac Reify_rhs := + Compilers.Reify.Reify_rhs_gen Reify prove_ExprEta_Compile_correct interp_op ltac:(fun tac => tac ()). + +Ltac prereify_context_variables := + Compilers.Reify.prereify_context_variables interp_base_type. +Ltac reify_context_variable := + Compilers.Reify.reify_context_variable base_type interp_base_type op. +Ltac lazy_reify_context_variable := + Compilers.Reify.lazy_reify_context_variable base_type interp_base_type op. +Ltac reify_context_variables := + Compilers.Reify.reify_context_variables base_type interp_base_type op. diff --git a/src/Reflection/Z/Syntax.v b/src/Compilers/Z/Syntax.v index 58c7de6e6..754b3fb5a 100644 --- a/src/Reflection/Z/Syntax.v +++ b/src/Compilers/Z/Syntax.v @@ -1,10 +1,9 @@ (** * PHOAS Syntax for expression trees on ℤ *) Require Import Coq.ZArith.ZArith. Require Import Bedrock.Word. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListZOperations. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeUtil. Require Import Crypto.Util.FixedWordSizes. Require Import Crypto.Util.Option. Require Import Crypto.Util.NatUtil. (* for nat_beq for equality schemes *) @@ -27,9 +26,7 @@ Inductive op : flat_type base_type -> flat_type base_type -> Type := | Land T1 T2 Tout : op (Tbase T1 * Tbase T2) (Tbase Tout) | Lor T1 T2 Tout : op (Tbase T1 * Tbase T2) (Tbase Tout) | Opp T Tout : op (Tbase T) (Tbase Tout) -| Neg T Tout (int_width : Z) : op (Tbase T) (Tbase Tout) -| Cmovne T1 T2 T3 T4 Tout : op (Tbase T1 * Tbase T2 * Tbase T3 * Tbase T4) (Tbase Tout) -| Cmovle T1 T2 T3 T4 Tout : op (Tbase T1 * Tbase T2 * Tbase T3 * Tbase T4) (Tbase Tout). +. Definition interp_base_type (v : base_type) : Type := match v with @@ -81,9 +78,6 @@ Definition Zinterp_op src dst (f : op src dst) | Land _ _ _ => fun xy => Z.land (fst xy) (snd xy) | Lor _ _ _ => fun xy => Z.lor (fst xy) (snd xy) | Opp _ _ => fun x => Z.opp x - | Neg _ _ int_width => fun x => ModularBaseSystemListZOperations.neg int_width x - | Cmovne _ _ _ _ _ => fun xyzw => let '(x, y, z, w) := eta4 xyzw in cmovne x y z w - | Cmovle _ _ _ _ _ => fun xyzw => let '(x, y, z, w) := eta4 xyzw in cmovl x y z w end%Z. Definition interp_op src dst (f : op src dst) : interp_flat_type interp_base_type src -> interp_flat_type interp_base_type dst diff --git a/src/Reflection/Z/Syntax/Equality.v b/src/Compilers/Z/Syntax/Equality.v index 2862859b7..10cd287be 100644 --- a/src/Reflection/Z/Syntax/Equality.v +++ b/src/Compilers/Z/Syntax/Equality.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.Equality. -Require Import Crypto.Reflection.Z.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.Equality. +Require Import Crypto.Compilers.Z.Syntax. Require Import Crypto.Util.Decidable. Require Import Crypto.Util.PartiallyReifiedProp. Require Import Crypto.Util.HProp. @@ -41,11 +41,6 @@ Definition op_beq_hetero {t1 tR t1' tR'} (f : op t1 tR) (g : op t1' tR') : bool => base_type_beq T1 T1' && base_type_beq T2 T2' && base_type_beq Tout Tout' | Opp Tin Tout, Opp Tin' Tout' => base_type_beq Tin Tin' && base_type_beq Tout Tout' - | Cmovne T1 T2 T3 T4 Tout, Cmovne T1' T2' T3' T4' Tout' - | Cmovle T1 T2 T3 T4 Tout, Cmovle T1' T2' T3' T4' Tout' - => base_type_beq T1 T1' && base_type_beq T2 T2' && base_type_beq T3 T3' && base_type_beq T4 T4' && base_type_beq Tout Tout' - | Neg Tin Tout n, Neg Tin' Tout' m - => base_type_beq Tin Tin' && base_type_beq Tout Tout' && Z.eqb n m | OpConst _ _, _ | Add _ _ _, _ | Sub _ _ _, _ @@ -55,9 +50,6 @@ Definition op_beq_hetero {t1 tR t1' tR'} (f : op t1 tR) (g : op t1' tR') : bool | Land _ _ _, _ | Lor _ _ _, _ | Opp _ _, _ - | Neg _ _ _, _ - | Cmovne _ _ _ _ _, _ - | Cmovle _ _ _ _ _, _ => false end%bool. diff --git a/src/Reflection/Z/Syntax/Util.v b/src/Compilers/Z/Syntax/Util.v index 72b08d6cf..6cf54a99c 100644 --- a/src/Reflection/Z/Syntax/Util.v +++ b/src/Compilers/Z/Syntax/Util.v @@ -1,9 +1,9 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.SmartMap. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.TypeUtil. -Require Import Crypto.Reflection.TypeInversion. -Require Import Crypto.Reflection.Z.Syntax. +Require Import Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.SmartMap. +Require Import Crypto.Compilers.Wf. +Require Import Crypto.Compilers.TypeUtil. +Require Import Crypto.Compilers.TypeInversion. +Require Import Crypto.Compilers.Z.Syntax. Require Import Crypto.Util.FixedWordSizesEquality. Require Import Crypto.Util.NatUtil. Require Import Crypto.Util.HProp. @@ -59,9 +59,6 @@ Definition genericize_op {var' src dst} (opc : op src dst) {f} | Land _ _ _ => fun _ _ => Land _ _ _ | Lor _ _ _ => fun _ _ => Lor _ _ _ | Opp _ _ => fun _ _ => Opp _ _ - | Neg _ _ int_width => fun _ _ => Neg _ _ int_width - | Cmovne _ _ _ _ _ => fun _ _ => Cmovne _ _ _ _ _ - | Cmovle _ _ _ _ _ => fun _ _ => Cmovle _ _ _ _ _ end. Lemma cast_const_id {t} v diff --git a/src/CompleteEdwardsCurve/CompleteEdwardsCurveTheorems.v b/src/Curves/Edwards/AffineProofs.v index aba07fb46..2d1db7126 100644 --- a/src/CompleteEdwardsCurve/CompleteEdwardsCurveTheorems.v +++ b/src/Curves/Edwards/AffineProofs.v @@ -1,9 +1,7 @@ Require Export Crypto.Spec.CompleteEdwardsCurve. -Require Import Crypto.Algebra Crypto.Algebra Crypto.Util.Decidable. -Require Import Crypto.CompleteEdwardsCurve.Pre. +Require Import Crypto.Algebra.Hierarchy Crypto.Util.Decidable. Require Import Coq.Logic.Eqdep_dec. -Require Import Crypto.Tactics.VerdiTactics. Require Import Coq.Classes.Morphisms. Require Import Coq.Relations.Relation_Definitions. Require Import Crypto.Util.Tuple Crypto.Util.Notations. @@ -225,7 +223,7 @@ Module E. {nonsquare_d : forall x, not (Feq (Fmul x x) Fd)}. Context {K Keq Kzero Kone Kopp Kadd Ksub Kmul Kinv Kdiv} - {fieldK: @Algebra.field K Keq Kzero Kone Kopp Kadd Ksub Kmul Kinv Kdiv} + {fieldK: @Algebra.Hierarchy.field K Keq Kzero Kone Kopp Kadd Ksub Kmul Kinv Kdiv} {Keq_dec:DecidableRel Keq}. Context {FtoK:F->K} {HFtoK:@Ring.is_homomorphism F Feq Fone Fadd Fmul K Keq Kone Kadd Kmul FtoK}. diff --git a/src/CompleteEdwardsCurve/EdwardsMontgomery.v b/src/Curves/Edwards/Montgomery.v index f5a30ff88..d274356c9 100644 --- a/src/CompleteEdwardsCurve/EdwardsMontgomery.v +++ b/src/Curves/Edwards/Montgomery.v @@ -1,16 +1,16 @@ -Require Import Crypto.CompleteEdwardsCurve.CompleteEdwardsCurveTheorems. -Require Import Crypto.Spec.MontgomeryCurve Crypto.MontgomeryCurveTheorems. -Require Import Crypto.MontgomeryCurve. +Require Import Crypto.Curves.Edwards.AffineProofs. +Require Import Crypto.Spec.MontgomeryCurve Crypto.Curves.Montgomery.AffineProofs. +Require Import Crypto.Curves.Montgomery.Affine. Require Import Crypto.Util.Notations Crypto.Util.Decidable. Require Import (*Crypto.Util.Tactics*) Crypto.Util.Sum Crypto.Util.Prod. -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Algebra.Field. Import BinNums. Module E. Section EdwardsMontgomery. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {char_ge_28 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 28} {Feq_dec:DecidableRel Feq}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. @@ -20,9 +20,9 @@ Module E. Local Notation "x ^ 2" := (x*x). Let char_ge_12 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 12. - Proof. eapply char_ge_weaken; eauto. vm_decide. Qed. + Proof. eapply Algebra.Hierarchy.char_ge_weaken; eauto. vm_decide. Qed. Let char_ge_3 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 3. - Proof. eapply char_ge_weaken; eauto. vm_decide. Qed. + Proof. eapply Algebra.Hierarchy.char_ge_weaken; eauto. vm_decide. Qed. Context {a d: F} {nonzero_a : a <> 0} diff --git a/src/CompleteEdwardsCurve/Pre.v b/src/Curves/Edwards/Pre.v index 4dfd01cfd..244acc9b5 100644 --- a/src/CompleteEdwardsCurve/Pre.v +++ b/src/Curves/Edwards/Pre.v @@ -1,11 +1,11 @@ Require Import Coq.Classes.Morphisms. Require Coq.Setoids.Setoid Crypto.Util.Relations. -Require Import Crypto.Algebra Crypto.Algebra.Ring Crypto.Algebra.Field. +Require Import Crypto.Algebra.Hierarchy Crypto.Algebra.Ring Crypto.Algebra.Field. Require Import Crypto.Util.Notations Crypto.Util.Decidable (*Crypto.Util.Tactics*). Require Import Coq.PArith.BinPos. Section Edwards. Context {F eq zero one opp add sub mul inv div} - {field:@Algebra.field F eq zero one opp add sub mul inv div} + {field:@Algebra.Hierarchy.field F eq zero one opp add sub mul inv div} {eq_dec:DecidableRel eq}. Local Infix "=" := eq. Local Notation "a <> b" := (not (a = b)). diff --git a/src/CompleteEdwardsCurve/ExtendedCoordinates.v b/src/Curves/Edwards/XYZT.v index f05a1d997..160866b64 100644 --- a/src/CompleteEdwardsCurve/ExtendedCoordinates.v +++ b/src/Curves/Edwards/XYZT.v @@ -1,17 +1,17 @@ Require Import Coq.Classes.Morphisms. -Require Import Crypto.Spec.CompleteEdwardsCurve Crypto.CompleteEdwardsCurve.CompleteEdwardsCurveTheorems. +Require Import Crypto.Spec.CompleteEdwardsCurve Crypto.Curves.Edwards.AffineProofs. -Require Import Crypto.Algebra Crypto.Algebra. Require Import Crypto.Util.Notations Crypto.Util.GlobalSettings. Require Export Crypto.Util.FixCoqMistakes. +Require Import Crypto.Util.Decidable. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.UniquePose. Module Extended. Section ExtendedCoordinates. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {char_ge_3 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos BinNat.N.two)} {Feq_dec:DecidableRel Feq}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. @@ -107,11 +107,11 @@ Module Extended. end. Next Obligation. pose proof (E.denominator_nonzero _ nonzero_a square_a _ nonsquare_d _ _ (proj2_sig (to_twisted P1)) _ _ (proj2_sig (to_twisted P2))); t. Qed. - Program Definition _group_proof nonzero_a' square_a' nonsquare_d' : group /\ _ /\ _ := + Program Definition _group_proof nonzero_a' square_a' nonsquare_d' : Algebra.Hierarchy.group /\ _ /\ _ := @Group.group_from_redundant_representation _ _ _ _ _ ((E.edwards_curve_abelian_group(a:=a)(d:=d)(nonzero_a:=nonzero_a')(square_a:=square_a') - (nonsquare_d:=nonsquare_d')).(abelian_group_group)) + (nonsquare_d:=nonsquare_d')).(Algebra.Hierarchy.abelian_group_group)) _ eq m1add @@ -130,7 +130,7 @@ Module Extended. Next Obligation. cbv [to_twisted opp]. t. Qed. Next Obligation. cbv [to_twisted zero]. t. Qed. Global Instance group x y z - : group := proj1 (_group_proof x y z). + : Algebra.Hierarchy.group := proj1 (_group_proof x y z). Global Instance homomorphism_from_twisted x y z : Monoid.is_homomorphism := proj1 (proj2 (_group_proof x y z)). Global Instance homomorphism_to_twisted x y z : diff --git a/src/MontgomeryCurve.v b/src/Curves/Montgomery/Affine.v index a04701ed5..721908a6a 100644 --- a/src/MontgomeryCurve.v +++ b/src/Curves/Montgomery/Affine.v @@ -1,4 +1,4 @@ -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Algebra.Field. Require Import Crypto.Util.GlobalSettings. Require Import Crypto.Util.Sum Crypto.Util.Prod. Require Import Crypto.Util.Tactics.BreakMatch. @@ -8,7 +8,7 @@ Module M. Section MontgomeryCurve. Import BinNat. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. diff --git a/src/MontgomeryCurveTheorems.v b/src/Curves/Montgomery/AffineProofs.v index 7f7ad5bdf..a83109a55 100644 --- a/src/MontgomeryCurveTheorems.v +++ b/src/Curves/Montgomery/AffineProofs.v @@ -1,22 +1,23 @@ -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Algebra.Field. Require Import Crypto.Util.GlobalSettings. Require Import Crypto.Util.Sum Crypto.Util.Prod. Require Import Crypto.Util.Tactics.BreakMatch. -Require Import Crypto.Spec.MontgomeryCurve Crypto.MontgomeryCurve. -Require Import Crypto.Spec.WeierstrassCurve Crypto.WeierstrassCurve.Definitions. -Require Import Crypto.WeierstrassCurve.WeierstrassCurveTheorems. +Require Import Crypto.Util.Decidable. +Require Import Crypto.Spec.MontgomeryCurve Crypto.Curves.Montgomery.Affine. +Require Import Crypto.Spec.WeierstrassCurve Crypto.Curves.Weierstrass.Affine. +Require Import Crypto.Curves.Weierstrass.AffineProofs. Module M. Section MontgomeryCurve. Import BinNat. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_28:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 28}. Let char_ge_12 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 12. - Proof. eapply char_ge_weaken; eauto. vm_decide. Qed. + Proof. eapply Algebra.Hierarchy.char_ge_weaken; eauto. vm_decide. Qed. Let char_ge_3 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 3. - Proof. eapply char_ge_weaken; eauto; vm_decide. Qed. + Proof. eapply Algebra.Hierarchy.char_ge_weaken; eauto; vm_decide. Qed. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. Local Infix "+" := Fadd. Local Infix "*" := Fmul. @@ -63,7 +64,7 @@ Module M. Program Definition _MW (discr_nonzero:id _) : _ /\ _ /\ _ := @Group.group_from_redundant_representation Wpoint W.eq Wadd W.zero Wopp - (abelian_group_group (W.commutative_group(char_ge_12:=char_ge_12)(discriminant_nonzero:=discr_nonzero))) + (Algebra.Hierarchy.abelian_group_group (W.commutative_group(char_ge_12:=char_ge_12)(discriminant_nonzero:=discr_nonzero))) (@M.point F Feq Fadd Fmul a b) M.eq (M.add(char_ge_3:=char_ge_3)(b_nonzero:=b_nonzero)) M.zero (M.opp(b_nonzero:=b_nonzero)) (M.of_Weierstrass(b_nonzero:=b_nonzero)) (M.to_Weierstrass(b_nonzero:=b_nonzero)) @@ -75,7 +76,7 @@ Module M. Next Obligation. Proof. t; fsatz. Qed. Next Obligation. Proof. t; fsatz. Qed. - Global Instance group discr_nonzero : Algebra.group := proj1 (_MW discr_nonzero). + Global Instance group discr_nonzero : Algebra.Hierarchy.group := proj1 (_MW discr_nonzero). Global Instance homomorphism_of_Weierstrass discr_nonzero : Monoid.is_homomorphism(phi:=M.of_Weierstrass) := proj1 (proj2 (_MW discr_nonzero)). Global Instance homomorphism_to_Weierstrass discr_nonzero : Monoid.is_homomorphism(phi:=M.to_Weierstrass) := proj2 (proj2 (_MW discr_nonzero)). End MontgomeryCurve. diff --git a/src/MontgomeryX.v b/src/Curves/Montgomery/XZ.v index 6cb5b2387..60020827c 100644 --- a/src/MontgomeryX.v +++ b/src/Curves/Montgomery/XZ.v @@ -1,13 +1,14 @@ -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Algebra.Field. Require Import Crypto.Util.GlobalSettings Crypto.Util.Notations. Require Import Crypto.Util.Sum Crypto.Util.Prod Crypto.Util.LetIn. -Require Import Crypto.Spec.MontgomeryCurve Crypto.MontgomeryCurve. +Require Import Crypto.Util.Decidable. +Require Import Crypto.Spec.MontgomeryCurve Crypto.Curves.Montgomery.Affine. Module M. Section MontgomeryCurve. Import BinNat. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_5:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 5}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. @@ -30,7 +31,7 @@ Module M. end. Let char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two)). - Proof. eapply char_ge_weaken; eauto; vm_decide. Qed. + Proof. eapply Algebra.Hierarchy.char_ge_weaken; eauto; vm_decide. Qed. (* From Curve25519 paper by djb, appendix B. Credited to Montgomery *) Context {a24:F} {a24_correct:(1+1+1+1)*a24 = a-(1+1)}. diff --git a/src/MontgomeryXProofs.v b/src/Curves/Montgomery/XZProofs.v index f3f0346c9..d24d1398c 100644 --- a/src/MontgomeryXProofs.v +++ b/src/Curves/Montgomery/XZProofs.v @@ -1,12 +1,13 @@ -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Algebra.Field. Require Import Crypto.Util.Sum Crypto.Util.Prod Crypto.Util.LetIn. -Require Import Crypto.Spec.MontgomeryCurve Crypto.MontgomeryCurve. -Require Import Crypto.MontgomeryX BinPos. +Require Import Crypto.Util.Decidable. +Require Import Crypto.Spec.MontgomeryCurve Crypto.Curves.Montgomery.Affine. +Require Import Crypto.Curves.Montgomery.XZ BinPos. Module M. Section MontgomeryCurve. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_5:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 5}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. @@ -17,7 +18,7 @@ Module M. Local Notation "( x , y )" := (inl (pair x y)). Let char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two)). - Proof. eapply char_ge_weaken; eauto; vm_decide. Qed. + Proof. eapply Algebra.Hierarchy.char_ge_weaken; eauto; vm_decide. Qed. Context {a b: F} {b_nonzero:b <> 0}. Context {a24:F} {a24_correct:(1+1+1+1)*a24 = a-(1+1)}. diff --git a/src/WeierstrassCurve/Definitions.v b/src/Curves/Weierstrass/Affine.v index fb400d8c8..90bb3bdbc 100644 --- a/src/WeierstrassCurve/Definitions.v +++ b/src/Curves/Weierstrass/Affine.v @@ -1,11 +1,11 @@ Require Import Crypto.Spec.WeierstrassCurve. -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Algebra.Field. Require Import Crypto.Util.Decidable Crypto.Util.Tactics.DestructHead Crypto.Util.Tactics.BreakMatch. Module W. Section W. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {a b:F} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:DecidableRel Feq}. Program Definition opp (P:@W.point F Feq Fadd Fmul a b) : @W.point F Feq Fadd Fmul a b diff --git a/src/WeierstrassCurve/WeierstrassCurveTheorems.v b/src/Curves/Weierstrass/AffineProofs.v index 7547eb147..81583d88f 100644 --- a/src/WeierstrassCurve/WeierstrassCurveTheorems.v +++ b/src/Curves/Weierstrass/AffineProofs.v @@ -1,18 +1,18 @@ Require Import Coq.Numbers.BinNums. Require Import Coq.Classes.Morphisms. -Require Import Crypto.Spec.WeierstrassCurve Crypto.WeierstrassCurve.Definitions. -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Spec.WeierstrassCurve Crypto.Curves.Weierstrass.Affine. +Require Import Crypto.Algebra.Field Crypto.Algebra.Hierarchy. Require Import Crypto.Util.Decidable Crypto.Util.Tactics.DestructHead Crypto.Util.Tactics.BreakMatch. Require Import Coq.PArith.BinPos. Module W. Section W. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {a b:F} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:DecidableRel Feq} {char_ge_12:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 12%positive}. (* FIXME: shouldn't need we need 4, not 12? *) Let char_ge_3 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul 3. - Proof. eapply char_ge_weaken; eauto; vm_decide. Qed. + Proof. eapply Algebra.Hierarchy.char_ge_weaken; eauto; vm_decide. Qed. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. Local Notation "0" := Fzero. Local Notation "1" := Fone. Local Infix "+" := Fadd. Local Infix "-" := Fsub. Local Infix "*" := Fmul. @@ -191,6 +191,6 @@ Module W. Time s. (* Finished transaction in 0.068 secs (0.066u,0.s) (successful) *) (* Total: 414.396 seconds, roughly 7 minutes*) - Time Qed. + Time Qed. (* Finished transaction in 390.998 secs (390.783u,0.276s) (successful) *) End W. End W. diff --git a/src/WeierstrassCurve/Pre.v b/src/Curves/Weierstrass/Pre.v index 3b12bcfe1..6647d8e76 100644 --- a/src/WeierstrassCurve/Pre.v +++ b/src/Curves/Weierstrass/Pre.v @@ -1,5 +1,5 @@ Require Import Coq.Classes.Morphisms. Require Coq.Setoids.Setoid. -Require Import Crypto.Algebra Crypto.Algebra.Field. +Require Import Crypto.Algebra.Field. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Notations. @@ -10,7 +10,7 @@ Local Open Scope core_scope. Section Pre. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))} {eq_dec: DecidableRel Feq}. Local Infix "=" := Feq. Local Notation "a <> b" := (not (a = b)). diff --git a/src/WeierstrassCurve/Projective.v b/src/Curves/Weierstrass/Projective.v index f07be0f36..20866ca5d 100644 --- a/src/WeierstrassCurve/Projective.v +++ b/src/Curves/Weierstrass/Projective.v @@ -10,7 +10,7 @@ Require Import Crypto.Util.Sum Crypto.Util.Prod Crypto.Util.Sigma. Module Projective. Section Projective. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {a b:F} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))} {Feq_dec:DecidableRel Feq}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. diff --git a/src/Encoding/EncodingTheorems.v b/src/Encoding/EncodingTheorems.v deleted file mode 100644 index c6f48a0ab..000000000 --- a/src/Encoding/EncodingTheorems.v +++ /dev/null @@ -1,14 +0,0 @@ -Require Import Crypto.Spec.Encoding. - -Section EncodingTheorems. - Context {A B : Type} {E : canonical encoding of A as B}. - - Lemma encoding_inj : forall x y, enc x = enc y -> x = y. - Proof. - intros. - assert (dec (enc x) = dec (enc y)) as dec_enc_eq by (f_equal; auto). - do 2 rewrite encoding_valid in dec_enc_eq. - inversion dec_enc_eq; auto. - Qed. - -End EncodingTheorems. diff --git a/src/Encoding/ModularWordEncodingPre.v b/src/Encoding/ModularWordEncodingPre.v deleted file mode 100644 index 874bfdc9d..000000000 --- a/src/Encoding/ModularWordEncodingPre.v +++ /dev/null @@ -1,45 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Bedrock.Word. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.ZUtil Crypto.Util.WordUtil. -Require Import Crypto.Spec.Encoding. - -Local Open Scope nat_scope. - -Section ModularWordEncodingPre. - Context {m : positive} {sz : nat} {m_pos : (0 < m)%Z} {bound_check : Z.to_nat m < 2 ^ sz}. - - Let Fm_enc (x : F m) : word sz := NToWord sz (Z.to_N (F.to_Z x)). - - Let Fm_dec (x_ : word sz) : option (F m) := - let z := Z.of_N (wordToN (x_)) in - if Z_lt_dec z m - then Some (F.of_Z m z) - else None - . - - Lemma Fm_encoding_valid : forall x, Fm_dec (Fm_enc x) = Some x. - Proof using bound_check m_pos. - unfold Fm_dec, Fm_enc; intros. - pose proof (F.to_Z_range x m_pos). - rewrite wordToN_NToWord_idempotent by (apply bound_check_nat_N; - assert (Z.to_nat (F.to_Z x) < Z.to_nat m) by (apply Z2Nat.inj_lt; omega); omega). - rewrite Z2N.id by omega. - rewrite F.of_Z_to_Z. - break_if; auto; omega. - Qed. - - Lemma Fm_encoding_canonical : forall w x, Fm_dec w = Some x -> Fm_enc x = w. - Proof using bound_check. - unfold Fm_dec, Fm_enc; intros ? ? dec_Some. - break_if; [ | congruence ]. - inversion dec_Some. - rewrite F.to_Z_of_Z. - rewrite Z.mod_small by (pose proof (N2Z.is_nonneg (wordToN w)); try omega). - rewrite N2Z.id. - apply NToWord_wordToN. - Qed. - -End ModularWordEncodingPre. diff --git a/src/Encoding/ModularWordEncodingTheorems.v b/src/Encoding/ModularWordEncodingTheorems.v deleted file mode 100644 index 81d4fc5d3..000000000 --- a/src/Encoding/ModularWordEncodingTheorems.v +++ /dev/null @@ -1,46 +0,0 @@ -Require Import Coq.ZArith.ZArith Coq.ZArith.Znumtheory. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Crypto.CompleteEdwardsCurve.CompleteEdwardsCurveTheorems. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems Crypto.ModularArithmetic.ModularArithmeticTheorems. -Require Import Bedrock.Word. -Require Import Crypto.Spec.Encoding. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.Tactics.SpecializeBy. -Require Import Crypto.Util.FixCoqMistakes. -Require Import Crypto.Spec.ModularWordEncoding. - - -Local Open Scope F_scope. - -Section SignBit. - Context {m : positive} {prime_m : prime m} {two_lt_m : (2 < m)%Z} {sz : nat} {bound_check : (Z.to_nat m < 2 ^ sz)%nat}. - - Lemma sign_bit_parity : forall x, @sign_bit m sz x = Z.odd (F.to_Z x). - Proof using Type*. - unfold sign_bit, Fm_enc; intros. - pose proof (shatter_word (NToWord sz (Z.to_N (F.to_Z x)))) as shatter. - case_eq sz; intros; subst; rewrite shatter. - + pose proof (prime_ge_2 m prime_m). - simpl in bound_check. - assert (m < 1)%Z by (apply Z2Nat.inj_lt; try omega; assumption). - omega. - + assert (0 < m)%Z as m_pos by (pose proof prime_ge_2 m prime_m; omega). - pose proof (F.to_Z_range x m_pos). - destruct (F.to_Z x); auto. - - destruct p; auto. - - pose proof (Pos2Z.neg_is_neg p); omega. - Qed. - - Lemma sign_bit_zero : @sign_bit m sz 0 = false. - Proof using Type*. - rewrite sign_bit_parity; auto. - Qed. - - Lemma sign_bit_opp (x : F m) (Hnz:x <> 0) : negb (@sign_bit m sz x) = @sign_bit m sz (F.opp x). - Proof using Type*. - pose proof F.to_Z_nonzero_range x Hnz; specialize_by omega. - rewrite !sign_bit_parity, F.to_Z_opp, Z_mod_nz_opp_full, Zmod_small, - Z.odd_sub, (NumTheoryUtil.p_odd m), (Bool.xorb_true_l (Z.odd (F.to_Z x))); - try eapply Zrel_prime_neq_mod_0, rel_prime_le_prime; intuition omega. - Qed. -End SignBit. diff --git a/src/Experiments/Ed25519_imports.hs b/src/Experiments/Ed25519_imports.hs deleted file mode 100644 index 726b4b268..000000000 --- a/src/Experiments/Ed25519_imports.hs +++ /dev/null @@ -1,5 +0,0 @@ -import qualified Data.List -import qualified Data.Bits -import qualified Data.Word (Word8, Word64) -import qualified Data.ByteString.Lazy as B -import qualified Data.Digest.Pure.SHA as SHA diff --git a/src/Experiments/ExtrHaskellNats.v b/src/Experiments/ExtrHaskellNats.v deleted file mode 100644 index 3e2974ea1..000000000 --- a/src/Experiments/ExtrHaskellNats.v +++ /dev/null @@ -1,111 +0,0 @@ -(** * Extraction Directives for [nat] in Haskell *) -(** [nat] is really complicated, so we jump through many hoops to get - code that compiles in 8.4 and 8.5 at the same time. *) -Require Coq.Numbers.Natural.Peano.NPeano. -Require Coq.Arith.Compare_dec Coq.Arith.EqNat Coq.Arith.Peano_dec. - -Extract Inductive nat => "Prelude.Integer" [ "0" "Prelude.succ" ] - "(\fO fS n -> {- match_on_nat -} if n Prelude.== 0 then fO () else fS (n Prelude.- 1))". - - -(** We rely on the fact that Coq forbids masking absolute names. Hopefully we can drop support for 8.4 before this is changed. *) -Module Coq. - Module M. Export NPeano.Nat. End M. - Module Init. - Module Nat. - Export M. - End Nat. - End Init. - Module Numbers. - Module Natural. - Module Peano. - Module NPeano. - Module Nat. - Export M. - End Nat. - End NPeano. - End Peano. - End Natural. - End Numbers. - Module Arith. - Module PeanoNat. - Module Nat. - Export M. - End Nat. - End PeanoNat. - End Arith. -End Coq. - -Module Export Import_NPeano_Nat. - Import Coq.Numbers.Natural.Peano.NPeano.Nat. - - Extract Inlined Constant add => "(Prelude.+)". - Extract Inlined Constant mul => "(Prelude.*)". - Extract Inlined Constant pow => "(Prelude.^)". - Extract Inlined Constant max => "Prelude.max". - Extract Inlined Constant min => "Prelude.min". - Extract Inlined Constant gcd => "Prelude.gcd". - Extract Inlined Constant lcm => "Prelude.lcm". - Extract Inlined Constant land => "(Data.Bits..&.)". - Extract Inlined Constant compare => "Prelude.compare". - Extract Inlined Constant ltb => "(Prelude.<)". - Extract Inlined Constant leb => "(Prelude.<=)". - Extract Inlined Constant eqb => "(Prelude.==)". - Extract Inlined Constant eq_dec => "(Prelude.==)". - Extract Inlined Constant odd => "Prelude.odd". - Extract Inlined Constant even => "Prelude.even". - Extract Constant pred => "(\n -> Prelude.max 0 (Prelude.pred n))". - Extract Constant sub => "(\n m -> Prelude.max 0 (n Prelude.- m))". - Extract Constant div => "(\n m -> if m Prelude.== 0 then 0 else Prelude.div n m)". - Extract Constant modulo => "(\n m -> if m Prelude.== 0 then 0 else Prelude.mod n m)". - - (* XXX: unsound due to potential overflow in the second argument *) - Extract Constant shiftr => "(\w n -> Data.Bits.shiftR w (Prelude.fromIntegral n))". - Extract Constant shiftl => "(\w n -> Data.Bits.shiftL w (Prelude.fromIntegral n))". - Extract Constant testbit => "(\w n -> Data.Bits.testBit w (Prelude.fromIntegral n))". -End Import_NPeano_Nat. - - -Module Export Import_Init_Nat. - Import Coq.Init.Nat. - - Extract Inlined Constant add => "(Prelude.+)". - Extract Inlined Constant mul => "(Prelude.*)". - Extract Inlined Constant max => "Prelude.max". - Extract Inlined Constant min => "Prelude.min". - Extract Constant pred => "(\n -> Prelude.max 0 (Prelude.pred n))". - Extract Constant sub => "(\n m -> Prelude.max 0 (n Prelude.- m))". - - Extract Constant div => "(\n m -> if m Prelude.== 0 then 0 else Prelude.div n m)". - Extract Constant modulo => "(\n m -> if m Prelude.== 0 then 0 else Prelude.mod n m)". - - (* XXX: unsound due to potential overflow in the second argument *) - Extract Constant shiftr => "(\w n -> Data.Bits.shiftR w (Prelude.fromIntegral n))". - Extract Constant shiftl => "(\w n -> Data.Bits.shiftL w (Prelude.fromIntegral n))". - Extract Constant testbit => "(\w n -> Data.Bits.testBit w (Prelude.fromIntegral n))". -End Import_Init_Nat. - - -Module Export Import_PeanoNat_Nat. - Import Coq.Arith.PeanoNat.Nat. - - Extract Inlined Constant eq_dec => "(Prelude.==)". - Extract Inlined Constant add => "(Prelude.+)". - Extract Inlined Constant mul => "(Prelude.*)". - Extract Inlined Constant max => "Prelude.max". - Extract Inlined Constant min => "Prelude.min". - Extract Inlined Constant compare => "Prelude.compare". - - (* XXX: unsound due to potential overflow in the second argument *) - Extract Constant shiftr => "(\w n -> Data.Bits.shiftR w (Prelude.fromIntegral n))". - Extract Constant shiftl => "(\w n -> Data.Bits.shiftL w (Prelude.fromIntegral n))". - Extract Constant testbit => "(\w n -> Data.Bits.testBit w (Prelude.fromIntegral n))". -End Import_PeanoNat_Nat. - -Extract Inlined Constant Compare_dec.nat_compare_alt => "Prelude.compare". -Extract Inlined Constant Compare_dec.lt_dec => "(Prelude.<)". -Extract Inlined Constant Compare_dec.leb => "(Prelude.<=)". -Extract Inlined Constant Compare_dec.le_lt_dec => "(Prelude.<=)". -Extract Inlined Constant EqNat.beq_nat => "(Prelude.==)". -Extract Inlined Constant EqNat.eq_nat_decide => "(Prelude.==)". -Extract Inlined Constant Peano_dec.eq_nat_dec => "(Prelude.==)". diff --git a/src/Experiments/GenericFieldPow.v b/src/Experiments/GenericFieldPow.v deleted file mode 100644 index 033ed9363..000000000 --- a/src/Experiments/GenericFieldPow.v +++ /dev/null @@ -1,350 +0,0 @@ -Require Import Coq.setoid_ring.Cring. -Require Import Coq.omega.Omega. -Require Export Crypto.Util.FixCoqMistakes. -Require Import Crypto.Util.Tactics.UniquePose. -(** TODO: Move some imports up here from below, if it doesn't break things *) -Require Coq.setoid_ring.Field_theory Coq.setoid_ring.Field_tac. -Require Coq.setoid_ring.Ring_theory Coq.setoid_ring.NArithRing. -Require Coq.nsatz.Nsatz. -Generalizable All Variables. - - -(*TODO: move *) -Lemma Z_pos_pred_0 p : Z.pos p - 1 = 0 -> p=1%positive. -Proof. destruct p; simpl in *; try discriminate; auto. Qed. - -Lemma Z_neg_succ_neg : forall a b, (Z.neg a + 1)%Z = Z.neg b -> a = Pos.succ b. -Admitted. - -Lemma Z_pos_pred_pos : forall a b, (Z.pos a - 1)%Z = Z.pos b -> a = Pos.succ b. -Admitted. - -Lemma Z_pred_neg p : (Z.neg p - 1)%Z = Z.neg (Pos.succ p). -Admitted. - -(* teach nsatz to deal with the definition of power we are use *) -Instance reify_pow_pos (R:Type) `{Ring R} -e1 lvar t1 n -`{Ring (T:=R)} -{_:reify e1 lvar t1} -: reify (PEpow e1 (N.pos n)) lvar (pow_pos t1 n)|1. - -Class Field_ops (F:Type) - `{Ring_ops F} - {inv:F->F} := {}. - -Class Division (A B C:Type) := division : A -> B -> C. - -Local Notation "_/_" := division. -Local Notation "n / d" := (division n d). - -Module F. - - Definition div `{Field_ops F} n d := n * (inv d). - Global Instance div_notation `{Field_ops F} : @Division F F F := div. - - Class Field {F inv} `{FieldCring:Cring (R:=F)} {Fo:Field_ops F (inv:=inv)} := - { - field_inv_comp : Proper (_==_ ==> _==_) inv; - field_inv_def : forall x, (x == 0 -> False) -> inv x * x == 1; - field_one_neq_zero : not (1 == 0) - }. - Global Existing Instance field_inv_comp. - - Definition powZ `{Field_ops F} (x:F) (n:Z) := - match n with - | Z0 => 1 - | Zpos p => pow_pos x p - | Zneg p => inv (pow_pos x p) - end. - Global Instance power_field `{Field_ops F} : Power | 5 := { power := powZ }. - - Section FieldProofs. - Context `{Field F}. - - Definition unfold_div (x y:F) : x/y = x * inv y := eq_refl. - - Global Instance Proper_div : - Proper (_==_ ==> _==_ ==> _==_) div. - Proof using Type*. - unfold div; repeat intro. - repeat match goal with - | [H: _ == _ |- _ ] => rewrite H; clear H - end; reflexivity. - Qed. - - Global Instance Proper_pow_pos : Proper (_==_==>eq==>_==_) pow_pos. - Proof using Rr. - cut (forall n (y x : F), x == y -> pow_pos x n == pow_pos y n); - [repeat intro; subst; eauto|]. - induction n; simpl; intros; trivial; - repeat eapply ring_mult_comp; eauto. - Qed. - - Global Instance Propper_powZ : Proper (_==_==>eq==>_==_) powZ. - Proof using Type*. - repeat intro; subst; unfold powZ. - match goal with |- context[match ?x with _ => _ end] => destruct x end; - repeat (eapply Proper_pow_pos || f_equiv; trivial). - Qed. - - Import Coq.setoid_ring.Field_theory Coq.setoid_ring.Field_tac. - Lemma field_theory_for_tactic : field_theory 0 1 _+_ _*_ _-_ -_ _/_ inv _==_. - Proof using Type*. - split; repeat constructor; repeat intro; gen_rewrite; try cring; - eauto using field_one_neq_zero, field_inv_def. Qed. - - Import Coq.setoid_ring.Ring_theory Coq.setoid_ring.NArithRing. - Lemma power_theory_for_tactic : power_theory 1 _*_ _==_ NtoZ power. - Proof using Rr. constructor; destruct n; reflexivity. Qed. - - Create HintDb field_nonzero discriminated. - Hint Resolve field_one_neq_zero : field_nonzero. - Ltac field_nonzero := repeat split; auto 3 with field_nonzero. - Ltac field_power_isconst t := Ncst t. - Add Field FieldProofsAddField : field_theory_for_tactic - (postprocess [field_nonzero], - power_tac power_theory_for_tactic [field_power_isconst]). - - Lemma div_mul_idemp_l : forall a b, (a==0 -> False) -> a*b/a == b. - Proof using Type*. intros. field. Qed. - - Context {eq_dec:forall x y : F, {x==y}+{x==y->False}}. - Lemma mul_zero_why : forall a b, a*b == 0 -> a == 0 \/ b == 0. - Proof using Type*. - - intros; destruct (eq_dec a 0); intuition. - assert (a * b / a == 0) by - (match goal with [H: _ == _ |- _ ] => rewrite H; field end). - rewrite div_mul_idemp_l in *; auto. - Qed. - - Import Coq.nsatz.Nsatz. - Global Instance Integral_domain_Field : Integral_domain (R:=F). - Proof using Type*. - constructor; intros; eauto using mul_zero_why, field_one_neq_zero. - Qed. - - Tactic Notation (at level 0) "field_simplify_eq" "in" hyp(H) := - let t := type of H in - generalize H; - field_lookup (PackField FIELD_SIMPL_EQ) [] t; - try (exact I); - try (idtac; []; clear H;intro H). - - Inductive field_simplify_done {x y:F} : (x==y) -> Type := - Field_simplify_done : forall (H:x==y), field_simplify_done H. - Ltac field_nsatz := - repeat match goal with - [ H: _ == _ |- _ ] => - match goal with - | [ Ha : field_simplify_done H |- _ ] => fail - | _ => idtac - end; - field_simplify_eq in H; - unique pose proof (Field_simplify_done H) - end; - repeat match goal with [ H: field_simplify_done _ |- _] => clear H end; - try field_simplify_eq; - try nsatz. - - Create HintDb field discriminated. - Hint Extern 5 (_ == _) => field_nsatz : field. - Hint Extern 5 (_ <-> _) => split. - - Lemma mul_inv_l : forall x, not (x == 0) -> inv x * x == 1. Proof using Type*. auto with field. Qed. - - Lemma mul_inv_r : forall x, not (x == 0) -> x * inv x == 1. Proof using Type*. auto with field. Qed. - - Lemma mul_cancel_r' (x y z:F) : not (z == 0) -> x * z == y * z -> x == y. - Proof using Type*. - intros. - assert (x * z * inv z == y * z * inv z) by - (match goal with [H: _ == _ |- _ ] => rewrite H; auto with field end). - assert (x * z * inv z == x * (z * inv z)) by auto with field. - assert (y * z * inv z == y * (z * inv z)) by auto with field. - rewrite mul_inv_r, @ring_mul_1_r in *; auto with field. - Qed. - - Lemma mul_cancel_r (x y z:F) : not (z == 0) -> (x * z == y * z <-> x == y). - Proof using Type*. intros;split;intros Heq; try eapply mul_cancel_r' in Heq; eauto with field. Qed. - - Lemma mul_cancel_l (x y z:F) : not (z == 0) -> (z * x == z * y <-> x == y). - Proof using Type*. intros;split;intros; try eapply mul_cancel_r; eauto with field. Qed. - - Lemma mul_cancel_r_eq : forall x z:F, not(z==0) -> (x*z == z <-> x == 1). - Proof using Type*. - intros;split;intros Heq; [|nsatz]. - pose proof ring_mul_1_l z as Hz; rewrite <- Hz in Heq at 2; rewrite mul_cancel_r in Heq; eauto. - Qed. - - Lemma mul_cancel_l_eq : forall x z:F, not(z==0) -> (z*x == z <-> x == 1). - Proof using Type*. intros;split;intros Heq; try eapply mul_cancel_r_eq; eauto with field. Qed. - - Lemma inv_unique (a:F) : forall x y, x * a == 1 -> y * a == 1 -> x == y. Proof using Type*. auto with field. Qed. - - Lemma mul_nonzero_nonzero (a b:F) : not (a == 0) -> not (b == 0) -> not (a*b == 0). - Proof using Type*. intros; intro Hab. destruct (mul_zero_why _ _ Hab); auto. Qed. - Hint Resolve mul_nonzero_nonzero : field_nonzero. - - Lemma inv_nonzero (x:F) : not(x == 0) -> not(inv x==0). - Proof using H. - intros Hx Hi. - assert (Hc:not (inv x*x==0)) by (rewrite field_inv_def; eauto with field_nonzero); contradict Hc. - ring [Hi]. - Qed. - Hint Resolve inv_nonzero : field_nonzero. - - Lemma div_nonzero (x y:F) : not(x==0) -> not(y==0) -> not(x/y==0). - Proof using Type*. - unfold division, div_notation, div; auto with field_nonzero. - Qed. - Hint Resolve div_nonzero : field_nonzero. - - Lemma pow_pos_nonzero (x:F) p : not(x==0) -> not(Ncring.pow_pos x p == 0). - Proof using Type*. - intros; induction p using Pos.peano_ind; try assumption; []. - rewrite Ncring.pow_pos_succ; eauto using mul_nonzero_nonzero. - Qed. - Hint Resolve pow_pos_nonzero : field_nonzero. - - Lemma sub_diag_iff (x y:F) : x - y == 0 <-> x == y. Proof using Type*. auto with field. Qed. - - Lemma mul_same (x:F) : x*x == x^2%Z. Proof using Type*. auto with field. Qed. - - Lemma inv_mul (x y:F) : not(x==0) -> not (y==0) -> inv (x*y) == inv x * inv y. - Proof using H. intros;field;intuition. Qed. - - Lemma pow_0_r (x:F) : x^0 == 1. Proof using Type*. auto with field. Qed. - Lemma pow_1_r : forall x:F, x^1%Z == x. Proof using Type*. auto with field. Qed. - Lemma pow_2_r : forall x:F, x^2%Z == x*x. Proof using Type*. auto with field. Qed. - Lemma pow_3_r : forall x:F, x^3%Z == x*x*x. Proof using Type*. auto with field. Qed. - - Lemma pow_succ_r (x:F) (n:Z) : not (x==0)\/(n>=0)%Z -> x^(n+1) == x * x^n. - Proof using Type*. - intros Hnz; unfold power, powZ, power_field, powZ; destruct n eqn:HSn. - - simpl; ring. - - setoid_rewrite <-Pos2Z.inj_succ; rewrite Ncring.pow_pos_succ; ring. - - destruct (Z.succ (Z.neg p)) eqn:Hn. - + assert (p=1%positive) by (destruct p; simpl in *; try discriminate; auto). - subst; simpl in *; field. destruct Hnz; auto with field_nonzero. - + destruct p, p0; discriminate. - + setoid_rewrite Hn. - apply Z_neg_succ_neg in Hn; subst. - rewrite Ncring.pow_pos_succ; field; - destruct Hnz; auto with field_nonzero. - Qed. - - Lemma pow_pred_r (x:F) (n:Z) : not (x==0) -> x^(n-1) == x^n/x. - Proof using Type*. - intros; unfold power, powZ, power_field, powZ; destruct n eqn:HSn. - - simpl. rewrite unfold_div; field. - - destruct (Z.pos p - 1) eqn:Hn. - + apply Z_pos_pred_0 in Hn; subst; simpl; field. - + apply Z_pos_pred_pos in Hn; subst. - rewrite Ncring.pow_pos_succ; field; auto with field_nonzero. - + destruct p; discriminate. - - rewrite Z_pred_neg, Ncring.pow_pos_succ; field; auto with field_nonzero. - Qed. - - Local Ltac pow_peano := - repeat (setoid_rewrite pow_0_r - || setoid_rewrite pow_succ_r - || setoid_rewrite pow_pred_r). - - Lemma pow_mul (x y:F) : forall (n:Z), not(x==0)/\not(y==0)\/(n>=0)%Z -> (x * y)^n == x^n * y^n. - Proof using Type*. - match goal with |- forall n, @?P n => eapply (Z.order_induction'_0 P) end. - { repeat intro. subst. reflexivity. } - - intros; cbv [power power_field powZ]; ring. - - intros n Hn IH Hxy. - repeat setoid_rewrite pow_succ_r; try rewrite IH; try ring; (right; omega). - - intros n Hn IH Hxy. destruct Hxy as [[]|?]; try omega; []. - repeat setoid_rewrite pow_pred_r; try rewrite IH; try field; auto with field_nonzero. - Qed. - - Lemma pow_nonzero (x:F) : forall (n:Z), not(x==0) -> not(x^n==0). - Proof using Type*. - - match goal with |- forall n, @?P n => eapply (Z.order_induction'_0 P) end; intros; pow_peano; - eauto with field_nonzero. - { repeat intro. subst. reflexivity. } - Qed. - Hint Resolve pow_nonzero : field_nonzero. - - Lemma pow_inv (x:F) : forall (n:Z), not(x==0) -> inv x^n == inv (x^n). - Proof using Type*. - - match goal with |- forall n, @?P n => eapply (Z.order_induction'_0 P) end. - { repeat intro. subst. reflexivity. } - - intros; cbv [power power_field powZ]. field; eauto with field_nonzero. - - intros n Hn IH Hx. - repeat setoid_rewrite pow_succ_r; try rewrite IH; try field; eauto with field_nonzero. - - intros n Hn IH Hx. - repeat setoid_rewrite pow_pred_r; try rewrite IH; try field; eauto 3 with field_nonzero. - Qed. - - Lemma pow_0_l : forall n, (n>0)%Z -> (0:F)^n==0. - Proof using Type*. - - match goal with |- forall n, @?P n => eapply (Z.order_induction'_0 P) end; intros; try omega. - { repeat intro. subst. reflexivity. } - setoid_rewrite pow_succ_r; [auto with field|right;omega]. - Qed. - - Lemma pow_div (x y:F) (n:Z) : not (y==0) -> not(x==0)\/(n >= 0)%Z -> (x/y)^n == x^n/y^n. - Proof using Type*. - intros Hy Hxn. unfold division, div_notation, div. - rewrite pow_mul, pow_inv; try field; destruct Hxn; auto with field_nonzero. - Qed. - - Hint Extern 3 (_ >= _)%Z => omega : field_nonzero. - Lemma issquare_mul (x y z:F) : not (y == 0) -> x^2%Z == z * y^2%Z -> (x/y)^2%Z == z. - Proof using Type*. intros. rewrite pow_div by (auto with field_nonzero); auto with field. Qed. - - Lemma issquare_mul_sub (x y z:F) : 0 == z*y^2%Z - x^2%Z -> (x/y)^2%Z == z \/ x == 0. - Proof using Type*. destruct (eq_dec y 0); [right|left]; auto using issquare_mul with field. Qed. - - Lemma div_mul : forall x y z : F, not(y==0) -> (z == (x / y) <-> z * y == x). - Proof using H. auto with field. Qed. - - Lemma div_1_r : forall x : F, x/1 == x. - Proof using Type*. eauto with field field_nonzero. Qed. - - Lemma div_1_l : forall x : F, not(x==0) -> 1/x == inv x. - Proof using Type*. auto with field. Qed. - - Lemma div_opp_l : forall x y, not (y==0) -> (-_ x) / y == -_ (x / y). - Proof using Type*. auto with field. Qed. - - Lemma div_opp_r : forall x y, not (y==0) -> x / (-_ y) == -_ (x / y). - Proof using Type*. auto with field. Qed. - - Lemma eq_opp_zero : forall x : F, (~ 1 + 1 == (0:F)) -> (x == -_ x <-> x == 0). - Proof using Type*. auto with field. Qed. - - Lemma add_cancel_l : forall x y z:F, z+x == z+y <-> x == y. - Proof using Type*. auto with field. Qed. - - Lemma add_cancel_r : forall x y z:F, x+z == y+z <-> x == y. - Proof using Type*. auto with field. Qed. - - Lemma add_cancel_r_eq : forall x z:F, x+z == z <-> x == 0. - Proof using Type*. auto with field. Qed. - - Lemma add_cancel_l_eq : forall x z:F, z+x == z <-> x == 0. - Proof using Type*. auto with field. Qed. - - Lemma sqrt_solutions : forall x y:F, y ^ 2%Z == x ^ 2%Z -> y == x \/ y == -_ x. - Proof using Type*. - intros ? ? squares_eq. - remember (y - x) as z eqn:Heqz. - assert (y == x + z) as Heqy by (subst; ring); rewrite Heqy in *; clear Heqy Heqz. - assert (Hw:(x + z)^2%Z == z * (x + (x + z)) + x^2%Z) - by (auto with field); rewrite Hw in squares_eq; clear Hw. - rewrite add_cancel_r_eq in squares_eq. - apply mul_zero_why in squares_eq; destruct squares_eq; auto with field. - Qed. - - End FieldProofs. -End F. diff --git a/src/Experiments/c.sh b/src/Experiments/c.sh deleted file mode 100644 index 12757595b..000000000 --- a/src/Experiments/c.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh - -cat << EOF -#include <stdint.h> - -typedef struct { uint64_t v[10]; } fe25519; -typedef struct { fe25519 X, Y, Z, T; } ge25519; - -void ge25519_add(ge25519 *R, ge25519 *P, ge25519 *Q) { -EOF - -python -c "print ('\n'.join('\tuint64_t %s_%s_%d = %s->%s.v[%i];'%(P,c,i,P,c,i) for i in range(10) for c in 'XYZT' for P in 'PQ'))" -grep '^\s*(\*\s*let' SpecificCurve25519.v | sed 's#(\*##g' | sed 's#\s*let#\tuint64_t#g' | sed 's#:=#=#g' | sed 's#\s\+in#;#g' | sed 's#\s*\*)##g' -grep -A4 '^\s*(\*\s*let' SpecificCurve25519.v | tail -4 | tr -dc '0123456789x \n' | python -c "import sys; print ('\tge25519 ret = {{' + '},\n\t{'.join(', '.join(line.split()) for line in sys.stdin) + '}};')" - -cat << EOF - *R = ret; -} -EOF diff --git a/src/BoundedArithmetic/ArchitectureToZLike.v b/src/LegacyArithmetic/ArchitectureToZLike.v index b9e7109b9..19450f831 100644 --- a/src/BoundedArithmetic/ArchitectureToZLike.v +++ b/src/LegacyArithmetic/ArchitectureToZLike.v @@ -1,8 +1,8 @@ (*** Implementing ℤ-Like via Architecture *) Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.ModularArithmetic.ZBounded. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.ZBounded. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.LetIn. diff --git a/src/BoundedArithmetic/ArchitectureToZLikeProofs.v b/src/LegacyArithmetic/ArchitectureToZLikeProofs.v index e08624274..8d4b59ceb 100644 --- a/src/BoundedArithmetic/ArchitectureToZLikeProofs.v +++ b/src/LegacyArithmetic/ArchitectureToZLikeProofs.v @@ -1,12 +1,12 @@ (*** Proving ℤ-Like via Architecture *) Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.RippleCarryAddSub. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Multiply. -Require Import Crypto.BoundedArithmetic.ArchitectureToZLike. -Require Import Crypto.ModularArithmetic.ZBounded. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.InterfaceProofs. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.RippleCarryAddSub. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Multiply. +Require Import Crypto.LegacyArithmetic.ArchitectureToZLike. +Require Import Crypto.LegacyArithmetic.ZBounded. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.UniquePose. diff --git a/src/ModularArithmetic/BarrettReduction/ZBounded.v b/src/LegacyArithmetic/BarretReduction.v index e7fb529fd..e278dc082 100644 --- a/src/ModularArithmetic/BarrettReduction/ZBounded.v +++ b/src/LegacyArithmetic/BarretReduction.v @@ -2,8 +2,8 @@ (** This file implements Barrett Reduction on [ZLikeOps]. We follow [BarretReduction/ZHandbook.v]. *) Require Import Coq.ZArith.ZArith Coq.Lists.List Coq.Classes.Morphisms Coq.micromega.Psatz. -Require Import Crypto.ModularArithmetic.BarrettReduction.ZHandbook. -Require Import Crypto.ModularArithmetic.ZBounded. +Require Import Crypto.Arithmetic.BarrettReduction.HAC. +Require Import Crypto.LegacyArithmetic.ZBounded. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Notations. diff --git a/src/LegacyArithmetic/BaseSystem.v b/src/LegacyArithmetic/BaseSystem.v new file mode 100644 index 000000000..a54bc483f --- /dev/null +++ b/src/LegacyArithmetic/BaseSystem.v @@ -0,0 +1,39 @@ +Require Import Coq.Lists.List. +Require Import Coq.ZArith.ZArith Coq.ZArith.Zdiv. +Require Import Coq.omega.Omega Coq.Numbers.Natural.Peano.NPeano Coq.Arith.Arith. +Require Import Crypto.Util.ListUtil Crypto.Util.ZUtil. +Require Import Crypto.Util.Notations. +Require Export Crypto.Util.FixCoqMistakes. +Import Nat. + +Local Open Scope Z. + +Class BaseVector (base : list Z):= { + base_positive : forall b, In b base -> b > 0; (* nonzero would probably work too... *) + b0_1 : forall x, nth_default x base 0 = 1; (** TODO(jadep,jgross): change to [nth_error base 0 = Some 1], then use [nth_error_value_eq_nth_default] to prove a [forall x, nth_default x base 0 = 1] as a lemma *) + base_good : + forall i j, (i+j < length base)%nat -> + let b := nth_default 0 base in + let r := (b i * b j) / b (i+j)%nat in + b i * b j = r * b (i+j)%nat +}. + +Section BaseSystem. + Context (base : list Z). + (** [BaseSystem] implements an constrained positional number system. + A wide variety of bases are supported: the base coefficients are not + required to be powers of 2, and it is NOT necessarily the case that + $b_{i+j} = b_i b_j$. Implementations of addition and multiplication are + provided, with focus on near-optimal multiplication performance on + non-trivial but small operands: maybe 10 32-bit integers or so. This + module does not handle carries automatically: if no restrictions are put + on the use of a [BaseSystem], each digit is unbounded. This has nothing + to do with modular arithmetic either. + *) + Definition digits : Type := list Z. + + Definition accumulate p acc := fst p * snd p + acc. + Definition decode' bs u := fold_right accumulate 0 (combine u bs). + Definition decode := decode' base. + Definition mul_each u := map (Z.mul u). +End BaseSystem.
\ No newline at end of file diff --git a/src/LegacyArithmetic/BaseSystemProofs.v b/src/LegacyArithmetic/BaseSystemProofs.v new file mode 100644 index 000000000..9a06109d1 --- /dev/null +++ b/src/LegacyArithmetic/BaseSystemProofs.v @@ -0,0 +1,133 @@ +Require Import Coq.Lists.List Coq.micromega.Psatz. +Require Import Crypto.Util.ListUtil Crypto.Util.ZUtil. +Require Import Coq.ZArith.ZArith Coq.ZArith.Zdiv. +Require Import Coq.omega.Omega Coq.Numbers.Natural.Peano.NPeano Coq.Arith.Arith. +Require Import Crypto.LegacyArithmetic.BaseSystem. +Require Import Crypto.Util.Tactics.UniquePose. +Require Import Crypto.Util.Notations. +Import Morphisms. +Local Open Scope Z. + +Local Hint Extern 1 (@eq Z _ _) => ring. + +Section BaseSystemProofs. + Context `(base_vector : BaseVector). + + Lemma decode'_truncate : forall bs us, decode' bs us = decode' bs (firstn (length bs) us). + Proof using Type. + unfold decode'; intros; f_equal; apply combine_truncate_l. + Qed. + + Lemma decode'_splice : forall xs ys bs, + decode' bs (xs ++ ys) = + decode' (firstn (length xs) bs) xs + decode' (skipn (length xs) bs) ys. + Proof using Type. + unfold decode'. + induction xs; destruct ys, bs; boring. + + rewrite combine_truncate_r. + do 2 rewrite Z.add_0_r; auto. + + unfold accumulate. + apply Z.add_assoc. + Qed. + + Lemma decode_nil : forall bs, decode' bs nil = 0. + Proof using Type. + + auto. + Qed. + Hint Rewrite decode_nil. + + Lemma decode_base_nil : forall us, decode' nil us = 0. + Proof using Type. + intros; rewrite decode'_truncate; auto. + Qed. + + Lemma mul_each_rep : forall bs u vs, + decode' bs (mul_each u vs) = u * decode' bs vs. + Proof using Type. + unfold decode', accumulate; induction bs; destruct vs; boring; ring. + Qed. + + Lemma base_eq_1cons: base = 1 :: skipn 1 base. + Proof using Type*. + pose proof (b0_1 0) as H. + destruct base; compute in H; try discriminate; boring. + Qed. + + Lemma decode'_cons : forall x1 x2 xs1 xs2, + decode' (x1 :: xs1) (x2 :: xs2) = x1 * x2 + decode' xs1 xs2. + Proof using Type. + unfold decode', accumulate; boring; ring. + Qed. + Hint Rewrite decode'_cons. + + Lemma decode_cons : forall x us, + decode base (x :: us) = x + decode base (0 :: us). + Proof using Type*. + unfold decode; intros. + rewrite base_eq_1cons. + autorewrite with core; ring_simplify; auto. + Qed. + + Lemma decode'_map_mul : forall v xs bs, + decode' (map (Z.mul v) bs) xs = + Z.mul v (decode' bs xs). + Proof using Type. + unfold decode'. + induction xs; destruct bs; boring. + unfold accumulate; simpl; nia. + Qed. + + Lemma decode_map_mul : forall v xs, + decode (map (Z.mul v) base) xs = + Z.mul v (decode base xs). + Proof using Type. + unfold decode; intros; apply decode'_map_mul. + Qed. + + Lemma mul_each_base : forall us bs c, + decode' bs (mul_each c us) = decode' (mul_each c bs) us. + Proof using Type. + induction us; destruct bs; boring; ring. + Qed. + + Hint Rewrite (@nth_default_nil Z). + Hint Rewrite (@firstn_nil Z). + Hint Rewrite (@skipn_nil Z). + + Lemma peel_decode : forall xs ys x y, decode' (x::xs) (y::ys) = x*y + decode' xs ys. + Proof using Type. + boring. + Qed. + Hint Rewrite peel_decode. + + Hint Rewrite plus_0_r. + + Lemma set_higher : forall bs vs x, + decode' bs (vs++x::nil) = decode' bs vs + nth_default 0 bs (length vs) * x. + Proof using Type. + intros. + rewrite !decode'_splice. + cbv [decode' nth_default]; break_match; ring_simplify; + match goal with + | [H:_ |- _] => unique pose proof (nth_error_error_length _ _ _ H) + | [H:_ |- _] => unique pose proof (nth_error_value_length _ _ _ _ H) + end; + repeat match goal with + | _ => solve [simpl;ring_simplify; trivial] + | _ => progress ring_simplify + | _ => progress rewrite skipn_all by trivial + | _ => progress rewrite combine_nil_r + | _ => progress rewrite firstn_all2 by trivial + end. + rewrite (combine_truncate_r vs bs); apply (f_equal2 Z.add); trivial; []. + unfold combine; break_match. + { apply (f_equal (@length _)) in Heql; simpl length in Heql; rewrite skipn_length in Heql; omega. } + { cbv -[Z.add Z.mul]; ring_simplify; f_equal. + assert (HH: nth_error (z0 :: l) 0 = Some z) by + ( + pose proof @nth_error_skipn _ (length vs) bs 0; + rewrite plus_0_r in *; + congruence); simpl in HH; congruence. } + Qed. +End BaseSystemProofs.
\ No newline at end of file diff --git a/src/BoundedArithmetic/Double/Core.v b/src/LegacyArithmetic/Double/Core.v index 82b450e76..b7be2d18a 100644 --- a/src/BoundedArithmetic/Double/Core.v +++ b/src/LegacyArithmetic/Double/Core.v @@ -1,14 +1,16 @@ (*** Implementing Large Bounded Arithmetic via pairs *) Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.ModularArithmetic.Pow2Base. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.InterfaceProofs. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.ListUtil. Require Import Crypto.Util.Notations. Require Import Crypto.Util.LetIn. Import Bug5107WorkAround. +Require Crypto.LegacyArithmetic.BaseSystem. +Require Crypto.LegacyArithmetic.Pow2Base. + Local Open Scope nat_scope. Local Open Scope Z_scope. Local Open Scope type_scope. @@ -18,7 +20,7 @@ Local Notation eta x := (fst x, snd x). (** The list is low to high; the tuple is low to high *) Definition tuple_decoder {n W} {decode : decoder n W} {k : nat} : decoder (k * n) (tuple W k) - := {| decode w := BaseSystem.decode (base_from_limb_widths (repeat n k)) + := {| decode w := BaseSystem.decode (Pow2Base.base_from_limb_widths (repeat n k)) (List.map decode (List.rev (Tuple.to_list _ w))) |}. Global Arguments tuple_decoder : simpl never. Hint Extern 3 (decoder _ (tuple ?W ?k)) => let kv := (eval simpl in (Z.of_nat k)) in apply (fun n decode => (@tuple_decoder n W decode k : decoder (kv * n) (tuple W k))) : typeclass_instances. diff --git a/src/BoundedArithmetic/Double/Proofs/BitwiseOr.v b/src/LegacyArithmetic/Double/Proofs/BitwiseOr.v index 9d5b409f8..0f07c6299 100644 --- a/src/BoundedArithmetic/Double/Proofs/BitwiseOr.v +++ b/src/LegacyArithmetic/Double/Proofs/BitwiseOr.v @@ -1,7 +1,7 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.BreakMatch. diff --git a/src/BoundedArithmetic/Double/Proofs/Decode.v b/src/LegacyArithmetic/Double/Proofs/Decode.v index e3d57bdfc..b5b6d6623 100644 --- a/src/BoundedArithmetic/Double/Proofs/Decode.v +++ b/src/LegacyArithmetic/Double/Proofs/Decode.v @@ -1,15 +1,15 @@ Require Import Coq.ZArith.ZArith Coq.Lists.List Coq.micromega.Psatz. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BaseSystem. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.InterfaceProofs. +Require Import Crypto.LegacyArithmetic.Double.Core. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.ListUtil. Require Import Crypto.Util.Notations. +Require Crypto.LegacyArithmetic.Pow2Base. +Require Crypto.LegacyArithmetic.Pow2BaseProofs. + Local Open Scope nat_scope. Local Open Scope type_scope. @@ -25,10 +25,10 @@ Section decode. Local Notation limb_widths := (repeat n k). Lemma decode_bounded {isdecode : is_decode decode} w - : 0 <= n -> bounded limb_widths (List.map decode (rev (to_list k w))). + : 0 <= n -> Pow2Base.bounded limb_widths (List.map decode (rev (to_list k w))). Proof using Type. intro. - eapply bounded_uniform; try solve [ eauto using repeat_spec ]. + eapply Pow2BaseProofs.bounded_uniform; try solve [ eauto using repeat_spec ]. { distr_length. } { intros z H'. apply in_map_iff in H'. @@ -42,20 +42,20 @@ Section decode. unfold tuple_decoder; hnf; simpl. intro w. destruct (zerop k); [ subst | ]. - { unfold BaseSystem.decode, BaseSystem.decode'; simpl; omega. } + { cbv; intuition congruence. } assert (0 <= n) by (destruct k as [ | [|] ]; [ omega | | destruct w ]; eauto using decode_exponent_nonnegative). - replace (2^(k * n)) with (upper_bound limb_widths) - by (erewrite upper_bound_uniform by eauto using repeat_spec; distr_length). - apply decode_upper_bound; auto using decode_bounded. + replace (2^(k * n)) with (Pow2Base.upper_bound limb_widths) + by (erewrite Pow2BaseProofs.upper_bound_uniform by eauto using repeat_spec; distr_length). + apply Pow2BaseProofs.decode_upper_bound; auto using decode_bounded. { intros ? H'. apply repeat_spec in H'; omega. } { distr_length. } Qed. End with_k. - Local Arguments base_from_limb_widths : simpl never. + Local Arguments Pow2Base.base_from_limb_widths : simpl never. Local Arguments repeat : simpl never. Local Arguments Z.mul !_ !_. Lemma tuple_decoder_S {k} w : 0 <= n -> (tuple_decoder (k := S (S k)) w = tuple_decoder (k := S k) (fst w) + (decode (snd w) << (S k * n)))%Z. @@ -64,16 +64,15 @@ Section decode. destruct w as [? w]; simpl. replace (decode w) with (decode w * 1 + 0)%Z by omega. rewrite map_app, map_cons, map_nil. - erewrite decode_shift_uniform_app by (eauto using repeat_spec; distr_length). + erewrite Pow2BaseProofs.decode_shift_uniform_app by (eauto using repeat_spec; distr_length). distr_length. autorewrite with push_skipn natsimplify push_firstn. reflexivity. Qed. Global Instance tuple_decoder_O w : tuple_decoder (k := 1) w =~> decode w. Proof using Type. - unfold tuple_decoder, BaseSystem.decode, BaseSystem.decode', accumulate, base_from_limb_widths, repeat. - simpl; hnf. - omega. + cbv [tuple_decoder LegacyArithmetic.BaseSystem.decode LegacyArithmetic.BaseSystem.decode' LegacyArithmetic.BaseSystem.accumulate Pow2Base.base_from_limb_widths repeat]. + simpl; hnf; lia. Qed. Global Instance tuple_decoder_m1 w : tuple_decoder (k := 0) w =~> 0. Proof using Type. reflexivity. Qed. @@ -92,7 +91,7 @@ Section decode. : (P _ (tuple_decoder (k := 1)) -> P _ decode) * (P _ decode -> P _ (tuple_decoder (k := 1))). Proof using Type. - unfold tuple_decoder, BaseSystem.decode, BaseSystem.decode', accumulate, base_from_limb_widths, repeat. + unfold tuple_decoder, BaseSystem.decode, BaseSystem.decode', BaseSystem.accumulate, Pow2Base.base_from_limb_widths, repeat. simpl; hnf. rewrite Z.mul_1_l. split; apply P_ext; simpl; intro; autorewrite with zsimplify_const; reflexivity. diff --git a/src/BoundedArithmetic/Double/Proofs/LoadImmediate.v b/src/LegacyArithmetic/Double/Proofs/LoadImmediate.v index 9c00b728f..2c7f87dd7 100644 --- a/src/BoundedArithmetic/Double/Proofs/LoadImmediate.v +++ b/src/LegacyArithmetic/Double/Proofs/LoadImmediate.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.InterfaceProofs. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. Require Import Crypto.Util.ZUtil. Local Open Scope Z_scope. diff --git a/src/BoundedArithmetic/Double/Proofs/Multiply.v b/src/LegacyArithmetic/Double/Proofs/Multiply.v index 6d2f72c25..8fed917d9 100644 --- a/src/BoundedArithmetic/Double/Proofs/Multiply.v +++ b/src/LegacyArithmetic/Double/Proofs/Multiply.v @@ -1,10 +1,10 @@ Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.SpreadLeftImmediate. -Require Import Crypto.BoundedArithmetic.Double.Proofs.RippleCarryAddSub. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.InterfaceProofs. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Double.Proofs.SpreadLeftImmediate. +Require Import Crypto.LegacyArithmetic.Double.Proofs.RippleCarryAddSub. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.SimplifyProjections. Require Import Crypto.Util.Notations. diff --git a/src/BoundedArithmetic/Double/Proofs/RippleCarryAddSub.v b/src/LegacyArithmetic/Double/Proofs/RippleCarryAddSub.v index 5d9443a91..e703c2e57 100644 --- a/src/BoundedArithmetic/Double/Proofs/RippleCarryAddSub.v +++ b/src/LegacyArithmetic/Double/Proofs/RippleCarryAddSub.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.InterfaceProofs. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.BreakMatch. diff --git a/src/BoundedArithmetic/Double/Proofs/SelectConditional.v b/src/LegacyArithmetic/Double/Proofs/SelectConditional.v index 8dd12e0bc..953acf056 100644 --- a/src/BoundedArithmetic/Double/Proofs/SelectConditional.v +++ b/src/LegacyArithmetic/Double/Proofs/SelectConditional.v @@ -1,7 +1,7 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. Section select_conditional. Context {n W} diff --git a/src/BoundedArithmetic/Double/Proofs/ShiftLeft.v b/src/LegacyArithmetic/Double/Proofs/ShiftLeft.v index 759c05e6e..2230e36b6 100644 --- a/src/BoundedArithmetic/Double/Proofs/ShiftLeft.v +++ b/src/LegacyArithmetic/Double/Proofs/ShiftLeft.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.ShiftLeftRightTactic. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Double.Proofs.ShiftLeftRightTactic. Require Import Crypto.Util.ZUtil. (*Require Import Crypto.Util.Tactics.*) diff --git a/src/BoundedArithmetic/Double/Proofs/ShiftLeftRightTactic.v b/src/LegacyArithmetic/Double/Proofs/ShiftLeftRightTactic.v index 997fb1937..41234bf6e 100644 --- a/src/BoundedArithmetic/Double/Proofs/ShiftLeftRightTactic.v +++ b/src/LegacyArithmetic/Double/Proofs/ShiftLeftRightTactic.v @@ -1,5 +1,5 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Interface. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.UniquePose. Require Import Crypto.Util.Tactics.BreakMatch. diff --git a/src/BoundedArithmetic/Double/Proofs/ShiftRight.v b/src/LegacyArithmetic/Double/Proofs/ShiftRight.v index f2509927f..16e7c5d6a 100644 --- a/src/BoundedArithmetic/Double/Proofs/ShiftRight.v +++ b/src/LegacyArithmetic/Double/Proofs/ShiftRight.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.ShiftLeftRightTactic. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Double.Proofs.ShiftLeftRightTactic. Require Import Crypto.Util.ZUtil. (*Require Import Crypto.Util.Tactics.*) diff --git a/src/BoundedArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v b/src/LegacyArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v index 7e9f5ddcd..00a6d03cd 100644 --- a/src/BoundedArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v +++ b/src/LegacyArithmetic/Double/Proofs/ShiftRightDoubleWordImmediate.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. -Require Import Crypto.BoundedArithmetic.Double.Proofs.ShiftLeftRightTactic. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Double.Proofs.ShiftLeftRightTactic. Require Import Crypto.Util.ZUtil. (*Require Import Crypto.Util.Tactics.*) diff --git a/src/BoundedArithmetic/Double/Proofs/SpreadLeftImmediate.v b/src/LegacyArithmetic/Double/Proofs/SpreadLeftImmediate.v index 84f24eef5..c50d43616 100644 --- a/src/BoundedArithmetic/Double/Proofs/SpreadLeftImmediate.v +++ b/src/LegacyArithmetic/Double/Proofs/SpreadLeftImmediate.v @@ -1,8 +1,8 @@ Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.BoundedArithmetic.Interface. -Require Import Crypto.BoundedArithmetic.InterfaceProofs. -Require Import Crypto.BoundedArithmetic.Double.Core. -Require Import Crypto.BoundedArithmetic.Double.Proofs.Decode. +Require Import Crypto.LegacyArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.InterfaceProofs. +Require Import Crypto.LegacyArithmetic.Double.Core. +Require Import Crypto.LegacyArithmetic.Double.Proofs.Decode. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.Tactics.SpecializeBy. diff --git a/src/BoundedArithmetic/Interface.v b/src/LegacyArithmetic/Interface.v index 4a671eb4c..4a671eb4c 100644 --- a/src/BoundedArithmetic/Interface.v +++ b/src/LegacyArithmetic/Interface.v diff --git a/src/BoundedArithmetic/InterfaceProofs.v b/src/LegacyArithmetic/InterfaceProofs.v index 85120f50c..9ef97fa55 100644 --- a/src/BoundedArithmetic/InterfaceProofs.v +++ b/src/LegacyArithmetic/InterfaceProofs.v @@ -1,6 +1,6 @@ (** * Alternate forms for Interface for bounded arithmetic *) Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.BoundedArithmetic.Interface. +Require Import Crypto.LegacyArithmetic.Interface. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tuple. Require Import Crypto.Util.AutoRewrite. diff --git a/src/ModularArithmetic/Montgomery/ZBounded.v b/src/LegacyArithmetic/MontgomeryReduction.v index 7b52ce009..c3538dd01 100644 --- a/src/ModularArithmetic/Montgomery/ZBounded.v +++ b/src/LegacyArithmetic/MontgomeryReduction.v @@ -2,9 +2,9 @@ (** This file implements Montgomery Form, Montgomery Reduction, and Montgomery Multiplication on [ZLikeOps]. We follow [Montgomery/Z.v]. *) Require Import Coq.ZArith.ZArith Coq.Lists.List Coq.Classes.Morphisms Coq.micromega.Psatz. -Require Import Crypto.ModularArithmetic.Montgomery.Z. -Require Import Crypto.ModularArithmetic.Montgomery.ZProofs. -Require Import Crypto.ModularArithmetic.ZBounded. +Require Import Crypto.Arithmetic.MontgomeryReduction.Definition. +Require Import Crypto.Arithmetic.MontgomeryReduction.Proofs. +Require Import Crypto.LegacyArithmetic.ZBounded. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.Test. Require Import Crypto.Util.Tactics.Not. @@ -37,7 +37,7 @@ Section montgomery. Definition partial_reduce : forall v : LargeT, { partial_reduce : SmallT | large_valid v - -> decode_small partial_reduce = Montgomery.Z.partial_reduce modulus small_bound (decode_small modulus') (decode_large v) + -> decode_small partial_reduce = MontgomeryReduction.Definition.partial_reduce modulus small_bound (decode_small modulus') (decode_large v) /\ small_valid partial_reduce }. Proof. intro T. evar (pr : SmallT); exists pr. intros T_valid. @@ -48,7 +48,7 @@ Section montgomery. assert (0 <= modulus) by apply (modulus_nonneg _). assert (modulus < small_bound) by (rewrite <- modulus_digits_correct; omega). rewrite <- partial_reduce_alt_eq by omega. - cbv [Montgomery.Z.partial_reduce Montgomery.Z.partial_reduce_alt Montgomery.Z.prereduce]. + cbv [MontgomeryReduction.Definition.partial_reduce MontgomeryReduction.Definition.partial_reduce_alt MontgomeryReduction.Definition.prereduce]. pull_zlike_decode. cse. subst pr; split; [ reflexivity | exact _ ]. @@ -57,7 +57,7 @@ Section montgomery. Definition reduce_via_partial : forall v : LargeT, { reduce : SmallT | large_valid v - -> decode_small reduce = Montgomery.Z.reduce_via_partial modulus small_bound (decode_small modulus') (decode_large v) + -> decode_small reduce = MontgomeryReduction.Definition.reduce_via_partial modulus small_bound (decode_small modulus') (decode_large v) /\ small_valid reduce }. Proof. intro T. evar (pr : SmallT); exists pr. intros T_valid. @@ -69,7 +69,7 @@ Section montgomery. assert (modulus < small_bound) by (rewrite <- modulus_digits_correct; omega). unfold reduce_via_partial. rewrite <- partial_reduce_alt_eq by omega. - cbv [Montgomery.Z.partial_reduce Montgomery.Z.partial_reduce_alt Montgomery.Z.prereduce]. + cbv [MontgomeryReduction.Definition.partial_reduce MontgomeryReduction.Definition.partial_reduce_alt MontgomeryReduction.Definition.prereduce]. pull_zlike_decode. cse. subst pr; split; [ reflexivity | exact _ ]. diff --git a/src/LegacyArithmetic/Pow2Base.v b/src/LegacyArithmetic/Pow2Base.v new file mode 100644 index 000000000..62f1f742d --- /dev/null +++ b/src/LegacyArithmetic/Pow2Base.v @@ -0,0 +1,19 @@ +Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. +Require Import Crypto.Util.ListUtil. +Require Import Crypto.Util.ZUtil. +Require Import Coq.Lists.List. + +Local Open Scope Z_scope. + +Section Pow2Base. + Context (limb_widths : list Z). + Local Notation "w[ i ]" := (nth_default 0 limb_widths i). + Fixpoint base_from_limb_widths limb_widths := + match limb_widths with + | nil => nil + | w :: lw => 1 :: map (Z.mul (two_p w)) (base_from_limb_widths lw) + end. + Local Notation base := (base_from_limb_widths limb_widths). + Definition bounded us := forall i, 0 <= nth_default 0 us i < 2 ^ w[i]. + Definition upper_bound := 2 ^ (sum_firstn limb_widths (length limb_widths)). +End Pow2Base. diff --git a/src/LegacyArithmetic/Pow2BaseProofs.v b/src/LegacyArithmetic/Pow2BaseProofs.v new file mode 100644 index 000000000..8a38275dd --- /dev/null +++ b/src/LegacyArithmetic/Pow2BaseProofs.v @@ -0,0 +1,555 @@ +Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.micromega.Psatz. +Require Import Coq.Numbers.Natural.Peano.NPeano. +Require Import Coq.Lists.List. +Require Import Coq.funind.Recdef. +Require Import Crypto.Util.ListUtil Crypto.Util.ZUtil Crypto.Util.NatUtil. +Require Import Crypto.LegacyArithmetic.VerdiTactics. +Require Import Crypto.Util.Tactics.SpecializeBy. +Require Import Crypto.Util.Tactics.BreakMatch. +Require Import Crypto.Util.Tactics.UniquePose. +Require Import Crypto.Util.Tactics.RewriteHyp. +Require Import Crypto.LegacyArithmetic.Pow2Base. +Require Import Crypto.Util.Notations. +Require Export Crypto.Util.Bool. +Require Export Crypto.Util.FixCoqMistakes. +Local Open Scope Z_scope. + +Require Crypto.LegacyArithmetic.BaseSystemProofs. + +Create HintDb simpl_add_to_nth discriminated. +Create HintDb push_upper_bound discriminated. +Create HintDb pull_upper_bound discriminated. +Create HintDb push_base_from_limb_widths discriminated. +Create HintDb pull_base_from_limb_widths discriminated. + +Hint Extern 1 => progress autorewrite with push_upper_bound in * : push_upper_bound. +Hint Extern 1 => progress autorewrite with pull_upper_bound in * : pull_upper_bound. +Hint Extern 1 => progress autorewrite with push_base_from_limb_widths in * : push_base_from_limb_widths. +Hint Extern 1 => progress autorewrite with pull_base_from_limb_widths in * : pull_base_from_limb_widths. + +Section Pow2BaseProofs. + Context {limb_widths} (limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w). + Local Notation base := (base_from_limb_widths limb_widths). + + Lemma base_from_limb_widths_length ls : length (base_from_limb_widths ls) = length ls. + Proof using Type. + clear limb_widths limb_widths_nonneg. + induction ls; [ reflexivity | simpl in * ]. + autorewrite with distr_length; auto. + Qed. + Hint Rewrite base_from_limb_widths_length : distr_length. + + Lemma base_from_limb_widths_cons : forall l0 l, + base_from_limb_widths (l0 :: l) = 1 :: map (Z.mul (two_p l0)) (base_from_limb_widths l). + Proof using Type. reflexivity. Qed. + Hint Rewrite base_from_limb_widths_cons : push_base_from_limb_widths. + Hint Rewrite <- base_from_limb_widths_cons : pull_base_from_limb_widths. + + Lemma base_from_limb_widths_nil : base_from_limb_widths nil = nil. + Proof using Type. reflexivity. Qed. + Hint Rewrite base_from_limb_widths_nil : push_base_from_limb_widths. + + Lemma firstn_base_from_limb_widths : forall n, firstn n (base_from_limb_widths limb_widths) = base_from_limb_widths (firstn n limb_widths). + Proof using Type. + clear limb_widths_nonneg. (* don't use this in the inductive hypothesis *) + induction limb_widths as [|l ls IHls]; intros [|n]; try reflexivity. + autorewrite with push_base_from_limb_widths push_firstn; boring. + Qed. + Hint Rewrite <- @firstn_base_from_limb_widths : push_base_from_limb_widths. + Hint Rewrite <- @firstn_base_from_limb_widths : pull_firstn. + Hint Rewrite @firstn_base_from_limb_widths : pull_base_from_limb_widths. + Hint Rewrite @firstn_base_from_limb_widths : push_firstn. + + Lemma sum_firstn_limb_widths_nonneg : forall n, 0 <= sum_firstn limb_widths n. + Proof using Type*. + unfold sum_firstn; intros. + apply fold_right_invariant; try omega. + eauto using Z.add_nonneg_nonneg, limb_widths_nonneg, In_firstn. + Qed. Hint Resolve sum_firstn_limb_widths_nonneg. + + Lemma base_from_limb_widths_step : forall i b w, (S i < length limb_widths)%nat -> + nth_error base i = Some b -> + nth_error limb_widths i = Some w -> + nth_error base (S i) = Some (two_p w * b). + Proof using Type. + clear limb_widths_nonneg. (* don't use this in the inductive hypothesis *) + induction limb_widths; intros ? ? ? ? nth_err_w nth_err_b; + unfold base_from_limb_widths in *; fold base_from_limb_widths in *; + [rewrite (@nil_length0 Z) in *; omega | ]. + simpl in *. + case_eq i; intros; subst. + + subst; apply nth_error_first in nth_err_w. + apply nth_error_first in nth_err_b; subst. + apply map_nth_error. + case_eq l; intros; subst; [simpl in *; omega | ]. + unfold base_from_limb_widths; fold base_from_limb_widths. + reflexivity. + + simpl in nth_err_w. + apply nth_error_map in nth_err_w. + destruct nth_err_w as [x [A B] ]. + subst. + replace (two_p w * (two_p a * x)) with (two_p a * (two_p w * x)) by ring. + apply map_nth_error. + apply IHl; auto. omega. + Qed. + + + Lemma nth_error_base : forall i, (i < length limb_widths)%nat -> + nth_error base i = Some (two_p (sum_firstn limb_widths i)). + Proof using Type*. + induction i; intros. + + unfold sum_firstn, base_from_limb_widths in *; case_eq limb_widths; try reflexivity. + intro lw_nil; rewrite lw_nil, (@nil_length0 Z) in *; omega. + + assert (i < length limb_widths)%nat as lt_i_length by omega. + specialize (IHi lt_i_length). + destruct (nth_error_length_exists_value _ _ lt_i_length) as [w nth_err_w]. + erewrite base_from_limb_widths_step; eauto. + f_equal. + simpl. + destruct (NPeano.Nat.eq_dec i 0). + - subst; unfold sum_firstn; simpl. + apply nth_error_exists_first in nth_err_w. + destruct nth_err_w as [l' lw_destruct]; subst. + simpl; ring_simplify. + f_equal; ring. + - erewrite sum_firstn_succ; eauto. + symmetry. + apply two_p_is_exp; auto using sum_firstn_limb_widths_nonneg. + apply limb_widths_nonneg. + eapply nth_error_value_In; eauto. + Qed. + + Lemma nth_default_base : forall d i, (i < length limb_widths)%nat -> + nth_default d base i = 2 ^ (sum_firstn limb_widths i). + Proof using Type*. + intros ? ? i_lt_length. + apply nth_error_value_eq_nth_default. + rewrite nth_error_base, two_p_correct by assumption. + reflexivity. + Qed. + + Lemma b0_1 : forall x : Z, limb_widths <> nil -> nth_default x base 0 = 1. + Proof using Type. + case_eq limb_widths; intros; [congruence | reflexivity]. + Qed. + + Lemma base_from_limb_widths_app : forall l0 l + (l0_nonneg : forall x, In x l0 -> 0 <= x) + (l_nonneg : forall x, In x l -> 0 <= x), + base_from_limb_widths (l0 ++ l) + = base_from_limb_widths l0 ++ map (Z.mul (two_p (sum_firstn l0 (length l0)))) (base_from_limb_widths l). + Proof using Type. + induction l0 as [|?? IHl0]. + { simpl; intros; rewrite <- map_id at 1; apply map_ext; intros; omega. } + { simpl; intros; rewrite !IHl0, !map_app, map_map, sum_firstn_succ_cons, two_p_is_exp by auto with znonzero. + do 2 f_equal; apply map_ext; intros; lia. } + Qed. + + Lemma skipn_base_from_limb_widths : forall n, skipn n (base_from_limb_widths limb_widths) = map (Z.mul (two_p (sum_firstn limb_widths n))) (base_from_limb_widths (skipn n limb_widths)). + Proof using Type*. + intro n; pose proof (base_from_limb_widths_app (firstn n limb_widths) (skipn n limb_widths)) as H. + specialize_by eauto using In_firstn, In_skipn. + autorewrite with simpl_firstn simpl_skipn in *. + rewrite H, skipn_app, skipn_all by auto with arith distr_length; clear H. + simpl; distr_length. + apply Min.min_case_strong; intro; + unfold sum_firstn; autorewrite with natsimplify simpl_skipn simpl_firstn; + reflexivity. + Qed. + Hint Rewrite <- @skipn_base_from_limb_widths : push_base_from_limb_widths. + Hint Rewrite <- @skipn_base_from_limb_widths : pull_skipn. + Hint Rewrite @skipn_base_from_limb_widths : pull_base_from_limb_widths. + Hint Rewrite @skipn_base_from_limb_widths : push_skipn. + + Lemma pow2_mod_bounded :forall lw us i, (forall w, In w lw -> 0 <= w) -> bounded lw us -> + Z.pow2_mod (nth_default 0 us i) (nth_default 0 lw i) = nth_default 0 us i. + Proof using Type. + clear. + repeat match goal with + | |- _ => progress (cbv [bounded]; intros) + | |- _ => break_if + | |- _ => apply Z.bits_inj' + | |- _ => rewrite Z.testbit_pow2_mod by (apply nth_default_preserves_properties; auto; omega) + | |- _ => reflexivity + end. + specialize (H0 i). + symmetry. + rewrite <- (Z.mod_pow2_bits_high (nth_default 0 us i) (nth_default 0 lw i) n); + [ rewrite Z.mod_small by omega; reflexivity | ]. + split; try omega. + apply nth_default_preserves_properties; auto; omega. + Qed. + + Lemma bounded_nil_iff : forall us, bounded nil us <-> (forall u, In u us -> u = 0). + Proof using Type. + clear. + split; cbv [bounded]; intros. + + edestruct (In_nth_error_value us u); try assumption. + specialize (H x). + replace u with (nth_default 0 us x) by (auto using nth_error_value_eq_nth_default). + rewrite nth_default_nil, Z.pow_0_r in H. + omega. + + rewrite nth_default_nil, Z.pow_0_r. + apply nth_default_preserves_properties; try omega. + intros. + apply H in H0. + omega. + Qed. + + Lemma bounded_iff : forall lw us, bounded lw us <-> forall i, 0 <= nth_default 0 us i < 2 ^ nth_default 0 lw i. + Proof using Type. + clear. + cbv [bounded]; intros. + reflexivity. + Qed. + + Lemma digit_select : forall us i, bounded limb_widths us -> + nth_default 0 us i = Z.pow2_mod (BaseSystem.decode base us >> sum_firstn limb_widths i) (nth_default 0 limb_widths i). + Proof using Type*. + intro; revert limb_widths limb_widths_nonneg; induction us; intros. + + rewrite nth_default_nil, BaseSystemProofs.decode_nil, Z.shiftr_0_l, Z.pow2_mod_spec, Z.mod_0_l by + (try (apply Z.pow_nonzero; try omega); apply nth_default_preserves_properties; auto; omega). + reflexivity. + + destruct i. + - rewrite nth_default_cons, sum_firstn_0, Z.shiftr_0_r. + destruct limb_widths as [|w lw]. + * cbv [base_from_limb_widths]. + rewrite <-pow2_mod_bounded with (lw := nil); rewrite bounded_nil_iff in *; auto using in_cons; + try solve [intros; exfalso; eauto using in_nil]. + rewrite !nth_default_nil, BaseSystemProofs.decode_base_nil; auto. + cbv. auto using in_eq. + * rewrite nth_default_cons, base_from_limb_widths_cons, BaseSystemProofs.peel_decode. + fold (BaseSystem.mul_each (two_p w)). + rewrite <-BaseSystemProofs.mul_each_base, BaseSystemProofs.mul_each_rep. + rewrite two_p_correct, (Z.mul_comm (2 ^ w)). + rewrite <-Z.shiftl_mul_pow2 by auto using in_eq. + rewrite bounded_iff in *. + specialize (H 0%nat); rewrite !nth_default_cons in H. + rewrite <-Z.lor_shiftl by (auto using in_eq; omega). + apply Z.bits_inj'; intros. + rewrite Z.testbit_pow2_mod by auto using in_eq. + break_if. { + autorewrite with Ztestbit; break_match; + try rewrite Z.testbit_neg_r with (n := n - w) by omega; + autorewrite with bool_congr; + f_equal; ring. + } { + replace a with (a mod 2 ^ w) by (auto using Z.mod_small). + apply Z.mod_pow2_bits_high. split; auto using in_eq; omega. + } + - rewrite nth_default_cons_S. + destruct limb_widths as [|w lw]. + * cbv [base_from_limb_widths]. + rewrite <-pow2_mod_bounded with (lw := nil); rewrite bounded_nil_iff in *; auto using in_cons. + rewrite sum_firstn_nil, !nth_default_nil, BaseSystemProofs.decode_base_nil, Z.shiftr_0_r. + apply nth_default_preserves_properties; intros; auto using in_cons. + f_equal; auto using in_cons. + * rewrite sum_firstn_succ_cons, nth_default_cons_S, base_from_limb_widths_cons, BaseSystemProofs.peel_decode. + fold (BaseSystem.mul_each (two_p w)). + rewrite <-BaseSystemProofs.mul_each_base, BaseSystemProofs.mul_each_rep. + rewrite two_p_correct, (Z.mul_comm (2 ^ w)). + rewrite <-Z.shiftl_mul_pow2 by auto using in_eq. + rewrite bounded_iff in *. + rewrite Z.shiftr_add_shiftl_high by first + [ pose proof (sum_firstn_nonnegative i lw); split; auto using in_eq; specialize_by auto using in_cons; omega + | specialize (H 0%nat); rewrite !nth_default_cons in H; omega ]. + rewrite IHus with (limb_widths := lw) by + (auto using in_cons; rewrite ?bounded_iff; intro j; specialize (H (S j)); + rewrite !nth_default_cons_S in H; assumption). + repeat f_equal; try ring. + Qed. + + Lemma nth_default_limb_widths_nonneg : forall i, 0 <= nth_default 0 limb_widths i. + Proof using Type*. + intros; apply nth_default_preserves_properties; auto; omega. + Qed. Hint Resolve nth_default_limb_widths_nonneg. + + Lemma decode_firstn_pow2_mod : forall us i, + (i <= length us)%nat -> + length us = length limb_widths -> + bounded limb_widths us -> + BaseSystem.decode' base (firstn i us) = Z.pow2_mod (BaseSystem.decode' base us) (sum_firstn limb_widths i). + Proof using Type*. + intros; induction i; + repeat match goal with + | |- _ => rewrite sum_firstn_0, BaseSystemProofs.decode_nil, Z.pow2_mod_0_r; reflexivity + | |- _ => progress distr_length + | |- _ => progress autorewrite with simpl_firstn + | |- _ => rewrite firstn_succ with (d := 0) + | |- _ => rewrite BaseSystemProofs.set_higher + | |- _ => rewrite nth_default_base + | |- _ => rewrite IHi + | |- _ => rewrite <-Z.lor_shiftl by (rewrite ?Z.pow2_mod_spec; try apply Z.mod_pos_bound; zero_bounds) + | |- appcontext[min ?x ?y] => (rewrite Nat.min_l by omega || rewrite Nat.min_r by omega) + | |- appcontext[2 ^ ?a * _] => rewrite (Z.mul_comm (2 ^ a)); rewrite <-Z.shiftl_mul_pow2 + | |- _ => solve [auto] + | |- _ => lia + end. + rewrite digit_select by assumption; apply Z.bits_inj'. + repeat match goal with + | |- _ => progress intros + | |- _ => progress autorewrite with Ztestbit + | |- _ => rewrite Z.testbit_pow2_mod by (omega || trivial) + | |- _ => break_if; try omega + | H : ?a < ?b |- appcontext[Z.testbit _ (?a - ?b)] => + rewrite (Z.testbit_neg_r _ (a-b)) by omega + | |- _ => reflexivity + | |- _ => solve [f_equal; ring] + | |- _ => rewrite sum_firstn_succ_default in *; + pose proof (nth_default_limb_widths_nonneg i); omega + end. + Qed. + + Lemma testbit_decode_firstn_high : forall us i n, + (i <= length us)%nat -> + length us = length limb_widths -> + bounded limb_widths us -> + sum_firstn limb_widths i <= n -> + Z.testbit (BaseSystem.decode base (firstn i us)) n = false. + Proof using Type*. + repeat match goal with + | |- _ => progress intros + | |- _ => progress autorewrite with Ztestbit + | |- _ => rewrite decode_firstn_pow2_mod + | |- _ => rewrite Z.testbit_pow2_mod + | |- _ => break_if + | |- _ => assumption + | |- _ => solve [auto] + | H : ?a <= ?b |- 0 <= ?b => assert (0 <= a) by (omega || auto); omega + end. + Qed. + + Lemma testbit_decode_high : forall us n, + length us = length limb_widths -> + bounded limb_widths us -> + sum_firstn limb_widths (length us) <= n -> + Z.testbit (BaseSystem.decode base us) n = false. + Proof using Type*. + intros. + erewrite <-(firstn_all _ us) by reflexivity. + auto using testbit_decode_firstn_high. + Qed. + + (** TODO: Figure out how to automate and clean up this proof *) + Lemma decode_nonneg : forall us, + length us = length limb_widths -> + bounded limb_widths us -> + 0 <= BaseSystem.decode base us. + Proof using Type*. + intros. + unfold bounded, BaseSystem.decode, BaseSystem.decode' in *; simpl in *. + pose 0 as zero. + assert (0 <= zero) by reflexivity. + replace base with (map (Z.mul (two_p zero)) base) + by (etransitivity; [ | apply map_id ]; apply map_ext; auto with zarith). + clearbody zero. + revert dependent zero. + generalize dependent limb_widths. + induction us as [|u us IHus]; intros [|w limb_widths'] ?? Hbounded ??; simpl in *; + try (reflexivity || congruence). + pose proof (Hbounded 0%nat) as Hbounded0. + pose proof (fun n => Hbounded (S n)) as HboundedS. + unfold nth_default, nth_error in Hbounded0. + unfold nth_default in HboundedS. + rewrite map_map. + unfold BaseSystem.accumulate at 1; simpl. + assert (0 < two_p zero) by (rewrite two_p_equiv; auto with zarith). + replace (map (fun x => two_p zero * (two_p w * x)) (base_from_limb_widths limb_widths')) with (map (Z.mul (two_p (zero + w))) (base_from_limb_widths limb_widths')) + by (apply map_ext; rewrite two_p_is_exp by auto with zarith omega; auto with zarith). + change 0 with (0 + 0) at 1. + apply Z.add_le_mono; simpl in *; auto with zarith. + Qed. + + Lemma decode_upper_bound : forall us, + length us = length limb_widths -> + bounded limb_widths us -> + 0 <= BaseSystem.decode base us < upper_bound limb_widths. + Proof using Type*. + cbv [upper_bound]; intros. + split. + { apply decode_nonneg; auto. } + { apply Z.testbit_false_bound; auto; intros. + rewrite testbit_decode_high; auto; + replace (length us) with (length limb_widths); try omega. } + Qed. + + Lemma decode_shift_app : forall us0 us1, (length (us0 ++ us1) <= length limb_widths)%nat -> + BaseSystem.decode base (us0 ++ us1) = (BaseSystem.decode (base_from_limb_widths (firstn (length us0) limb_widths)) us0) + ((BaseSystem.decode (base_from_limb_widths (skipn (length us0) limb_widths)) us1) << sum_firstn limb_widths (length us0)). + Proof using Type*. + unfold BaseSystem.decode; intros us0 us1 ?. + assert (0 <= sum_firstn limb_widths (length us0)) by auto using sum_firstn_nonnegative. + rewrite BaseSystemProofs.decode'_splice; autorewrite with push_firstn. + apply Z.add_cancel_l. + autorewrite with pull_base_from_limb_widths Zshift_to_pow zsimplify. + rewrite BaseSystemProofs.decode'_map_mul, two_p_correct; nia. + Qed. + + Lemma decode_shift : forall us u0, (length (u0 :: us) <= length limb_widths)%nat -> + BaseSystem.decode base (u0 :: us) = u0 + ((BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us) << (nth_default 0 limb_widths 0)). + Proof using Type*. + intros; etransitivity; [ apply (decode_shift_app (u0::nil)); assumption | ]. + transitivity (u0 * 1 + 0 + ((BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us) << (nth_default 0 limb_widths 0 + 0))); [ | autorewrite with zsimplify; reflexivity ]. + destruct limb_widths; distr_length; reflexivity. + Qed. + + Lemma upper_bound_nil : upper_bound nil = 1. + Proof using Type. reflexivity. Qed. + + Lemma upper_bound_cons x xs : 0 <= x -> 0 <= sum_firstn xs (length xs) -> upper_bound (x::xs) = 2^x * upper_bound xs. + Proof using Type. + intros Hx Hxs. + unfold upper_bound; simpl. + autorewrite with simpl_sum_firstn pull_Zpow. + reflexivity. + Qed. + + Lemma upper_bound_app xs ys : 0 <= sum_firstn xs (length xs) -> 0 <= sum_firstn ys (length ys) -> upper_bound (xs ++ ys) = upper_bound xs * upper_bound ys. + Proof using Type. + intros Hxs Hys. + unfold upper_bound; simpl. + autorewrite with distr_length simpl_sum_firstn pull_Zpow. + reflexivity. + Qed. + +End Pow2BaseProofs. +Hint Rewrite base_from_limb_widths_cons base_from_limb_widths_nil : push_base_from_limb_widths. +Hint Rewrite <- base_from_limb_widths_cons : pull_base_from_limb_widths. + +Hint Rewrite <- @firstn_base_from_limb_widths : push_base_from_limb_widths. +Hint Rewrite <- @firstn_base_from_limb_widths : pull_firstn. +Hint Rewrite @firstn_base_from_limb_widths : pull_base_from_limb_widths. +Hint Rewrite @firstn_base_from_limb_widths : push_firstn. +Hint Rewrite <- @skipn_base_from_limb_widths : push_base_from_limb_widths. +Hint Rewrite <- @skipn_base_from_limb_widths : pull_skipn. +Hint Rewrite @skipn_base_from_limb_widths : pull_base_from_limb_widths. +Hint Rewrite @skipn_base_from_limb_widths : push_skipn. + +Hint Rewrite @base_from_limb_widths_length : distr_length. +Hint Rewrite @upper_bound_nil @upper_bound_cons @upper_bound_app using solve [ eauto with znonzero ] : push_upper_bound. +Hint Rewrite <- @upper_bound_cons @upper_bound_app using solve [ eauto with znonzero ] : pull_upper_bound. + +Section UniformBase. + Context {width : Z} (limb_width_nonneg : 0 <= width). + Context (limb_widths : list Z) + (limb_widths_uniform : forall w, In w limb_widths -> w = width). + Local Notation base := (base_from_limb_widths limb_widths). + + Lemma bounded_uniform : forall us, (length us <= length limb_widths)%nat -> + (bounded limb_widths us <-> (forall u, In u us -> 0 <= u < 2 ^ width)). + Proof using Type*. + cbv [bounded]; split; intro A; intros. + + let G := fresh "G" in + match goal with H : In _ us |- _ => + eapply In_nth in H; destruct H as [? G]; destruct G as [? G]; + rewrite <-nth_default_eq in G; rewrite <-G end. + specialize (A x). + split; try eapply A. + eapply Z.lt_le_trans; try apply A. + apply nth_default_preserves_properties; [ | apply Z.pow_le_mono_r; omega ] . + intros; apply Z.eq_le_incl. + f_equal; auto. + + apply nth_default_preserves_properties_length_dep; + try solve [apply nth_default_preserves_properties; split; zero_bounds; rewrite limb_widths_uniform; auto || omega]. + intros; apply nth_default_preserves_properties_length_dep; try solve [intros; omega]. + let x := fresh "x" in intro x; intros; + replace x with width; try symmetry; auto. + Qed. + + Lemma uniform_limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w. + Proof using Type*. + intros. + replace w with width by (symmetry; auto). + assumption. + Qed. + + Lemma nth_default_uniform_base_full : forall i, + nth_default 0 limb_widths i = if lt_dec i (length limb_widths) + then width else 0. + Admitted. + + Lemma nth_default_uniform_base : forall i, (i < length limb_widths)%nat -> + nth_default 0 limb_widths i = width. + Proof using Type*. + intros; rewrite nth_default_uniform_base_full. + edestruct lt_dec; omega. + Qed. + + Lemma sum_firstn_uniform_base : forall i, (i <= length limb_widths)%nat -> + sum_firstn limb_widths i = Z.of_nat i * width. + Proof using limb_widths_uniform. + clear limb_width_nonneg. (* clear this before induction so we don't depend on this *) + induction limb_widths as [|x xs IHxs]; (intros [|i] ?); + simpl @length in *; + autorewrite with simpl_sum_firstn push_Zof_nat zsimplify; + try reflexivity; + try omega. + assert (x = width) by auto with datatypes; subst. + rewrite IHxs by auto with datatypes omega; omega. + Qed. + + Lemma sum_firstn_uniform_base_strong : forall i, (length limb_widths <= i)%nat -> + sum_firstn limb_widths i = Z.of_nat (length limb_widths) * width. + Proof using limb_widths_uniform. + intros; rewrite sum_firstn_all, sum_firstn_uniform_base by omega; reflexivity. + Qed. + + Lemma upper_bound_uniform : upper_bound limb_widths = 2^(Z.of_nat (length limb_widths) * width). + Proof using limb_widths_uniform. + unfold upper_bound; rewrite sum_firstn_uniform_base_strong by omega; reflexivity. + Qed. + + (* TODO : move *) + Lemma decode_truncate_base : forall us bs, BaseSystem.decode bs us = BaseSystem.decode (firstn (length us) bs) us. + Proof using Type. + clear. + induction us; intros. + + rewrite !BaseSystemProofs.decode_nil; reflexivity. + + distr_length. + destruct bs. + - rewrite firstn_nil, !BaseSystemProofs.decode_base_nil; reflexivity. + - rewrite firstn_cons, !BaseSystemProofs.peel_decode. + f_equal. + apply IHus. + Qed. + + (* TODO : move *) + Lemma tl_repeat : forall {A} xs n (x : A), (forall y, In y xs -> y = x) -> + (n < length xs)%nat -> + firstn n xs = firstn n (tl xs). + Proof using Type. + intros. + erewrite (repeat_spec_eq xs) by first [ eassumption | reflexivity ]. + rewrite ListUtil.tl_repeat. + autorewrite with push_firstn. + apply f_equal; omega *. + Qed. + + Lemma decode_tl_base : forall us, (length us < length limb_widths)%nat -> + BaseSystem.decode base us = BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us. + Proof using limb_widths_uniform. + intros. + match goal with |- BaseSystem.decode ?b1 _ = BaseSystem.decode ?b2 _ => + rewrite (decode_truncate_base _ b1), (decode_truncate_base _ b2) end. + rewrite !firstn_base_from_limb_widths. + do 2 f_equal. + eauto using tl_repeat. + Qed. + + Lemma decode_shift_uniform_tl : forall us u0, (length (u0 :: us) <= length limb_widths)%nat -> + BaseSystem.decode base (u0 :: us) = u0 + ((BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us) << width). + Proof using Type*. + intros. + rewrite <- (nth_default_uniform_base 0) by distr_length. + rewrite decode_shift by auto using uniform_limb_widths_nonneg. + reflexivity. + Qed. + + Lemma decode_shift_uniform_app : forall us0 us1, (length (us0 ++ us1) <= length limb_widths)%nat -> + BaseSystem.decode base (us0 ++ us1) = (BaseSystem.decode (base_from_limb_widths (firstn (length us0) limb_widths)) us0) + ((BaseSystem.decode (base_from_limb_widths (skipn (length us0) limb_widths)) us1) << (Z.of_nat (length us0) * width)). + Proof using Type*. + intros. + rewrite <- sum_firstn_uniform_base by (distr_length; omega). + rewrite decode_shift_app by auto using uniform_limb_widths_nonneg. + reflexivity. + Qed. +End UniformBase.
\ No newline at end of file diff --git a/src/LegacyArithmetic/README.md b/src/LegacyArithmetic/README.md new file mode 100644 index 000000000..b0137664c --- /dev/null +++ b/src/LegacyArithmetic/README.md @@ -0,0 +1,3 @@ +The development of this directory predates `src/Arithmetic`, and should probably +be considered to be superseded by it. The p256 Montgomery reduction for +a 128-bit cpu synthesized here still works. diff --git a/src/Tactics/VerdiTactics.v b/src/LegacyArithmetic/VerdiTactics.v index 546acf10e..4060fc675 100644 --- a/src/Tactics/VerdiTactics.v +++ b/src/LegacyArithmetic/VerdiTactics.v @@ -26,17 +26,17 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) -Ltac subst_max := +Ltac subst_max := idtac "VerdiTactics is deprecated in fiat-crypto"; repeat match goal with | [ H : ?X = _ |- _ ] => subst X | [H : _ = ?X |- _] => subst X end. -Ltac inv H := inversion H; subst_max. -Ltac invc H := inv H; clear H. -Ltac invcs H := invc H; simpl in *. +Ltac inv H := idtac "VerdiTactics is deprecated in fiat-crypto"; inversion H; subst_max. +Ltac invc H := idtac "VerdiTactics is deprecated in fiat-crypto"; inv H; clear H. +Ltac invcs H := idtac "VerdiTactics is deprecated in fiat-crypto"; invc H; simpl in *. -Ltac break_if := +Ltac break_if := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ |- context [ if ?X then _ else _ ] ] => match type of X with @@ -50,7 +50,7 @@ Ltac break_if := end end. -Ltac break_match_hyp := +Ltac break_match_hyp := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : context [ match ?X with _ => _ end ] |- _] => match type of X with @@ -59,7 +59,7 @@ Ltac break_match_hyp := end end. -Ltac break_match_goal := +Ltac break_match_goal := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ |- context [ match ?X with _ => _ end ] ] => match type of X with @@ -68,66 +68,66 @@ Ltac break_match_goal := end end. -Ltac break_match := break_match_goal || break_match_hyp. +Ltac break_match := idtac "VerdiTactics is deprecated in fiat-crypto"; break_match_goal || break_match_hyp. -Ltac break_exists := +Ltac break_exists := idtac "VerdiTactics is deprecated in fiat-crypto"; repeat match goal with | [H : exists _, _ |- _ ] => destruct H end. -Ltac break_exists_exists := +Ltac break_exists_exists := idtac "VerdiTactics is deprecated in fiat-crypto"; repeat match goal with | H:exists _, _ |- _ => let x := fresh "x" in destruct H as [x]; exists x end. -Ltac break_and := +Ltac break_and := idtac "VerdiTactics is deprecated in fiat-crypto"; repeat match goal with | [H : _ /\ _ |- _ ] => destruct H end. -Ltac solve_by_inversion' tac := +Ltac solve_by_inversion' tac := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [H : _ |- _] => solve [inv H; tac] end. -Ltac solve_by_inversion := solve_by_inversion' auto. +Ltac solve_by_inversion := idtac "VerdiTactics is deprecated in fiat-crypto"; solve_by_inversion' auto. -Ltac apply_fun f H:= +Ltac apply_fun f H:= idtac "VerdiTactics is deprecated in fiat-crypto"; match type of H with | ?X = ?Y => assert (f X = f Y) end. -Ltac conclude H tac := +Ltac conclude H tac := idtac "VerdiTactics is deprecated in fiat-crypto"; (let H' := fresh in match type of H with | ?P -> _ => assert P as H' by (tac) end; specialize (H H'); clear H'). -Ltac concludes := +Ltac concludes := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?P -> _ |- _ ] => conclude H auto end. -Ltac forward H := +Ltac forward H := idtac "VerdiTactics is deprecated in fiat-crypto"; let H' := fresh in match type of H with | ?P -> _ => assert P as H' end. -Ltac forwards := +Ltac forwards := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?P -> _ |- _ ] => forward H end. -Ltac find_contradiction := +Ltac find_contradiction := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?X = _, H' : ?X = _ |- _ ] => rewrite H in H'; solve_by_inversion end. -Ltac find_rewrite := +Ltac find_rewrite := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?X _ _ _ _ = _, H' : ?X _ _ _ _ = _ |- _ ] => rewrite H in H' | [ H : ?X = _, H' : ?X = _ |- _ ] => rewrite H in H' @@ -135,31 +135,31 @@ Ltac find_rewrite := | [ H : ?X = _ |- context [ ?X ] ] => rewrite H end. -Ltac find_rewrite_lem lem := +Ltac find_rewrite_lem lem := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _ ] => rewrite lem in H; [idtac] end. -Ltac find_rewrite_lem_by lem t := +Ltac find_rewrite_lem_by lem t := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _ ] => rewrite lem in H by t end. -Ltac find_erewrite_lem lem := +Ltac find_erewrite_lem lem := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _] => erewrite lem in H by eauto end. -Ltac find_reverse_rewrite := +Ltac find_reverse_rewrite := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ = ?X _ _ _ _, H' : ?X _ _ _ _ = _ |- _ ] => rewrite <- H in H' | [ H : _ = ?X, H' : context [ ?X ] |- _ ] => rewrite <- H in H' | [ H : _ = ?X |- context [ ?X ] ] => rewrite <- H end. -Ltac find_inversion := +Ltac find_inversion := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?X _ _ _ _ _ _ = ?X _ _ _ _ _ _ |- _ ] => invc H | [ H : ?X _ _ _ _ _ = ?X _ _ _ _ _ |- _ ] => invc H @@ -169,7 +169,7 @@ Ltac find_inversion := | [ H : ?X _ = ?X _ |- _ ] => invc H end. -Ltac prove_eq := +Ltac prove_eq := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?X ?x1 ?x2 ?x3 = ?X ?y1 ?y2 ?y3 |- _ ] => assert (x1 = y1) by congruence; @@ -185,75 +185,75 @@ Ltac prove_eq := clear H end. -Ltac tuple_inversion := +Ltac tuple_inversion := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : (_, _, _, _) = (_, _, _, _) |- _ ] => invc H | [ H : (_, _, _) = (_, _, _) |- _ ] => invc H | [ H : (_, _) = (_, _) |- _ ] => invc H end. -Ltac f_apply H f := +Ltac f_apply H f := idtac "VerdiTactics is deprecated in fiat-crypto"; match type of H with | ?X = ?Y => assert (f X = f Y) by (rewrite H; auto) end. -Ltac break_let := +Ltac break_let := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : context [ (let (_,_) := ?X in _) ] |- _ ] => destruct X eqn:? | [ |- context [ (let (_,_) := ?X in _) ] ] => destruct X eqn:? end. -Ltac break_or_hyp := +Ltac break_or_hyp := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ \/ _ |- _ ] => invc H end. -Ltac copy_apply lem H := +Ltac copy_apply lem H := idtac "VerdiTactics is deprecated in fiat-crypto"; let x := fresh in pose proof H as x; apply lem in x. -Ltac copy_eapply lem H := +Ltac copy_eapply lem H := idtac "VerdiTactics is deprecated in fiat-crypto"; let x := fresh in pose proof H as x; eapply lem in x. -Ltac conclude_using tac := +Ltac conclude_using tac := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?P -> _ |- _ ] => conclude H tac end. -Ltac find_higher_order_rewrite := +Ltac find_higher_order_rewrite := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ = _ |- _ ] => rewrite H in * | [ H : forall _, _ = _ |- _ ] => rewrite H in * | [ H : forall _ _, _ = _ |- _ ] => rewrite H in * end. -Ltac find_reverse_higher_order_rewrite := +Ltac find_reverse_higher_order_rewrite := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ = _ |- _ ] => rewrite <- H in * | [ H : forall _, _ = _ |- _ ] => rewrite <- H in * | [ H : forall _ _, _ = _ |- _ ] => rewrite <- H in * end. -Ltac clean := +Ltac clean := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?X = ?X |- _ ] => clear H end. -Ltac find_apply_hyp_goal := +Ltac find_apply_hyp_goal := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _ ] => solve [apply H] end. -Ltac find_copy_apply_lem_hyp lem := +Ltac find_copy_apply_lem_hyp lem := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _ ] => copy_apply lem H end. -Ltac find_apply_hyp_hyp := +Ltac find_apply_hyp_hyp := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : forall _, _ -> _, H' : _ |- _ ] => @@ -262,7 +262,7 @@ Ltac find_apply_hyp_hyp := apply H in H'; auto; [idtac] end. -Ltac find_copy_apply_hyp_hyp := +Ltac find_copy_apply_hyp_hyp := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : forall _, _ -> _, H' : _ |- _ ] => @@ -271,17 +271,17 @@ Ltac find_copy_apply_hyp_hyp := copy_apply H H'; auto; [idtac] end. -Ltac find_apply_lem_hyp lem := +Ltac find_apply_lem_hyp lem := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _ ] => apply lem in H end. -Ltac find_eapply_lem_hyp lem := +Ltac find_eapply_lem_hyp lem := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _ ] => eapply lem in H end. -Ltac insterU H := +Ltac insterU H := idtac "VerdiTactics is deprecated in fiat-crypto"; match type of H with | forall _ : ?T, _ => let x := fresh "x" in @@ -290,18 +290,18 @@ Ltac insterU H := clear x; specialize (H x') end. -Ltac find_insterU := +Ltac find_insterU := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : forall _, _ |- _ ] => insterU H end. -Ltac eapply_prop P := +Ltac eapply_prop P := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | H : P _ |- _ => eapply H end. -Ltac isVar t := +Ltac isVar t := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | v : _ |- _ => match t with @@ -309,15 +309,15 @@ Ltac isVar t := end end. -Ltac remGen t := +Ltac remGen t := idtac "VerdiTactics is deprecated in fiat-crypto"; let x := fresh in let H := fresh in remember t as x eqn:H; generalize dependent H. -Ltac remGenIfNotVar t := first [isVar t| remGen t]. +Ltac remGenIfNotVar t := idtac "VerdiTactics is deprecated in fiat-crypto"; first [isVar t| remGen t]. -Ltac rememberNonVars H := +Ltac rememberNonVars H := idtac "VerdiTactics is deprecated in fiat-crypto"; match type of H with | _ ?a ?b ?c ?d ?e => remGenIfNotVar a; @@ -341,7 +341,7 @@ Ltac rememberNonVars H := remGenIfNotVar a end. -Ltac generalizeEverythingElse H := +Ltac generalizeEverythingElse H := idtac "VerdiTactics is deprecated in fiat-crypto"; repeat match goal with | [ x : ?T |- _ ] => first [ @@ -354,48 +354,48 @@ Ltac generalizeEverythingElse H := revert x] end. -Ltac prep_induction H := +Ltac prep_induction H := idtac "VerdiTactics is deprecated in fiat-crypto"; rememberNonVars H; generalizeEverythingElse H. -Ltac econcludes := +Ltac econcludes := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?P -> _ |- _ ] => conclude H eauto end. -Ltac find_copy_eapply_lem_hyp lem := +Ltac find_copy_eapply_lem_hyp lem := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : _ |- _ ] => copy_eapply lem H end. -Ltac apply_prop_hyp P Q := +Ltac apply_prop_hyp P Q := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : context [ P ], H' : context [ Q ] |- _ ] => apply H in H' end. -Ltac eapply_prop_hyp P Q := +Ltac eapply_prop_hyp P Q := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : context [ P ], H' : context [ Q ] |- _ ] => eapply H in H' end. -Ltac copy_eapply_prop_hyp P Q := +Ltac copy_eapply_prop_hyp P Q := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : context [ P ], H' : context [ Q ] |- _ ] => copy_eapply H H' end. -Ltac find_false := +Ltac find_false := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | H : _ -> False |- _ => exfalso; apply H end. -Ltac injc H := +Ltac injc H := idtac "VerdiTactics is deprecated in fiat-crypto"; injection H; clear H; intro; subst_max. -Ltac find_injection := +Ltac find_injection := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : ?X _ _ _ _ _ _ = ?X _ _ _ _ _ _ |- _ ] => injc H | [ H : ?X _ _ _ _ _ = ?X _ _ _ _ _ |- _ ] => injc H @@ -405,10 +405,10 @@ Ltac find_injection := | [ H : ?X _ = ?X _ |- _ ] => injc H end. -Ltac aggresive_rewrite_goal := +Ltac aggresive_rewrite_goal := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with H : _ |- _ => rewrite H end. -Ltac break_exists_name x := +Ltac break_exists_name x := idtac "VerdiTactics is deprecated in fiat-crypto"; match goal with | [ H : exists _, _ |- _ ] => destruct H as [x H] end. diff --git a/src/ModularArithmetic/ZBounded.v b/src/LegacyArithmetic/ZBounded.v index bccbf7428..bccbf7428 100644 --- a/src/ModularArithmetic/ZBounded.v +++ b/src/LegacyArithmetic/ZBounded.v diff --git a/src/ModularArithmetic/ZBoundedZ.v b/src/LegacyArithmetic/ZBoundedZ.v index fd004451b..fef654f47 100644 --- a/src/ModularArithmetic/ZBoundedZ.v +++ b/src/LegacyArithmetic/ZBoundedZ.v @@ -1,6 +1,6 @@ (*** ℤ can be a bounded ℤ-Like type *) Require Import Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Crypto.ModularArithmetic.ZBounded. +Require Import Crypto.LegacyArithmetic.ZBounded. Require Import Crypto.Util.ZUtil. Require Import Crypto.Util.Tactics.BreakMatch. Require Import Crypto.Util.LetIn. diff --git a/src/ModularArithmetic/Conversion.v b/src/ModularArithmetic/Conversion.v deleted file mode 100644 index 3e8436f43..000000000 --- a/src/ModularArithmetic/Conversion.v +++ /dev/null @@ -1,318 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Coq.Lists.List. -Require Import Coq.funind.Recdef. -Require Import Crypto.Util.ListUtil Crypto.Util.ZUtil Crypto.Util.NatUtil. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.Tactics.UniquePose. -Require Import Crypto.Util.Tactics.SpecializeBy. -Require Import Crypto.Util.Tactics.SubstLet. -Require Import Crypto.Util.Tactics.Forward. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs Crypto.BaseSystemProofs. -Require Import Crypto.Util.Notations. -Require Export Crypto.Util.FixCoqMistakes. -Require Crypto.BaseSystem. -Local Open Scope Z_scope. - -Section ConversionHelper. - Local Hint Resolve in_eq in_cons. - - (* concatenates first n bits of a with all bits of b *) - Definition concat_bits n a b := Z.lor (Z.pow2_mod a n) (b << n). - - Lemma concat_bits_spec : forall a b n i, 0 <= n -> - Z.testbit (concat_bits n a b) i = - if Z_lt_dec i n then Z.testbit a i else Z.testbit b (i - n). - Proof. - repeat match goal with - | |- _ => progress cbv [concat_bits]; intros - | |- _ => progress autorewrite with Ztestbit - | |- _ => rewrite Z.testbit_pow2_mod by omega - | |- _ => rewrite Z.testbit_neg_r by omega - | |- _ => break_if - | |- appcontext [Z.testbit (?a << ?b) ?i] => destruct (Z_le_dec 0 i) - | |- (?a || ?b)%bool = ?a => replace b with false - | |- _ => reflexivity - end. - Qed. - - Definition update_by_concat_bits num_low_bits bits x := concat_bits num_low_bits x bits. - -End ConversionHelper. - -Section Conversion. - Context {limb_widthsA} (limb_widthsA_nonneg : forall w, In w limb_widthsA -> 0 <= w) - {limb_widthsB} (limb_widthsB_nonneg : forall w, In w limb_widthsB -> 0 <= w). - Local Notation bitsIn lw := (sum_firstn lw (length lw)). - Context (bits_fit : bitsIn limb_widthsA <= bitsIn limb_widthsB). - Local Notation decodeA := (BaseSystem.decode (base_from_limb_widths limb_widthsA)). - Local Notation decodeB := (BaseSystem.decode (base_from_limb_widths limb_widthsB)). - Local Notation "u # i" := (nth_default 0 u i). - Local Hint Resolve in_eq in_cons nth_default_limb_widths_nonneg sum_firstn_limb_widths_nonneg Nat2Z.is_nonneg. - Local Opaque bounded. - - Function convert' inp i out - {measure (fun x => Z.to_nat ((bitsIn limb_widthsA) - Z.of_nat x)) i}:= - if Z_le_dec (bitsIn limb_widthsA) (Z.of_nat i) - then out - else - let digitA := digit_index limb_widthsA (Z.of_nat i) in - let digitB := digit_index limb_widthsB (Z.of_nat i) in - let indexA := bit_index limb_widthsA (Z.of_nat i) in - let indexB := bit_index limb_widthsB (Z.of_nat i) in - let dist := Z.min ((limb_widthsA # digitA) - indexA) ((limb_widthsB # digitB) - indexB) in - let bitsA := Z.pow2_mod ((inp # digitA) >> indexA) dist in - convert' inp (i + Z.to_nat dist)%nat (update_nth digitB (update_by_concat_bits indexB bitsA) out). - Proof. - generalize limb_widthsA_nonneg; intros _. (* don't drop this from the proof in 8.4 *) - generalize limb_widthsB_nonneg; intros _. (* don't drop this from the proof in 8.4 *) - repeat match goal with - | |- _ => progress intros - | |- appcontext [bit_index (Z.of_nat ?i)] => - unique pose proof (Nat2Z.is_nonneg i) - | H : forall x : Z, In x ?lw -> 0 <= x |- appcontext [bit_index ?lw ?i] => - unique pose proof (bit_index_not_done lw i) - | H : forall x : Z, In x ?lw -> 0 <= x |- appcontext [bit_index ?lw ?i] => - unique assert (0 <= i < bitsIn lw -> i + ((lw # digit_index lw i) - bit_index lw i) <= bitsIn lw) by auto using rem_bits_in_digit_le_rem_bits - | |- _ => rewrite Z2Nat.id - | |- _ => rewrite Nat2Z.inj_add - | |- (Z.to_nat _ < Z.to_nat _)%nat => apply Z2Nat.inj_lt - | |- (?a - _ < ?a - _) => apply Z.sub_lt_mono_l - | |- appcontext [Z.min ?a ?b] => unique assert (0 < Z.min a b) by (specialize_by lia; lia) - | |- _ => lia - end. - Defined. - - Definition convert'_invariant inp i out := - length out = length limb_widthsB - /\ bounded limb_widthsB out - /\ Z.of_nat i <= bitsIn limb_widthsA - /\ forall n, Z.testbit (decodeB out) n = if Z_lt_dec n (Z.of_nat i) then Z.testbit (decodeA inp) n else false. - - Ltac subst_lia := subst_let; subst; lia. - - Lemma convert'_bounded_step : forall inp i out, - bounded limb_widthsB out -> - let digitA := digit_index limb_widthsA (Z.of_nat i) in - let digitB := digit_index limb_widthsB (Z.of_nat i) in - let indexA := bit_index limb_widthsA (Z.of_nat i) in - let indexB := bit_index limb_widthsB (Z.of_nat i) in - let dist := Z.min ((limb_widthsA # digitA) - indexA) - ((limb_widthsB # digitB) - indexB) in - let bitsA := Z.pow2_mod ((inp # digitA) >> indexA) dist in - 0 < dist -> - bounded limb_widthsB (update_nth digitB (update_by_concat_bits indexB bitsA) out). - Proof using limb_widthsB_nonneg. - repeat match goal with - | |- _ => progress intros - | |- _ => progress autorewrite with Ztestbit - | |- _ => rewrite update_nth_nth_default_full - | |- _ => rewrite Z.testbit_pow2_mod - | |- _ => break_if - | |- _ => progress cbv [update_by_concat_bits]; - rewrite concat_bits_spec by (apply bit_index_nonneg; auto using Nat2Z.is_nonneg) - | |- bounded _ _ => apply pow2_mod_bounded_iff - | |- Z.pow2_mod _ _ = _ => apply Z.bits_inj' - | |- false = Z.testbit _ _ => symmetry - | x := _ |- Z.testbit ?x _ = _ => subst x - | |- Z.testbit _ _ = false => eapply testbit_bounded_high; eauto; lia - | |- _ => solve [auto] - | |- _ => subst_lia - end. - Qed. - - Lemma convert'_index_step : forall inp i out, - bounded limb_widthsB out -> - let digitA := digit_index limb_widthsA (Z.of_nat i) in - let digitB := digit_index limb_widthsB (Z.of_nat i) in - let indexA := bit_index limb_widthsA (Z.of_nat i) in - let indexB := bit_index limb_widthsB (Z.of_nat i) in - let dist := Z.min ((limb_widthsA # digitA) - indexA) - ((limb_widthsB # digitB) - indexB) in - let bitsA := Z.pow2_mod ((inp # digitA) >> indexA) dist in - 0 < dist -> - Z.of_nat i < bitsIn limb_widthsA -> - Z.of_nat i + dist <= bitsIn limb_widthsA. - Proof using limb_widthsA_nonneg. - pose proof (rem_bits_in_digit_le_rem_bits limb_widthsA). - pose proof (rem_bits_in_digit_le_rem_bits limb_widthsA). - repeat match goal with - | |- _ => progress intros - | H : forall x : Z, In x ?lw -> x = ?y, H0 : 0 < ?y |- _ => - unique pose proof (uniform_limb_widths_nonneg H0 lw H) - | |- _ => progress specialize_by assumption - | H : _ /\ _ |- _ => destruct H - | |- _ => break_if - | |- _ => split - | a := digit_index _ ?i, H : forall x, 0 <= x < bitsIn _ -> _ |- _ => specialize (H i); forward H - | |- _ => subst_lia - | |- _ => apply bit_index_pos_iff; auto - | |- _ => apply Nat2Z.is_nonneg - end. - Qed. - - Lemma convert'_invariant_step : forall inp i out, - length inp = length limb_widthsA -> - bounded limb_widthsA inp -> - convert'_invariant inp i out -> - let digitA := digit_index limb_widthsA (Z.of_nat i) in - let digitB := digit_index limb_widthsB (Z.of_nat i) in - let indexA := bit_index limb_widthsA (Z.of_nat i) in - let indexB := bit_index limb_widthsB (Z.of_nat i) in - let dist := Z.min ((limb_widthsA # digitA) - indexA) - ((limb_widthsB # digitB) - indexB) in - let bitsA := Z.pow2_mod ((inp # digitA) >> indexA) dist in - 0 < dist -> - Z.of_nat i < bitsIn limb_widthsA -> - convert'_invariant inp (i + Z.to_nat dist)%nat - (update_nth digitB (update_by_concat_bits indexB bitsA) out). - Proof using Type*. - Time - repeat match goal with - | |- _ => progress intros; cbv [convert'_invariant] in * - | |- _ => progress autorewrite with Ztestbit - | H : forall x, In x ?lw -> 0 <= x |- appcontext[digit_index ?lw ?i] => - unique pose proof (digit_index_lt_length lw H i) - | |- _ => rewrite Nat2Z.inj_add - | |- _ => rewrite Z2Nat.id in * - | H : forall n, Z.testbit (decodeB _) n = _ |- Z.testbit (decodeB _) ?n = _ => - specialize (H n) - | H0 : ?n < ?i, H1 : ?n < ?i + ?d, - H : Z.testbit (decodeB _) ?n = Z.testbit (decodeA _) ?n |- _ = Z.testbit (decodeA _) ?n => - rewrite <-H - | H : _ /\ _ |- _ => destruct H - | |- _ => break_if - | |- _ => split - | |- _ => rewrite testbit_decode_full - | |- _ => rewrite update_nth_nth_default_full - | |- _ => rewrite nth_default_out_of_bounds by omega - | H : ~ (0 <= ?n ) |- appcontext[Z.testbit ?a ?n] => rewrite (Z.testbit_neg_r a n) by omega - | |- _ => progress cbv [update_by_concat_bits]; - rewrite concat_bits_spec by (apply bit_index_nonneg; auto using Nat2Z.is_nonneg) - | |- _ => solve [distr_length] - | |- _ => eapply convert'_bounded_step; solve [auto] - | |- _ => etransitivity; [ | eapply convert'_index_step]; subst_let; eauto; lia - | H : digit_index limb_widthsB ?i = digit_index limb_widthsB ?j |- _ => - unique assert (digit_index limb_widthsA i = digit_index limb_widthsA j) by - (symmetry; apply same_digit; assumption || lia); - pose proof (same_digit_bit_index_sub limb_widthsA j i) as X; - forward X; [ | lia | lia | lia ] - | d := digit_index ?lw ?j, - H : digit_index ?lw ?i <> ?d |- _ => - exfalso; apply H; symmetry; apply same_digit; assumption || subst_lia - | d := digit_index ?lw ?j, - H : digit_index ?lw ?i = ?d |- _ => - let X := fresh "H" in - ((pose proof (same_digit_bit_index_sub lw i j) as X; - forward X; [ subst_let | subst_lia | lia | lia ]) || - (pose proof (same_digit_bit_index_sub lw j i) as X; - forward X; [ subst_let | subst_lia | lia | lia ])) - | |- Z.testbit _ (bit_index ?lw _ - bit_index ?lw ?i + _) = false => - apply (@testbit_bounded_high limb_widthsA); auto; - rewrite (same_digit_bit_index_sub) by subst_lia; - rewrite <-(split_index_eqn limb_widthsA i) at 2 by lia - | |- ?lw # ?b <= ?a - ((sum_firstn ?lw ?b) + ?c) + ?c => replace (a - (sum_firstn lw b + c) + c) with (a - sum_firstn lw b) by ring; apply Z.le_add_le_sub_r - | |- (?lw # ?n) + sum_firstn ?lw ?n <= _ => - rewrite <-sum_firstn_succ_default; transitivity (bitsIn lw); [ | lia]; - apply sum_firstn_prefix_le; auto; lia - | |- _ => lia - | |- _ => assumption - | |- _ => solve [auto] - | |- _ => rewrite <-testbit_decode by (assumption || lia || auto); assumption - | |- _ => repeat (f_equal; try congruence); lia - end. - Qed. - - Lemma convert'_invariant_holds : forall inp i out, - length inp = length limb_widthsA -> - bounded limb_widthsA inp -> - convert'_invariant inp i out -> - convert'_invariant inp (Z.to_nat (bitsIn limb_widthsA)) (convert' inp i out). - Proof using Type. - intros until 2; functional induction (convert' inp i out); - repeat match goal with - | |- _ => progress intros - | H : forall x : Z, In x ?lw -> 0 <= x |- appcontext [bit_index ?lw ?i] => - unique pose proof (bit_index_not_done lw i) - | H : convert'_invariant _ _ _ |- convert'_invariant _ _ (convert' _ _ _) => - eapply convert'_invariant_step in H; solve [auto; specialize_by lia; lia] - | H : convert'_invariant _ _ ?out |- convert'_invariant _ _ ?out => progress cbv [convert'_invariant] in * - | H : _ /\ _ |- _ => destruct H - | |- _ => rewrite Z2Nat.id - | |- _ => split - | |- _ => assumption - | |- _ => lia - | |- _ => solve [eauto] - | |- _ => replace (bitsIn limb_widthsA) with (Z.of_nat i) by (apply Z.le_antisymm; assumption) - end. - Qed. - - Definition convert us := convert' us 0 (BaseSystem.zeros (length limb_widthsB)). - - Lemma convert_correct : forall us, length us = length limb_widthsA -> - bounded limb_widthsA us -> - decodeA us = decodeB (convert us). - Proof using Type. - repeat match goal with - | |- _ => progress intros - | |- _ => progress cbv [convert convert'_invariant] in * - | |- _ => progress change (Z.of_nat 0) with 0 in * - | |- _ => progress rewrite ?length_zeros, ?zeros_rep, ?Z.testbit_0_l - | H : length _ = length limb_widthsA |- _ => rewrite H - | |- _ => rewrite Z.testbit_neg_r by omega - | |- _ => rewrite nth_default_zeros - | |- _ => break_if - | |- _ => split - | H : _ /\ _ |- _ => destruct H - | H : forall n, Z.testbit ?x n = _ |- _ = ?x => apply Z.bits_inj'; intros; rewrite H - | |- _ = decodeB (convert' ?a ?b ?c) => edestruct (convert'_invariant_holds a b c) - | |- _ => apply testbit_decode_high - | |- _ => assumption - | |- _ => reflexivity - | |- _ => lia - | |- _ => solve [auto using sum_firstn_limb_widths_nonneg] - | |- _ => solve [apply nth_default_preserves_properties; auto; lia] - | |- _ => rewrite Z2Nat.id in * - | |- bounded _ _ => apply bounded_iff - | |- 0 < 2 ^ _ => zero_bounds - end. - Qed. - - (* This is part of convert'_invariant, but proving it separately strips preconditions *) - Lemma convert'_bounded : forall inp i out, - bounded limb_widthsB out -> - bounded limb_widthsB (convert' inp i out). - Proof using Type. - intros; functional induction (convert' inp i out); auto. - apply IHl. - apply convert'_bounded_step; auto. - clear IHl. - pose proof (bit_index_not_done limb_widthsA (Z.of_nat i)). - pose proof (bit_index_not_done limb_widthsB (Z.of_nat i)). - specialize_by lia. - lia. - Qed. - - Lemma convert_bounded : forall us, bounded limb_widthsB (convert us). - Proof using Type. - intros; apply convert'_bounded. - apply bounded_iff; intros. - rewrite nth_default_zeros. - split; zero_bounds. - Qed. - - (* This is part of convert'_invariant, but proving it separately strips preconditions *) - Lemma length_convert' : forall inp i out, - length (convert' inp i out) = length out. - Proof using Type. - intros; functional induction (convert' inp i out); distr_length. - Qed. - - Lemma length_convert : forall us, length (convert us) = length limb_widthsB. - Proof using Type. - cbv [convert]; intros. - rewrite length_convert', length_zeros. - reflexivity. - Qed. -End Conversion. diff --git a/src/ModularArithmetic/ExtPow2BaseMulProofs.v b/src/ModularArithmetic/ExtPow2BaseMulProofs.v deleted file mode 100644 index 38e9cf634..000000000 --- a/src/ModularArithmetic/ExtPow2BaseMulProofs.v +++ /dev/null @@ -1,34 +0,0 @@ -Require Import Coq.ZArith.ZArith Coq.Lists.List. -Require Import Crypto.BaseSystem. -Require Import Crypto.BaseSystemProofs. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs. -Require Import Crypto.ModularArithmetic.ExtendedBaseVector. -Require Import Crypto.Util.ListUtil. - -Local Open Scope Z_scope. - -Section ext_mul. - Context (limb_widths : list Z) - (limb_widths_nonnegative : forall x, In x limb_widths -> 0 <= x). - Local Notation k := (sum_firstn limb_widths (length limb_widths)). - Local Notation base := (base_from_limb_widths limb_widths). - Context (bv : BaseVector base) - (limb_widths_match_modulus : forall i j, - (i < length limb_widths)%nat -> - (j < length limb_widths)%nat -> - (i + j >= length limb_widths)%nat -> - let w_sum := sum_firstn limb_widths in - k + w_sum (i + j - length limb_widths)%nat <= w_sum i + w_sum j). - - Local Hint Resolve firstn_us_base_ext_base ExtBaseVector bv. - - Lemma mul_rep_extended : forall (us vs : BaseSystem.digits), - (length us <= length base)%nat -> - (length vs <= length base)%nat -> - (BaseSystem.decode base us) * (BaseSystem.decode base vs) = BaseSystem.decode (ext_base limb_widths) (BaseSystem.mul (ext_base limb_widths) us vs). - Proof using Type*. - intros; apply mul_rep_two_base; auto; - distr_length. - Qed. -End ext_mul. diff --git a/src/ModularArithmetic/ExtendedBaseVector.v b/src/ModularArithmetic/ExtendedBaseVector.v deleted file mode 100644 index 2236461ce..000000000 --- a/src/ModularArithmetic/ExtendedBaseVector.v +++ /dev/null @@ -1,200 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. -Require Import Coq.Lists.List. -Require Import Crypto.Util.ListUtil Crypto.Util.CaseUtil Crypto.Util.ZUtil. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs. -Require Import Crypto.BaseSystemProofs. -Require Crypto.BaseSystem. -Local Open Scope Z_scope. - -Section ExtendedBaseVector. - Context (limb_widths : list Z) - (limb_widths_nonnegative : forall x, In x limb_widths -> 0 <= x). - Local Notation k := (sum_firstn limb_widths (length limb_widths)). - Local Notation base := (base_from_limb_widths limb_widths). - - (* This section defines a new BaseVector that has double the length of the BaseVector - * used to construct [params]. The coefficients of the new vector are as follows: - * - * ext_base[i] = if (i < length base) then base[i] else 2^k * base[i] - * - * The purpose of this construction is that it allows us to multiply numbers expressed - * using [base], obtaining a number expressed using [ext_base]. (Numbers are "expressed" as - * vectors of digits; the value of a digit vector is obtained by doing a dot product with - * the base vector.) So if x, y are digit vectors: - * - * (x \dot base) * (y \dot base) = (z \dot ext_base) - * - * Then we can separate z into its first and second halves: - * - * (z \dot ext_base) = (z1 \dot base) + (2 ^ k) * (z2 \dot base) - * - * Now, if we want to reduce the product modulo 2 ^ k - c: - * - * (z \dot ext_base) mod (2^k-c)= (z1 \dot base) + (2 ^ k) * (z2 \dot base) mod (2^k-c) - * (z \dot ext_base) mod (2^k-c)= (z1 \dot base) + c * (z2 \dot base) mod (2^k-c) - * - * This sum may be short enough to express using base; if not, we can reduce again. - *) - Definition ext_limb_widths := limb_widths ++ limb_widths. - Definition ext_base := base_from_limb_widths ext_limb_widths. - Lemma ext_base_alt : ext_base = base ++ (map (Z.mul (2^k)) base). - Proof using Type*. - unfold ext_base, ext_limb_widths. - rewrite base_from_limb_widths_app by auto. - rewrite two_p_equiv. - reflexivity. - Qed. - - Lemma ext_base_positive : forall b, In b ext_base -> b > 0. - Proof using Type*. - apply base_positive; unfold ext_limb_widths. - intros ? H. apply in_app_or in H; destruct H; auto. - Qed. - - Lemma b0_1 : forall x, nth_default x base 0 = 1 -> nth_default x ext_base 0 = 1. - Proof using Type*. - intros. rewrite ext_base_alt, nth_default_app. - destruct base; assumption. - Qed. - - Lemma map_nth_default_base_high : forall n, (n < (length base))%nat -> - nth_default 0 (map (Z.mul (2 ^ k)) base) n = - (2 ^ k) * (nth_default 0 base n). - Proof using Type. - intros. - erewrite map_nth_default; auto. - Qed. - - Lemma ext_limb_widths_nonneg - (limb_widths_nonneg : forall w : Z, In w limb_widths -> 0 <= w) - : forall w : Z, In w ext_limb_widths -> 0 <= w. - Proof using Type*. - unfold ext_limb_widths; setoid_rewrite in_app_iff. - intros ? [?|?]; auto. - Qed. - - Lemma ext_limb_widths_upper_bound - : upper_bound ext_limb_widths = upper_bound limb_widths * upper_bound limb_widths. - Proof using Type*. - unfold ext_limb_widths. - autorewrite with push_upper_bound; reflexivity. - Qed. - - Section base_good. - Context (two_k_nonzero : 2^k <> 0) - (base_good : forall i j, (i+j < length base)%nat -> - let b := nth_default 0 base in - let r := (b i * b j) / b (i+j)%nat in - b i * b j = r * b (i+j)%nat) - (limb_widths_match_modulus : forall i j, - (i < length limb_widths)%nat -> - (j < length limb_widths)%nat -> - (i + j >= length limb_widths)%nat -> - let w_sum := sum_firstn limb_widths in - k + w_sum (i + j - length limb_widths)%nat <= w_sum i + w_sum j). - - Lemma base_good_over_boundary - : forall (i : nat) - (l : (i < length base)%nat) - (j' : nat) - (Hj': (i + j' < length base)%nat), - 2 ^ k * (nth_default 0 base i * nth_default 0 base j') = - (2 ^ k * (nth_default 0 base i * nth_default 0 base j')) - / (2 ^ k * nth_default 0 base (i + j')) * - (2 ^ k * nth_default 0 base (i + j')). - Proof using base_good two_k_nonzero. - clear limb_widths_match_modulus. - intros. - remember (nth_default 0 base) as b. - rewrite Zdiv_mult_cancel_l by (exact two_k_nonzero). - replace (b i * b j' / b (i + j')%nat * (2 ^ k * b (i + j')%nat)) - with ((2 ^ k * (b (i + j')%nat * (b i * b j' / b (i + j')%nat)))) by ring. - rewrite Z.mul_cancel_l by (exact two_k_nonzero). - replace (b (i + j')%nat * (b i * b j' / b (i + j')%nat)) - with ((b i * b j' / b (i + j')%nat) * b (i + j')%nat) by ring. - subst b. - apply (base_good i j'); omega. - Qed. - - Lemma ext_base_good : - forall i j, (i+j < length ext_base)%nat -> - let b := nth_default 0 ext_base in - let r := (b i * b j) / b (i+j)%nat in - b i * b j = r * b (i+j)%nat. - Proof using Type*. - intros. - subst b. subst r. - rewrite ext_base_alt in *. - rewrite app_length in H; rewrite map_length in H. - repeat rewrite nth_default_app. - repeat break_if; try omega. - { (* i < length base, j < length base, i + j < length base *) - auto using BaseSystem.base_good. - } { (* i < length base, j < length base, i + j >= length base *) - rewrite (map_nth_default _ _ _ _ 0) by omega. - apply base_matches_modulus; auto using limb_widths_nonnegative, limb_widths_match_modulus; - distr_length. - assumption. - } { (* i < length base, j >= length base, i + j >= length base *) - do 2 rewrite map_nth_default_base_high by omega. - remember (j - length base)%nat as j'. - replace (i + j - length base)%nat with (i + j')%nat by omega. - replace (nth_default 0 base i * (2 ^ k * nth_default 0 base j')) - with (2 ^ k * (nth_default 0 base i * nth_default 0 base j')) - by ring. - eapply base_good_over_boundary; eauto; omega. - } { (* i >= length base, j < length base, i + j >= length base *) - do 2 rewrite map_nth_default_base_high by omega. - remember (i - length base)%nat as i'. - replace (i + j - length base)%nat with (j + i')%nat by omega. - replace (2 ^ k * nth_default 0 base i' * nth_default 0 base j) - with (2 ^ k * (nth_default 0 base j * nth_default 0 base i')) - by ring. - eapply base_good_over_boundary; eauto; omega. - } - Qed. - End base_good. - - Lemma extended_base_length: - length ext_base = (length base + length base)%nat. - Proof using Type. - clear limb_widths_nonnegative. - unfold ext_base, ext_limb_widths; autorewrite with distr_length; reflexivity. - Qed. - - Lemma firstn_us_base_ext_base : forall (us : BaseSystem.digits), - (length us <= length base)%nat - -> firstn (length us) base = firstn (length us) ext_base. - Proof using Type*. - rewrite ext_base_alt; intros. - rewrite firstn_app_inleft; auto; omega. - Qed. - - Lemma decode_short : forall (us : BaseSystem.digits), - (length us <= length base)%nat -> - BaseSystem.decode base us = BaseSystem.decode ext_base us. - Proof using Type*. auto using decode_short_initial, firstn_us_base_ext_base. Qed. - - Section BaseVector. - Context {bv : BaseSystem.BaseVector base} - (limb_widths_match_modulus : forall i j, - (i < length limb_widths)%nat -> - (j < length limb_widths)%nat -> - (i + j >= length limb_widths)%nat -> - let w_sum := sum_firstn limb_widths in - k + w_sum (i + j - length limb_widths)%nat <= w_sum i + w_sum j). - - Instance ExtBaseVector : BaseSystem.BaseVector ext_base := - { base_positive := ext_base_positive; - b0_1 x := b0_1 x (BaseSystem.b0_1 _); - base_good := ext_base_good (two_sum_firstn_limb_widths_nonzero limb_widths_nonnegative _) BaseSystem.base_good limb_widths_match_modulus }. - End BaseVector. -End ExtendedBaseVector. - -Hint Rewrite @extended_base_length : distr_length. -Hint Resolve ext_limb_widths_nonneg : znonzero. -Hint Rewrite @ext_limb_widths_upper_bound using solve [ eauto with znonzero ] : push_upper_bound. -Hint Rewrite <- @ext_limb_widths_upper_bound using solve [ eauto with znonzero ] : pull_upper_bound. diff --git a/src/ModularArithmetic/ModularBaseSystem.v b/src/ModularArithmetic/ModularBaseSystem.v deleted file mode 100644 index 0e09386f5..000000000 --- a/src/ModularArithmetic/ModularBaseSystem.v +++ /dev/null @@ -1,124 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. -Require Import Coq.Lists.List. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.BaseSystem. -Require Import Crypto.BaseSystemProofs. -Require Import Crypto.ModularArithmetic.ExtendedBaseVector. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListZOperations. -Require Import Crypto.ModularArithmetic.ModularBaseSystemList. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListProofs. -Require Import Crypto.Util.ListUtil Crypto.Util.CaseUtil Crypto.Util.ZUtil. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.AdditionChainExponentiation. -Require Import Crypto.Util.Notations. -Require Import Crypto.Tactics.VerdiTactics. -Local Open Scope Z_scope. - -Section ModularBaseSystem. - Context `{prm :PseudoMersenneBaseParams}. - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation digits := (tuple Z (length limb_widths)). - Local Arguments to_list {_ _} _. - Local Arguments from_list {_ _} _ _. - Local Arguments length_to_list {_ _ _}. - Local Notation "[[ u ]]" := (to_list u). - - Definition decode (us : digits) : F modulus := decode [[us]]. - - Definition encode (x : F modulus) : digits := from_list (encode x) length_encode. - - Definition add (us vs : digits) : digits := from_list (add [[us]] [[vs]]) - (add_same_length _ _ _ length_to_list length_to_list). - - Definition mul (us vs : digits) : digits := from_list (mul [[us]] [[vs]]) - (length_mul length_to_list length_to_list). - - Definition sub (modulus_multiple: digits) - (modulus_multiple_correct : decode modulus_multiple = 0%F) - (us vs : digits) : digits := - from_list (sub [[modulus_multiple]] [[us]] [[vs]]) - (length_sub length_to_list length_to_list length_to_list). - - Definition zero : digits := encode (F.of_Z _ 0). - - Definition one : digits := encode (F.of_Z _ 1). - - Definition opp (modulus_multiple : digits) - (modulus_multiple_correct : decode modulus_multiple = 0%F) - (x : digits) : - digits := sub modulus_multiple modulus_multiple_correct zero x. - - Definition pow (x : digits) (chain : list (nat * nat)) : digits := - fold_chain one mul chain (x :: nil). - - Definition inv (chain : list (nat * nat)) - (chain_correct : fold_chain 0%N N.add chain (1%N :: nil) = Z.to_N (modulus - 2)) - (x : digits) : digits := pow x chain. - - (* Placeholder *) - Definition div (x y : digits) : digits := encode (F.div (decode x) (decode y)). - - Definition carry_ (carry_chain : list nat) (us : digits) : digits := - from_list (carry_sequence carry_chain [[us]]) (length_carry_sequence length_to_list). - - Definition carry_add (carry_chain : list nat) (us vs : digits) : digits := - carry_ carry_chain (add us vs). - Definition carry_mul (carry_chain : list nat) (us vs : digits) : digits := - carry_ carry_chain (mul us vs). - Definition carry_sub (carry_chain : list nat) (modulus_multiple: digits) - (modulus_multiple_correct : decode modulus_multiple = 0%F) - (us vs : digits) : digits := - carry_ carry_chain (sub modulus_multiple modulus_multiple_correct us vs). - Definition carry_opp (carry_chain : list nat) (modulus_multiple : digits) - (modulus_multiple_correct : decode modulus_multiple = 0%F) - (x : digits) : digits := - carry_sub carry_chain modulus_multiple modulus_multiple_correct zero x. - - Definition rep (us : digits) (x : F modulus) := decode us = x. - Local Notation "u ~= x" := (rep u x). - Local Hint Unfold rep. - - Definition eq (x y : digits) : Prop := decode x = decode y. - - Definition freeze int_width (x : digits) : digits := - from_list (freeze int_width [[x]]) (length_freeze length_to_list). - - Definition eqb int_width (x y : digits) : bool := fieldwiseb Z.eqb (freeze int_width x) (freeze int_width y). - - (* Note : both of the following square root definitions will produce garbage output if the input is - not square mod [modulus]. The caller should either provably only call them with square input, - or test that the output squared is in fact equal to the input and case split. *) - Definition sqrt_3mod4 (chain : list (nat * nat)) - (chain_correct : fold_chain 0%N N.add chain (1%N :: nil) = Z.to_N (modulus / 4 + 1)) - (x : digits) : digits := pow x chain. - - Definition sqrt_5mod8 int_width powx powx_squared (chain : list (nat * nat)) - (chain_correct : fold_chain 0%N N.add chain (1%N :: nil) = Z.to_N (modulus / 8 + 1)) - (sqrt_minus1 x : digits) : digits := - if eqb int_width powx_squared x then powx else mul sqrt_minus1 powx. - - Import Morphisms. - Global Instance eq_Equivalence : Equivalence eq. - Proof using Type. - split; cbv [eq]; repeat intro; congruence. - Qed. - - Definition select int_width (b : Z) (x y : digits) := - add (map (Z.land (neg int_width b)) x) - (map (Z.land (neg int_width (Z.lxor b 1))) x). - - Context {target_widths} (target_widths_nonneg : forall x, In x target_widths -> 0 <= x) - (bits_eq : sum_firstn limb_widths (length limb_widths) = - sum_firstn target_widths (length target_widths)). - Local Notation target_digits := (tuple Z (length target_widths)). - - Definition pack (x : digits) : target_digits := - from_list (pack target_widths_nonneg bits_eq [[x]]) length_pack. - - Definition unpack (x : target_digits) : digits := - from_list (unpack target_widths_nonneg bits_eq [[x]]) length_unpack. - -End ModularBaseSystem. diff --git a/src/ModularArithmetic/ModularBaseSystemList.v b/src/ModularArithmetic/ModularBaseSystemList.v deleted file mode 100644 index 8cce5481c..000000000 --- a/src/ModularArithmetic/ModularBaseSystemList.v +++ /dev/null @@ -1,90 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Coq.Lists.List. -Require Import Crypto.Util.ListUtil Crypto.Util.CaseUtil Crypto.Util.ZUtil. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.BaseSystem. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ExtendedBaseVector. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListZOperations. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.LetIn. -Require Import Crypto.Util.Notations. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Conversion. -Local Open Scope Z_scope. - -Section Defs. - Context `{prm :PseudoMersenneBaseParams} (modulus_multiple : digits). - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation "u [ i ]" := (nth_default 0 u i). - - Definition decode (us : digits) := F.of_Z modulus (BaseSystem.decode base us). - - Definition encode (x : F modulus) := encodeZ limb_widths (F.to_Z x). - - (* Converts from length of extended base to length of base by reduction modulo M.*) - Definition reduce (us : digits) : digits := - let high := skipn (length limb_widths) us in - let low := firstn (length limb_widths) us in - let wrap := map (Z.mul c) high in - BaseSystem.add low wrap. - - Definition mul (us vs : digits) := reduce (BaseSystem.mul (ext_base limb_widths) us vs). - - (* In order to subtract without underflowing, we add a multiple of the modulus first. *) - Definition sub (us vs : digits) := BaseSystem.sub (add modulus_multiple us) vs. - - (* [carry_and_reduce] multiplies the carried value by c, and, if carrying - from index [i] in a list [us], adds the value to the digit with index - [(S i) mod (length us)] *) - Definition carry_and_reduce := - carry_gen limb_widths (fun ci => c * ci) (fun Si => (Si mod (length limb_widths))%nat). - - Definition carry i : digits -> digits := - if eq_nat_dec i (pred (length limb_widths)) - then carry_and_reduce i - else carry_simple limb_widths i. - - Definition carry_sequence is (us : digits) : digits := fold_right carry us is. - - Definition carry_full : digits -> digits := carry_sequence (full_carry_chain limb_widths). - - Definition modulus_digits := encodeZ limb_widths modulus. - - (* Constant-time comparison with modulus; only works if all digits of [us] - are less than 2 ^ their respective limb width. *) - Fixpoint ge_modulus' {A} (f : Z -> A) us (result : Z) i := - dlet r := result in - match i return A with - | O => - dlet x := (cmovl (modulus_digits [0]) (us [0]) r 0) in f x - | S i' => - ge_modulus' f us (cmovne (modulus_digits [i]) (us [i]) r 0) i' - end. - - Definition ge_modulus us := ge_modulus' id us 1 (length limb_widths - 1)%nat. - - Definition conditional_subtract_modulus int_width (us : digits) (cond : Z) := - (* [and_term] is all ones if us' is full, so the subtractions subtract q overall. - Otherwise, it's all zeroes, and the subtractions do nothing. *) - map2 (fun x y => x - y) us (map (Z.land (neg int_width cond)) modulus_digits). - - Definition freeze int_width (us : digits) : digits := - let us' := carry_full (carry_full (carry_full us)) in - conditional_subtract_modulus int_width us' (ge_modulus us'). - - Context {target_widths} (target_widths_nonneg : forall x, In x target_widths -> 0 <= x) - (bits_eq : sum_firstn limb_widths (length limb_widths) = - sum_firstn target_widths (length target_widths)). - - Definition pack := @convert limb_widths limb_widths_nonneg - target_widths target_widths_nonneg - (Z.eq_le_incl _ _ bits_eq). - - Definition unpack := @convert target_widths target_widths_nonneg - limb_widths limb_widths_nonneg - (Z.eq_le_incl _ _ (Z.eq_sym bits_eq)). - -End Defs. diff --git a/src/ModularArithmetic/ModularBaseSystemListProofs.v b/src/ModularArithmetic/ModularBaseSystemListProofs.v deleted file mode 100644 index 8d749dfdd..000000000 --- a/src/ModularArithmetic/ModularBaseSystemListProofs.v +++ /dev/null @@ -1,539 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Coq.Lists.List. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.BaseSystem. -Require Import Crypto.BaseSystemProofs. -Require Import Crypto.ModularArithmetic.Conversion. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs. -Require Import Crypto.ModularArithmetic.ExtendedBaseVector. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.Util.Tactics.UniquePose. -Require Import Crypto.Util.Tactics.SpecializeBy. -Require Import Crypto.Util.ListUtil. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.Notations. - -Require Import Crypto.ModularArithmetic.ModularBaseSystemListZOperations. -Require Import Crypto.ModularArithmetic.ModularBaseSystemList. -Local Open Scope Z_scope. - -Section LengthProofs. - Context `{prm :PseudoMersenneBaseParams}. - Local Notation base := (base_from_limb_widths limb_widths). - - Lemma length_encode {x} : length (encode x) = length limb_widths. - Proof using Type. - cbv [encode encodeZ]; intros. - rewrite encode'_spec; - auto using encode'_length, limb_widths_nonneg, Nat.eq_le_incl, base_from_limb_widths_length. - Qed. - - Lemma length_reduce : forall us, - (length limb_widths <= length us <= length (ext_base limb_widths))%nat -> - (length (reduce us) = length limb_widths)%nat. - Proof using Type. - rewrite extended_base_length. - unfold reduce; intros. - rewrite add_length_exact. - pose proof (@base_from_limb_widths_length limb_widths). - rewrite map_length, firstn_length, skipn_length, Min.min_l, Max.max_l; - omega. - Qed. - - Lemma length_mul {u v} : - length u = length limb_widths - -> length v = length limb_widths - -> length (mul u v) = length limb_widths. - Proof using Type. - cbv [mul]; intros. - apply length_reduce. - destruct u; try congruence. - + rewrite @nil_length0 in *; omega. - + rewrite mul_length_exact, extended_base_length, base_from_limb_widths_length; try omega; - repeat match goal with - | |- _ => progress intros - | |- nth_default _ (ext_base _) 0 = 1 => apply b0_1 - | x := nth_default _ (ext_base _) |- _ => apply ext_base_good - | x := nth_default _ base |- _ => apply base_good - | x := nth_default _ base |- _ => apply limb_widths_good - | |- 2 ^ _ <> 0 => apply Z.pow_nonzero - | |- _ => solve [apply BaseSystem.b0_1] - | |- _ => solve [auto using limb_widths_nonneg, sum_firstn_limb_widths_nonneg, limb_widths_match_modulus] - | |- _ => omega - | |- _ => congruence - end. - Qed. - - Section Sub. - Context {mm : list Z} (mm_length : length mm = length limb_widths). - - Lemma length_sub {u v} : - length u = length limb_widths - -> length v = length limb_widths - -> length (sub mm u v) = length limb_widths. - Proof using Type*. - cbv [sub]; intros. - rewrite sub_length, add_length_exact. - repeat rewrite Max.max_r; omega. - Qed. - End Sub. - - Lemma length_carry_and_reduce {us}: forall i, length (carry_and_reduce i us) = length us. - Proof using Type. intros; unfold carry_and_reduce; autorewrite with distr_length; reflexivity. Qed. - Hint Rewrite @length_carry_and_reduce : distr_length. - - Lemma length_carry {u i} : - length u = length limb_widths - -> length (carry i u) = length limb_widths. - Proof using Type. intros; unfold carry; break_if; autorewrite with distr_length; omega. Qed. - Hint Rewrite @length_carry : distr_length. - - Lemma length_carry_sequence {u i} : - length u = length limb_widths - -> length (carry_sequence i u) = length limb_widths. - Proof using Type. - induction i; intros; unfold carry_sequence; - simpl; autorewrite with distr_length; auto. Qed. - Hint Rewrite @length_carry_sequence : distr_length. - - Lemma length_carry_full {u} : - length u = length limb_widths - -> length (carry_full u) = length limb_widths. - Proof using Type. intros; unfold carry_full; autorewrite with distr_length; congruence. Qed. - Hint Rewrite @length_carry_full : distr_length. - - Lemma length_modulus_digits : length modulus_digits = length limb_widths. - Proof using Type. - intros; unfold modulus_digits, encodeZ. - rewrite encode'_spec, encode'_length; - auto using encode'_length, limb_widths_nonneg, Nat.eq_le_incl, base_from_limb_widths_length. - Qed. - Hint Rewrite @length_modulus_digits : distr_length. - - Lemma length_conditional_subtract_modulus {int_width u cond} : - length u = length limb_widths - -> length (conditional_subtract_modulus int_width u cond) = length limb_widths. - Proof using Type. - intros; unfold conditional_subtract_modulus. - rewrite map2_length, map_length, length_modulus_digits. - apply Min.min_case; omega. - Qed. - Hint Rewrite @length_conditional_subtract_modulus : distr_length. - - Lemma length_freeze {int_width u} : - length u = length limb_widths - -> length (freeze int_width u) = length limb_widths. - Proof using Type. - intros; unfold freeze; repeat autorewrite with distr_length; congruence. - Qed. - - Lemma length_pack : forall {target_widths} - {target_widths_nonneg : forall x, In x target_widths -> 0 <= x} - {pf us}, - length (pack target_widths_nonneg pf us) = length target_widths. - Proof using Type. - cbv [pack]; intros. - apply length_convert. - Qed. - - Lemma length_unpack : forall {target_widths} - {target_widths_nonneg : forall x, In x target_widths -> 0 <= x} - {pf us}, - length (unpack target_widths_nonneg pf us) = length limb_widths. - Proof using Type. - cbv [pack]; intros. - apply length_convert. - Qed. - -End LengthProofs. - -Section ModulusDigitsProofs. - Context `{prm :PseudoMersenneBaseParams} - (c_upper_bound : c - 1 < 2 ^ nth_default 0 limb_widths 0). - Local Notation base := (base_from_limb_widths limb_widths). - Local Hint Resolve sum_firstn_limb_widths_nonneg. - Local Hint Resolve limb_widths_nonneg. - - Lemma decode_modulus_digits : decode' base modulus_digits = modulus. - Proof using Type. - cbv [modulus_digits]. - pose proof c_pos. pose proof modulus_pos. - rewrite encodeZ_spec by eauto using limb_widths_nonnil, limb_widths_good. - apply Z.mod_small. - cbv [upper_bound]. fold k. - assert (Z.pos modulus = 2 ^ k - c) by (cbv [c]; ring). - omega. - Qed. - - Lemma bounded_modulus_digits : bounded limb_widths modulus_digits. - Proof using Type. - apply bounded_encodeZ; auto using limb_widths_nonneg. - pose proof modulus_pos; omega. - Qed. - - Lemma modulus_digits_ones : forall i, (0 < i < length limb_widths)%nat -> - nth_default 0 modulus_digits i = Z.ones (nth_default 0 limb_widths i). - Proof using Type*. - repeat match goal with - | |- _ => progress (cbv [BaseSystem.decode]; intros) - | |- _ => progress autorewrite with Ztestbit - | |- _ => unique pose proof c_pos - | |- _ => unique pose proof modulus_pos - | |- _ => unique assert (Z.pos modulus = 2 ^ k - c) by (cbv [c]; ring) - | |- _ => break_if - | |- _ => rewrite decode_modulus_digits - | |- _ => rewrite Z.testbit_pow2_mod - by eauto using nth_default_limb_widths_nonneg - | |- _ => rewrite Z.ones_spec by eauto using nth_default_limb_widths_nonneg - | |- _ => erewrite digit_select - by (eauto; apply bounded_encodeZ; eauto; omega) - | |- Z.testbit (2 ^ k - c) _ = _ => - rewrite Z.testbit_sub_pow2 by (try omega; cbv [k]; - pose proof (sum_firstn_prefix_le limb_widths (S i) (length limb_widths)); - specialize_by (eauto || omega); - rewrite sum_firstn_succ_default in *; split; zero_bounds; eauto) - | |- Z.pow2_mod _ _ = Z.ones _ => apply Z.bits_inj' - | |- Z.testbit (Z.pos modulus) ?i = true => transitivity (Z.testbit (2 ^ k - c) i) - | |- _ => congruence - end. - - replace (c - 1) with ((c - 1) mod 2 ^ nth_default 0 limb_widths 0) by (apply Z.mod_small; omega). - rewrite Z.mod_pow2_bits_high; auto. - pose proof (sum_firstn_prefix_le limb_widths 1 i). - specialize_by (eauto || omega). - rewrite !sum_firstn_succ_default, !sum_firstn_0 in *. - split; zero_bounds; eauto using nth_default_limb_widths_nonneg. - Qed. - - Lemma bounded_le_modulus_digits : forall us i, length us = length limb_widths -> - bounded limb_widths us -> (0 < i < length limb_widths)%nat -> - nth_default 0 us i <= nth_default 0 modulus_digits i. - Proof using Type*. - intros until 0; rewrite bounded_iff; intros. - rewrite modulus_digits_ones by omega. - specialize (H0 i). - rewrite Z.ones_equiv. - omega. - Qed. - -End ModulusDigitsProofs. - -Section ModulusComparisonProofs. - Context `{prm :PseudoMersenneBaseParams} - (c_upper_bound : c - 1 < 2 ^ nth_default 0 limb_widths 0). - Local Notation base := (base_from_limb_widths limb_widths). - Local Hint Resolve sum_firstn_limb_widths_nonneg. - Local Hint Resolve limb_widths_nonneg. - - Fixpoint compare' us vs i := - match i with - | O => Eq - | S i' => if Z_eq_dec (nth_default 0 us i') (nth_default 0 vs i') - then compare' us vs i' - else Z.compare (nth_default 0 us i') (nth_default 0 vs i') - end. - - (* Lexicographically compare two vectors of equal length, starting from the END of the list - (in our context, this is the most significant end). NOT constant time. *) - Definition compare us vs := compare' us vs (length us). - - Lemma decode_firstn_compare' : forall us vs i, - (i <= length limb_widths)%nat -> - length us = length limb_widths -> bounded limb_widths us -> - length vs = length limb_widths -> bounded limb_widths vs -> - (Z.compare (decode' base (firstn i us)) (decode' base (firstn i vs)) - = compare' us vs i). - Proof using Type. - induction i; - repeat match goal with - | |- _ => progress intros - | |- _ => progress (simpl compare') - | |- _ => progress specialize_by (assumption || omega) - | |- _ => rewrite sum_firstn_0 - | |- _ => rewrite set_higher - | |- _ => rewrite nth_default_base by eauto - | |- _ => rewrite firstn_length, Min.min_l by omega - | |- _ => rewrite firstn_O - | |- _ => rewrite firstn_succ with (d := 0) by omega - | |- _ => rewrite Z.compare_add_shiftl by - (eauto || (rewrite decode_firstn_pow2_mod, Z.pow2_mod_pow2_mod, Z.min_id by - (eauto || omega); reflexivity)) - | |- appcontext[2 ^ ?x * ?y] => replace (2 ^ x * y) with (y << x) by - (rewrite (Z.mul_comm (2 ^ x)); apply Z.shiftl_mul_pow2; eauto) - | |- _ => tauto - | |- _ => split - | |- _ => break_if - end. - Qed. - - Lemma decode_compare' : forall us vs, - length us = length limb_widths -> bounded limb_widths us -> - length vs = length limb_widths -> bounded limb_widths vs -> - (Z.compare (decode' base us) (decode' base vs) - = compare' us vs (length limb_widths)). - Proof using Type. - intros. - rewrite <-decode_firstn_compare' by (auto || omega). - rewrite !firstn_all by auto. - reflexivity. - Qed. - - Lemma ge_modulus'_0 : forall {A} f us i, - ge_modulus' (A := A) f us 0 i = f 0. - Proof using Type. - induction i; intros; simpl; cbv [cmovne cmovl]; break_if; auto. - Qed. - - Lemma ge_modulus'_01 : forall {A} f us i b, - (b = 0 \/ b = 1) -> - (ge_modulus' (A := A) f us b i = f 0 \/ ge_modulus' (A := A) f us b i = f 1). - Proof using Type. - induction i; intros; - try intuition (subst; cbv [ge_modulus' LetIn.Let_In cmovl cmovne]; break_if; tauto). - simpl; cbv [LetIn.Let_In cmovl cmovne]. - break_if; apply IHi; tauto. - Qed. - - Lemma ge_modulus_01 : forall us, - (ge_modulus us = 0 \/ ge_modulus us = 1). - Proof using Type. - cbv [ge_modulus]; intros; apply ge_modulus'_01; tauto. - Qed. - - Lemma ge_modulus'_true_digitwise : forall us, - length us = length limb_widths -> - forall i, (i < length us)%nat -> ge_modulus' id us 1 i = 1 -> - forall j, (j <= i)%nat -> - nth_default 0 modulus_digits j <= nth_default 0 us j. - Proof using Type. - induction i; - repeat match goal with - | |- _ => progress intros; simpl in * - | |- _ => progress cbv [LetIn.Let_In cmovne cmovl] in * - | |- _ =>erewrite (ge_modulus'_0 (@id Z)) in * - | H : (?x <= 0)%nat |- _ => progress replace x with 0%nat in * by omega - | |- _ => break_if - | |- _ => discriminate - | |- _ => solve [rewrite ?Z.leb_le, ?Z.eqb_eq in *; omega] - end. - destruct (le_dec j i). - + apply IHi; auto; omega. - + replace j with (S i) in * by omega; rewrite Z.eqb_eq in *; try omega. - Qed. - - Lemma ge_modulus'_compare' : forall us, length us = length limb_widths -> bounded limb_widths us -> - forall i, (i < length limb_widths)%nat -> - (ge_modulus' id us 1 i = 0 <-> compare' us modulus_digits (S i) = Lt). - Proof using Type*. - induction i; - repeat match goal with - | |- _ => progress (intros; cbv [LetIn.Let_In id cmovne cmovl]) - | |- _ => progress (simpl compare' in * ) - | |- _ => progress specialize_by omega - | |- _ => (progress rewrite ?Z.compare_eq_iff, - ?Z.compare_gt_iff, ?Z.compare_lt_iff in * ) - | |- appcontext[ge_modulus' _ _ _ 0] => - cbv [ge_modulus'] - | |- appcontext[ge_modulus' _ _ _ (S _)] => - unfold ge_modulus'; fold (ge_modulus' (@id Z)) - | |- _ => break_if - | |- _ => rewrite Nat.sub_0_r - | |- _ => rewrite (ge_modulus'_0 (@id Z)) - | |- _ => rewrite Bool.andb_true_r - | |- _ => rewrite Z.leb_compare; break_match - | |- _ => rewrite Z.eqb_compare; break_match - | |- _ => (rewrite Z.leb_le in * ) - | |- _ => (rewrite Z.leb_gt in * ) - | |- _ => (rewrite Z.eqb_eq in * ) - | |- _ => (rewrite Z.eqb_neq in * ) - | |- _ => split; (congruence || omega) - | |- _ => assumption - end; - pose proof (bounded_le_modulus_digits c_upper_bound us (S i)); - specialize_by (auto || omega); split; (congruence || omega). - Qed. - - Lemma ge_modulus_spec : forall u, length u = length limb_widths -> - bounded limb_widths u -> - (ge_modulus u = 0 <-> 0 <= BaseSystem.decode base u < modulus). - Proof using Type*. - cbv [ge_modulus]; intros. - assert (0 < length limb_widths)%nat - by (pose proof limb_widths_nonnil; destruct limb_widths; - distr_length; omega || congruence). - rewrite ge_modulus'_compare' by (auto || omega). - replace (S (length limb_widths - 1)) with (length limb_widths) by omega. - rewrite <-decode_compare' - by (try (apply length_modulus_digits || apply bounded_encodeZ); eauto; - pose proof modulus_pos; omega). - rewrite Z.compare_lt_iff. - rewrite decode_modulus_digits. - repeat (split; intros; eauto using decode_nonneg). - cbv [BaseSystem.decode] in *. omega. - Qed. - -End ModulusComparisonProofs. - -Section ConditionalSubtractModulusProofs. - Context `{prm :PseudoMersenneBaseParams} - (* B is machine integer width (e.g. 32, 64) *) - {B} (B_pos : 0 < B) (B_compat : forall w, In w limb_widths -> w <= B) - (c_upper_bound : c - 1 < 2 ^ nth_default 0 limb_widths 0) - (lt_1_length_limb_widths : (1 < length limb_widths)%nat). - Local Notation base := (base_from_limb_widths limb_widths). - Local Hint Resolve sum_firstn_limb_widths_nonneg. - Local Hint Resolve limb_widths_nonneg. - Local Hint Resolve length_modulus_digits. - - Lemma map2_sub_eq : forall us vs, length us = length vs -> - map2 (fun x y => x - y) us vs = BaseSystem.sub us vs. - Proof using lt_1_length_limb_widths. - induction us; destruct vs; boring; try omega. - Qed. - - (* TODO : ListUtil *) - Lemma map_id_strong : forall {A} f (xs : list A), - (forall x, In x xs -> f x = x) -> map f xs = xs. - Proof using Type. - induction xs; intros; auto. - simpl; f_equal; auto using in_eq, in_cons. - Qed. - - Lemma bounded_digit_fits : forall us, - length us = length limb_widths -> bounded limb_widths us -> - forall x, In x us -> 0 <= x < 2 ^ B. - Proof using B_compat c_upper_bound lt_1_length_limb_widths. - intros. - let i := fresh "i" in - match goal with H : In ?x ?us, Hb : bounded _ _ |- _ => - apply In_nth with (d := 0) in H; destruct H as [i [? ?] ]; - rewrite bounded_iff in Hb; specialize (Hb i); - assert (2 ^ nth i limb_widths 0 <= 2 ^ B) by - (apply Z.pow_le_mono_r; try apply B_compat, nth_In; omega) end. - rewrite !nth_default_eq in *. - omega. - Qed. - - Lemma map_land_max_ones : forall us, - length us = length limb_widths -> - bounded limb_widths us -> map (Z.land (Z.ones B)) us = us. - Proof using Type*. - repeat match goal with - | |- _ => progress intros - | |- _ => apply map_id_strong - | |- appcontext[Z.ones ?n &' ?x] => rewrite (Z.land_comm _ x); - rewrite Z.land_ones by omega - | |- _ => apply Z.mod_small - | |- _ => solve [eauto using bounded_digit_fits] - end. - Qed. - - Lemma map_land_zero : forall us, map (Z.land 0) us = zeros (length us). - Proof using Type. - induction us; boring. - Qed. - - Hint Rewrite @length_modulus_digits @length_zeros : distr_length. - Lemma conditional_subtract_modulus_spec : forall u cond - (cond_01 : cond = 0 \/ cond = 1), - length u = length limb_widths -> - BaseSystem.decode base (conditional_subtract_modulus B u cond) = - BaseSystem.decode base u - cond * modulus. - Proof using Type*. - repeat match goal with - | |- _ => progress (cbv [conditional_subtract_modulus neg]; intros) - | |- _ => destruct cond_01; subst - | |- _ => break_if - | |- _ => rewrite map_land_max_ones by auto using bounded_modulus_digits - | |- _ => rewrite map_land_zero - | |- _ => rewrite map2_sub_eq by distr_length - | |- _ => rewrite sub_rep by auto - | |- _ => rewrite zeros_rep - | |- _ => rewrite decode_modulus_digits by auto - | |- _ => f_equal; ring - | |- _ => discriminate - end. - Qed. - - Lemma conditional_subtract_modulus_preserves_bounded : forall u, - length u = length limb_widths -> - bounded limb_widths u -> - bounded limb_widths (conditional_subtract_modulus B u (ge_modulus u)). - Proof using Type*. - repeat match goal with - | |- _ => progress (cbv [conditional_subtract_modulus neg]; intros) - | |- _ => unique pose proof bounded_modulus_digits - | |- _ => rewrite map_land_max_ones by auto using bounded_modulus_digits - | |- _ => rewrite map_land_zero - | |- _ => rewrite length_modulus_digits in * - | |- _ => rewrite length_zeros in * - | |- _ => rewrite Min.min_l in * by omega - | |- _ => rewrite nth_default_zeros - | |- _ => rewrite nth_default_map2 with (d1 := 0) (d2 := 0) - | |- _ => break_if - | |- bounded _ _ => apply bounded_iff - | |- 0 <= 0 < _ => split; zero_bounds; eauto using nth_default_limb_widths_nonneg - end; - repeat match goal with - | H : bounded _ ?x |- appcontext[nth_default 0 ?x ?i] => - rewrite bounded_iff in H; specialize (H i) - | |- _ => omega - end. - cbv [ge_modulus] in Heqb. - rewrite Z.eqb_eq in *. - apply ge_modulus'_true_digitwise with (j := i) in Heqb; auto; omega. - Qed. - - Lemma bounded_mul2_modulus : forall u, length u = length limb_widths -> - bounded limb_widths u -> ge_modulus u = 1 -> - modulus <= BaseSystem.decode base u < 2 * modulus. - Proof using c_upper_bound lt_1_length_limb_widths. - intros. - pose proof (@decode_upper_bound _ limb_widths_nonneg u). - specialize_by auto. - cbv [upper_bound] in *. - fold k in *. - assert (Z.pos modulus = 2 ^ k - c) by (cbv [c]; ring). - destruct (Z_le_dec modulus (BaseSystem.decode base u)). - + split; try omega. - apply Z.lt_le_trans with (m := 2 ^ k); try omega. - assert (2 * c <= 2 ^ k); try omega. - transitivity (2 ^ (nth_default 0 limb_widths 0 + 1)); - try (rewrite Z.pow_add_r, ?Z.pow_1_r; - eauto using nth_default_limb_widths_nonneg; omega). - apply Z.pow_le_mono_r; try omega. - unfold k. - pose proof (sum_firstn_prefix_le limb_widths 2 (length limb_widths)). - specialize_by (eauto || omega). - etransitivity; try eassumption. - rewrite !sum_firstn_succ_default, sum_firstn_0. - assert (0 < nth_default 0 limb_widths 1); try omega. - apply limb_widths_pos. - rewrite nth_default_eq. - apply nth_In. - omega. - + assert (0 <= BaseSystem.decode base u < modulus) as Hlt_modulus by omega. - apply ge_modulus_spec in Hlt_modulus; auto. - congruence. - Qed. - - Lemma conditional_subtract_lt_modulus : forall u, - length u = length limb_widths -> - bounded limb_widths u -> - ge_modulus (conditional_subtract_modulus B u (ge_modulus u)) = 0. - Proof using Type*. - intros. - rewrite ge_modulus_spec by auto using length_conditional_subtract_modulus, conditional_subtract_modulus_preserves_bounded. - pose proof (ge_modulus_01 u) as Hgm01. - rewrite conditional_subtract_modulus_spec by auto. - destruct Hgm01 as [Hgm0 | Hgm1]; rewrite ?Hgm0, ?Hgm1. - + apply ge_modulus_spec in Hgm0; auto. - omega. - + pose proof (bounded_mul2_modulus u); specialize_by auto. - omega. - Qed. -End ConditionalSubtractModulusProofs. diff --git a/src/ModularArithmetic/ModularBaseSystemListZOperations.v b/src/ModularArithmetic/ModularBaseSystemListZOperations.v deleted file mode 100644 index 5b39f1066..000000000 --- a/src/ModularArithmetic/ModularBaseSystemListZOperations.v +++ /dev/null @@ -1,60 +0,0 @@ -(** * Definitions of some basic operations on ℤ used in ModularBaseSystemList *) -(** We separate these out so that we can depend on them in other files - without waiting for ModularBaseSystemList to build. *) -Require Import Coq.ZArith.ZArith. -Require Import Bedrock.Word. -Require Import Crypto.Util.FixedWordSizes. -Require Import Crypto.Util.Tuple. - -Definition cmovl (x y r1 r2 : Z) := if Z.leb x y then r1 else r2. -Definition cmovne (x y r1 r2 : Z) := if Z.eqb x y then r1 else r2. - -(* analagous to NEG assembly instruction on an integer that is 0 or 1: - neg 1 = 2^64 - 1 (on 64-bit; 2^32-1 on 32-bit, etc.) - neg 0 = 0 *) -Definition neg (int_width : Z) (b : Z) := if Z.eqb b 1 then Z.ones int_width else 0%Z. - -Definition wcmovl_gen {sz} x y r1 r2 - := @ZToWord_gen sz (cmovl (@wordToZ_gen sz x) (@wordToZ_gen sz y) (@wordToZ_gen sz r1) (@wordToZ_gen sz r2)). -Definition wcmovne_gen {sz} x y r1 r2 - := @ZToWord_gen sz (cmovne (@wordToZ_gen sz x) (@wordToZ_gen sz y) (@wordToZ_gen sz r1) (@wordToZ_gen sz r2)). -Definition wneg_gen {sz} (int_width : Z) b - := @ZToWord_gen sz (neg int_width (@wordToZ_gen sz b)). - -Definition wcmovl32 x y r1 r2 := ZToWord32 (cmovl (word32ToZ x) (word32ToZ y) (word32ToZ r1) (word32ToZ r2)). -Definition wcmovne32 x y r1 r2 := ZToWord32 (cmovne (word32ToZ x) (word32ToZ y) (word32ToZ r1) (word32ToZ r2)). -Definition wneg32 (int_width : Z) b := ZToWord32 (neg int_width (word32ToZ b)). - -Definition wcmovl64 x y r1 r2 := ZToWord64 (cmovl (word64ToZ x) (word64ToZ y) (word64ToZ r1) (word64ToZ r2)). -Definition wcmovne64 x y r1 r2 := ZToWord64 (cmovne (word64ToZ x) (word64ToZ y) (word64ToZ r1) (word64ToZ r2)). -Definition wneg64 (int_width : Z) b := ZToWord64 (neg int_width (word64ToZ b)). - -Definition wcmovl128 x y r1 r2 := ZToWord128 (cmovl (word128ToZ x) (word128ToZ y) (word128ToZ r1) (word128ToZ r2)). -Definition wcmovne128 x y r1 r2 := ZToWord128 (cmovne (word128ToZ x) (word128ToZ y) (word128ToZ r1) (word128ToZ r2)). -Definition wneg128 (int_width : Z) b := ZToWord128 (neg int_width (word128ToZ b)). - -Definition wcmovl {logsz} - := word_case_dep (T:=fun _ word => word -> word -> word -> word -> word) - logsz wcmovl32 wcmovl64 wcmovl128 (fun _ => @wcmovl_gen _). -Definition wcmovne {logsz} - := word_case_dep (T:=fun _ word => word -> word -> word -> word -> word) - logsz wcmovne32 wcmovne64 wcmovne128 (fun _ => @wcmovne_gen _). -Definition wneg {logsz} - := word_case_dep (T:=fun _ word => Z -> word -> word) - logsz wneg32 wneg64 wneg128 (fun _ => @wneg_gen _). - -Hint Unfold wcmovl wcmovne wneg : fixed_size_constants. - -(** After unfolding [wneg], [wcmovl], [wcmovne], this tactic adjusts - the unfolded form to allow processing by - [FixedWordSizesEquality.fixed_size_op_to_word] *) -Ltac adjust_mbs_wops := - change wcmovl32 with (@wcmovl_gen 32) in *; - change wcmovl64 with (@wcmovl_gen 64) in *; - change wcmovl128 with (@wcmovl_gen 128) in *; - change wcmovne32 with (@wcmovne_gen 32) in *; - change wcmovne64 with (@wcmovne_gen 64) in *; - change wcmovne128 with (@wcmovne_gen 128) in *; - change wneg32 with (@wneg_gen 32) in *; - change wneg64 with (@wneg_gen 64) in *; - change wneg128 with (@wneg_gen 128) in *. diff --git a/src/ModularArithmetic/ModularBaseSystemListZOperationsProofs.v b/src/ModularArithmetic/ModularBaseSystemListZOperationsProofs.v deleted file mode 100644 index eb310f0f8..000000000 --- a/src/ModularArithmetic/ModularBaseSystemListZOperationsProofs.v +++ /dev/null @@ -1,29 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListZOperations. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.Tactics.BreakMatch. - -Local Open Scope Z_scope. - -Lemma neg_nonneg : forall x y, 0 <= x -> 0 <= ModularBaseSystemListZOperations.neg x y. -Proof. - unfold neg; intros; break_match; auto with zarith. -Qed. -Hint Resolve neg_nonneg : zarith. - -Lemma neg_upperbound : forall x y, 0 <= x -> ModularBaseSystemListZOperations.neg x y <= Z.ones x. -Proof. - unfold neg; intros; break_match; auto with zarith. -Qed. -Hint Resolve neg_upperbound : zarith. - -Lemma neg_range : forall x y, 0 <= x -> - 0 <= neg x y < 2 ^ x. -Proof. - intros. - split; auto using neg_nonneg. - eapply Z.le_lt_trans; eauto using neg_upperbound. - rewrite Z.ones_equiv. - omega. -Qed. diff --git a/src/ModularArithmetic/ModularBaseSystemOpt.v b/src/ModularArithmetic/ModularBaseSystemOpt.v deleted file mode 100644 index 0a240568b..000000000 --- a/src/ModularArithmetic/ModularBaseSystemOpt.v +++ /dev/null @@ -1,1094 +0,0 @@ -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ExtendedBaseVector. -Require Import Crypto.ModularArithmetic.Conversion. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs. -Require Import Crypto.BaseSystem. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListZOperations. -Require Import Crypto.ModularArithmetic.ModularBaseSystemList. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystem. -Require Import Crypto.ModularArithmetic.ModularBaseSystemProofs. -Require Import Coq.Lists.List. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.LetIn. -Require Import Crypto.Util.AdditionChainExponentiation. -Require Import Crypto.Util.ListUtil Crypto.Util.ZUtil Crypto.Util.NatUtil Crypto.Util.CaseUtil. -Import ListNotations. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.ZArith.Znumtheory. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Coq.QArith.QArith Coq.QArith.Qround. -Require Import Crypto.Tactics.VerdiTactics. -Require Export Crypto.Util.FixCoqMistakes. -Local Open Scope Z. - -(* Computed versions of some functions. *) - -Definition plus_opt := Eval compute in plus. - -Definition Z_add_opt := Eval compute in Z.add. -Definition Z_sub_opt := Eval compute in Z.sub. -Definition Z_mul_opt := Eval compute in Z.mul. -Definition Z_div_opt := Eval compute in Z.div. -Definition Z_pow_opt := Eval compute in Z.pow. -Definition Z_opp_opt := Eval compute in Z.opp. -Definition Z_min_opt := Eval compute in Z.min. -Definition Z_ones_opt := Eval compute in Z.ones. -Definition Z_of_nat_opt := Eval compute in Z.of_nat. -Definition Z_le_dec_opt := Eval compute in Z_le_dec. -Definition Z_lt_dec_opt := Eval compute in Z_lt_dec. -Definition Z_shiftl_opt := Eval compute in Z.shiftl. -Definition Z_shiftl_by_opt := Eval compute in Z.shiftl_by. - -Definition nth_default_opt {A} := Eval compute in @nth_default A. -Definition set_nth_opt {A} := Eval compute in @set_nth A. -Definition update_nth_opt {A} := Eval compute in @update_nth A. -Definition map_opt {A B} := Eval compute in @List.map A B. -Definition full_carry_chain_opt := Eval compute in @Pow2Base.full_carry_chain. -Definition length_opt := Eval compute in length. -Definition base_from_limb_widths_opt := Eval compute in @Pow2Base.base_from_limb_widths. -Definition minus_opt := Eval compute in minus. -Definition from_list_default_opt {A} := Eval compute in (@from_list_default A). -Definition sum_firstn_opt {A} := Eval compute in (@sum_firstn A). -Definition zeros_opt := Eval compute in (@zeros). -Definition bit_index_opt := Eval compute in bit_index. -Definition digit_index_opt := Eval compute in digit_index. - -(* Some automation that comes in handy when constructing base parameters *) -Ltac opt_step := - match goal with - | [ |- _ = match ?e with nil => _ | _ => _ end :> ?T ] - => refine (_ : match e with nil => _ | _ => _ end = _); - destruct e - end. - -Definition limb_widths_from_len_step loop len k := - (fun i prev => - match i with - | O => nil - | S i' => let x := (if (Z.eqb ((k * Z.of_nat (len - i + 1)) mod (Z.of_nat len)) 0) - then (k * Z.of_nat (len - i + 1)) / Z.of_nat len - else (k * Z.of_nat (len - i + 1)) / Z.of_nat len + 1)in - x - prev:: (loop i' x) - end). -Definition limb_widths_from_len len k := - (fix loop i prev := limb_widths_from_len_step loop len k i prev) len 0. - -Definition brute_force_indices0 lw : bool - := List.fold_right - andb true - (List.map - (fun i - => List.fold_right - andb true - (List.map - (fun j - => sum_firstn lw (i + j) <=? sum_firstn lw i + sum_firstn lw j) - (seq 0 (length lw - i)))) - (seq 0 (length lw))). - -Lemma brute_force_indices_correct0 lw - : brute_force_indices0 lw = true -> forall i j : nat, - (i + j < length lw)%nat -> sum_firstn lw (i + j) <= sum_firstn lw i + sum_firstn lw j. -Proof. - unfold brute_force_indices0. - progress repeat setoid_rewrite fold_right_andb_true_map_iff. - setoid_rewrite in_seq. - setoid_rewrite Z.leb_le. - eauto with omega. -Qed. - -Definition brute_force_indices1 lw : bool - := List.fold_right - andb true - (List.map - (fun i - => List.fold_right - andb true - (List.map - (fun j - => let w_sum := sum_firstn lw in - sum_firstn lw (length lw) + w_sum (i + j - length lw)%nat <=? w_sum i + w_sum j) - (seq (length lw - i) (length lw - (length lw - i))))) - (seq 1 (length lw - 1))). - -Lemma brute_force_indices_correct1 lw - : brute_force_indices1 lw = true -> forall i j : nat, - (i < length lw)%nat -> - (j < length lw)%nat -> - (i + j >= length lw)%nat -> - let w_sum := sum_firstn lw in - sum_firstn lw (length lw) + w_sum (i + j - length lw)%nat <= w_sum i + w_sum j. -Proof. - unfold brute_force_indices1. - progress repeat setoid_rewrite fold_right_andb_true_map_iff. - setoid_rewrite in_seq. - setoid_rewrite Z.leb_le. - eauto with omega. -Qed. - -Ltac construct_params prime_modulus len k := - let lwv := (eval cbv in (limb_widths_from_len len k)) in - let lw := fresh "lw" in pose lwv as lw; - eapply Build_PseudoMersenneBaseParams with (limb_widths := lw); - [ abstract (apply fold_right_and_True_forall_In_iff; simpl; repeat (split; [omega |]); auto) - | abstract (cbv; congruence) - | abstract (refine (@brute_force_indices_correct0 lw _); vm_cast_no_check (eq_refl true)) - | abstract apply prime_modulus - | abstract (cbv; congruence) - | abstract (refine (@brute_force_indices_correct1 lw _); vm_cast_no_check (eq_refl true))]. - -Definition construct_mul2modulus {m} (prm : PseudoMersenneBaseParams m) : digits := - match limb_widths with - | nil => nil - | x :: tail => - 2 ^ (x + 1) - (2 * c) :: List.map (fun w => 2 ^ (w + 1) - 2) tail - end. - -Ltac compute_preconditions := - cbv; intros; repeat match goal with H : _ \/ _ |- _ => - destruct H; subst; [ congruence | ] end; (congruence || omega). - -Ltac subst_precondition := match goal with - | [H : ?P, H' : ?P -> _ |- _] => specialize (H' H); clear H -end. - -Ltac kill_precondition H := - forward H; [abstract (try exact eq_refl; clear; cbv; intros; repeat break_or_hyp; intuition)|]; - subst_precondition. - -Section Carries. - Context `{prm : PseudoMersenneBaseParams} - (* allows caller to precompute k and c *) - (k_ c_ : Z) (k_subst : k = k_) (c_subst : c = c_). - Local Notation base := (Pow2Base.base_from_limb_widths limb_widths). - Local Notation digits := (tuple Z (length limb_widths)). - - Definition carry_gen_opt_sig fc fi i us - : { d : list Z | (0 <= fi (S (fi i)) < length us)%nat -> - d = carry_gen limb_widths fc fi i us}. - Proof. - eexists; intros. - cbv beta iota delta [carry_gen carry_single Z.pow2_mod]. - rewrite add_to_nth_set_nth. - change @nth_default with @nth_default_opt in *. - change @set_nth with @set_nth_opt in *. - change Z.ones with Z_ones_opt. - rewrite set_nth_nth_default by assumption. - rewrite <- @beq_nat_eq_nat_dec. - reflexivity. - Defined. - - Definition carry_gen_opt fc fi i us := Eval cbv [proj1_sig carry_gen_opt_sig] in - proj1_sig (carry_gen_opt_sig fc fi i us). - - Definition carry_gen_opt_correct fc fi i us - : (0 <= fi (S (fi i)) < length us)%nat -> - carry_gen_opt fc fi i us = carry_gen limb_widths fc fi i us - := proj2_sig (carry_gen_opt_sig fc fi i us). - - Definition carry_opt_sig - (i : nat) (b : list Z) - : { d : list Z | (length b = length limb_widths) - -> (i < length limb_widths)%nat - -> d = carry i b }. - Proof. - eexists ; intros. - cbv [carry]. - rewrite <-pull_app_if_sumbool. - cbv beta delta - [carry carry_and_reduce carry_simple]. - lazymatch goal with - | [ |- _ = (if ?br then ?c else ?d) ] - => let x := fresh "x" in let y := fresh "y" in evar (x:list Z); evar (y:list Z); transitivity (if br then x else y); subst x; subst y - end. - Focus 2. { - cbv zeta. - break_if; rewrite <-carry_gen_opt_correct by (omega || - (replace (length b) with (length limb_widths) by congruence; - apply Nat.mod_bound_pos; omega)); reflexivity. - } Unfocus. - rewrite c_subst. - rewrite <- @beq_nat_eq_nat_dec. - cbv [carry_gen_opt]. - reflexivity. - Defined. - - Definition carry_opt is us := Eval cbv [proj1_sig carry_opt_sig] in - proj1_sig (carry_opt_sig is us). - - Definition carry_opt_correct i us - : length us = length limb_widths - -> (i < length limb_widths)%nat - -> carry_opt i us = carry i us - := proj2_sig (carry_opt_sig i us). - - Definition carry_sequence_opt_sig (is : list nat) (us : list Z) - : { b : list Z | (length us = length limb_widths) - -> (forall i, In i is -> i < length limb_widths)%nat - -> b = carry_sequence is us }. - Proof. - eexists. intros H. - cbv [carry_sequence]. - transitivity (fold_right carry_opt us is). - Focus 2. - { induction is; [ reflexivity | ]. - simpl; rewrite IHis, carry_opt_correct. - - reflexivity. - - fold (carry_sequence is us). auto using length_carry_sequence. - - auto using in_eq. - - intros. auto using in_cons. - } - Unfocus. - reflexivity. - Defined. - - Definition carry_sequence_opt is us := Eval cbv [proj1_sig carry_sequence_opt_sig] in - proj1_sig (carry_sequence_opt_sig is us). - - Definition carry_sequence_opt_correct is us - : (length us = length limb_widths) - -> (forall i, In i is -> i < length limb_widths)%nat - -> carry_sequence_opt is us = carry_sequence is us - := proj2_sig (carry_sequence_opt_sig is us). - - Definition carry_gen_opt_cps_sig - {T} fc fi - (i : nat) - (f : list Z -> T) - (b : list Z) - : { d : T | (0 <= fi (S (fi i)) < length b)%nat -> d = f (carry_gen limb_widths fc fi i b) }. - Proof. - eexists. intros H. - rewrite <-carry_gen_opt_correct by assumption. - cbv beta iota delta [carry_gen_opt]. - match goal with |- appcontext[?a &' Z_ones_opt _] => - let LHS := match goal with |- ?LHS = ?RHS => LHS end in - let RHS := match goal with |- ?LHS = ?RHS => RHS end in - let RHSf := match (eval pattern (a) in RHS) with ?RHSf _ => RHSf end in - change (LHS = Let_In (a) RHSf) end. - reflexivity. - Defined. - - Definition carry_gen_opt_cps {T} fc fi i f b - := Eval cbv beta iota delta [proj1_sig carry_gen_opt_cps_sig] in - proj1_sig (@carry_gen_opt_cps_sig T fc fi i f b). - - Definition carry_gen_opt_cps_correct {T} fc fi i f b : - (0 <= fi (S (fi i)) < length b)%nat -> - @carry_gen_opt_cps T fc fi i f b = f (carry_gen limb_widths fc fi i b) - := proj2_sig (carry_gen_opt_cps_sig fc fi i f b). - - Definition carry_opt_cps_sig - {T} - (i : nat) - (f : list Z -> T) - (b : list Z) - : { d : T | (length b = length limb_widths) - -> (i < length limb_widths)%nat - -> d = f (carry i b) }. - Proof. - eexists. intros. - cbv beta delta - [carry carry_and_reduce carry_simple]. - rewrite <-pull_app_if_sumbool. - lazymatch goal with - | [ |- _ = ?f (if ?br then ?c else ?d) ] - => let x := fresh "x" in let y := fresh "y" in evar (x:T); evar (y:T); transitivity (if br then x else y); subst x; subst y - end. - Focus 2. { - cbv zeta. - break_if; rewrite <-carry_gen_opt_cps_correct by (omega || - (replace (length b) with (length limb_widths) by congruence; - apply Nat.mod_bound_pos; omega)); reflexivity. - } Unfocus. - rewrite c_subst. - rewrite <- @beq_nat_eq_nat_dec. - reflexivity. - Defined. - - Definition carry_opt_cps {T} i f b - := Eval cbv beta iota delta [proj1_sig carry_opt_cps_sig] in proj1_sig (@carry_opt_cps_sig T i f b). - - Definition carry_opt_cps_correct {T} i f b : - (length b = length limb_widths) - -> (i < length limb_widths)%nat - -> @carry_opt_cps T i f b = f (carry i b) - := proj2_sig (carry_opt_cps_sig i f b). - - Definition carry_sequence_opt_cps_sig {T} (is : list nat) (us : list Z) - (f : list Z -> T) - : { b : T | (length us = length limb_widths) - -> (forall i, In i is -> i < length limb_widths)%nat - -> b = f (carry_sequence is us) }. - Proof. - eexists. - cbv [carry_sequence]. - transitivity (fold_right carry_opt_cps f (List.rev is) us). - Focus 2. - { - assert (forall i, In i (rev is) -> i < length limb_widths)%nat as Hr. { - subst. intros. rewrite <- in_rev in *. auto. } - remember (rev is) as ris eqn:Heq. - rewrite <- (rev_involutive is), <- Heq in H0 |- *. - clear H0 Heq is. - rewrite fold_left_rev_right. - revert H. revert us; induction ris; [ reflexivity | ]; intros. - { simpl. - rewrite <- IHris; clear IHris; - [|intros; apply Hr; right; assumption|auto using length_carry]. - rewrite carry_opt_cps_correct; [reflexivity|congruence|]. - apply Hr; left; reflexivity. - } } - Unfocus. - cbv [carry_opt_cps]. - reflexivity. - Defined. - - Definition carry_sequence_opt_cps {T} is us (f : list Z -> T) := - Eval cbv [proj1_sig carry_sequence_opt_cps_sig] in - proj1_sig (carry_sequence_opt_cps_sig is us f). - - Definition carry_sequence_opt_cps_correct {T} is us (f : list Z -> T) - : (length us = length limb_widths) - -> (forall i, In i is -> i < length limb_widths)%nat - -> carry_sequence_opt_cps is us f = f (carry_sequence is us) - := proj2_sig (carry_sequence_opt_cps_sig is us f). - - Lemma full_carry_chain_bounds : forall i, In i (Pow2Base.full_carry_chain limb_widths) -> - (i < length limb_widths)%nat. - Proof. - unfold Pow2Base.full_carry_chain; intros. - apply Pow2BaseProofs.make_chain_lt; auto. - Qed. - - Definition carry_full_opt_sig (us : list Z) : - { b : list Z | (length us = length limb_widths) - -> b = carry_full us }. - Proof. - eexists; cbv [carry_full]; intros. - match goal with |- ?LHS = ?RHS => change (LHS = id RHS) end. - rewrite <-carry_sequence_opt_cps_correct with (f := id) by (auto; apply full_carry_chain_bounds). - change @Pow2Base.full_carry_chain with full_carry_chain_opt. - reflexivity. - Defined. - - Definition carry_full_opt (us : list Z) : list Z - := Eval cbv [proj1_sig carry_full_opt_sig] in proj1_sig (carry_full_opt_sig us). - - Definition carry_full_opt_correct us - : length us = length limb_widths - -> carry_full_opt us = carry_full us - := proj2_sig (carry_full_opt_sig us). - - Definition carry_full_opt_cps_sig - {T} - (f : list Z -> T) - (us : list Z) - : { d : T | length us = length limb_widths - -> d = f (carry_full us) }. - Proof. - eexists; intros. - rewrite <- carry_full_opt_correct by auto. - cbv beta iota delta [carry_full_opt]. - rewrite carry_sequence_opt_cps_correct by (auto || apply full_carry_chain_bounds). - match goal with |- ?LHS = ?f (?g (carry_sequence ?is ?us)) => - change (LHS = (fun x => f (g x)) (carry_sequence is us)) end. - rewrite <-carry_sequence_opt_cps_correct by (auto || apply full_carry_chain_bounds). - reflexivity. - Defined. - - Definition carry_full_opt_cps {T} (f : list Z -> T) (us : list Z) : T - := Eval cbv [proj1_sig carry_full_opt_cps_sig] in proj1_sig (carry_full_opt_cps_sig f us). - - Definition carry_full_opt_cps_correct {T} us (f : list Z -> T) - : length us = length limb_widths - -> carry_full_opt_cps f us = f (carry_full us) - := proj2_sig (carry_full_opt_cps_sig f us). - -End Carries. - -Section CarryChain. - Context `{prm : PseudoMersenneBaseParams} {cc : CarryChain limb_widths}. - Local Notation digits := (tuple Z (length limb_widths)). - - Definition carry__opt_sig {T} (f : digits -> T) (us : digits) - : { x | x = f (carry_ carry_chain us) }. - Proof. - eexists. - cbv [carry_]. - rewrite <- from_list_default_eq with (d := 0%Z). - change @from_list_default with @from_list_default_opt. - erewrite <-carry_sequence_opt_cps_correct by eauto using carry_chain_valid, length_to_list. - cbv [carry_sequence_opt_cps]. - reflexivity. - Defined. - - Definition carry__opt_cps {T} (f:digits -> T) (us : digits) : T - := Eval cbv [proj1_sig carry__opt_sig] in proj1_sig (carry__opt_sig f us). - - Definition carry__opt_cps_correct {T} (f:digits -> T) (us : digits) - : carry__opt_cps f us = f (carry_ carry_chain us) - := proj2_sig (carry__opt_sig f us). -End CarryChain. - -Section Addition. - Context `{prm : PseudoMersenneBaseParams} {sc : SubtractionCoefficient} {cc : CarryChain limb_widths}. - Local Notation digits := (tuple Z (length limb_widths)). - - Definition add_opt_sig (us vs : digits) : { b : digits | b = add us vs }. - Proof. - eexists. - reflexivity. - Defined. - - Definition add_opt (us vs : digits) : digits - := Eval cbv [proj1_sig add_opt_sig] in proj1_sig (add_opt_sig us vs). - - Definition add_opt_correct us vs - : add_opt us vs = add us vs - := proj2_sig (add_opt_sig us vs). - - Definition carry_add_opt_sig {T} (f:digits -> T) - (us vs : digits) : { x | x = f (carry_add carry_chain us vs) }. - Proof. - eexists. - cbv [carry_add]. - rewrite <-carry__opt_cps_correct, <-add_opt_correct. - cbv [carry_sequence_opt_cps carry__opt_cps add_opt add]. - rewrite to_list_from_list. - reflexivity. - Defined. - - Definition carry_add_opt_cps {T} (f:digits -> T) (us vs : digits) : T - := Eval cbv [proj1_sig carry_add_opt_sig] in proj1_sig (carry_add_opt_sig f us vs). - - Definition carry_add_opt_cps_correct {T} (f:digits -> T) (us vs : digits) - : carry_add_opt_cps f us vs = f (carry_add carry_chain us vs) - := proj2_sig (carry_add_opt_sig f us vs). - - Definition carry_add_opt := carry_add_opt_cps id. - - Definition carry_add_opt_correct (us vs : digits) - : carry_add_opt us vs = carry_add carry_chain us vs := - carry_add_opt_cps_correct id us vs. -End Addition. - -Section Subtraction. - Context `{prm : PseudoMersenneBaseParams} {sc : SubtractionCoefficient} {cc : CarryChain limb_widths}. - Local Notation digits := (tuple Z (length limb_widths)). - - Definition sub_opt_sig (us vs : digits) : { b : digits | b = sub coeff coeff_mod us vs }. - Proof. - eexists. - cbv [BaseSystem.add ModularBaseSystem.sub BaseSystem.sub]. - reflexivity. - Defined. - - Definition sub_opt (us vs : digits) : digits - := Eval cbv [proj1_sig sub_opt_sig] in proj1_sig (sub_opt_sig us vs). - - Definition sub_opt_correct us vs - : sub_opt us vs = sub coeff coeff_mod us vs - := proj2_sig (sub_opt_sig us vs). - - Definition carry_sub_opt_sig {T} (f:digits -> T) - (us vs : digits) : { x | x = f (carry_sub carry_chain coeff coeff_mod us vs) }. - Proof. - eexists. - cbv [carry_sub]. - rewrite <-carry__opt_cps_correct, <-sub_opt_correct. - cbv [carry_sequence_opt_cps carry__opt_cps sub_opt]. - rewrite to_list_from_list. - reflexivity. - Defined. - - Definition carry_sub_opt_cps {T} (f:digits -> T) (us vs : digits) : T - := Eval cbv [proj1_sig carry_sub_opt_sig] in proj1_sig (carry_sub_opt_sig f us vs). - - Definition carry_sub_opt_cps_correct {T} (f:digits -> T) (us vs : digits) - : carry_sub_opt_cps f us vs = f (carry_sub carry_chain coeff coeff_mod us vs) - := proj2_sig (carry_sub_opt_sig f us vs). - - Definition carry_sub_opt := carry_sub_opt_cps id. - - Definition carry_sub_opt_correct (us vs : digits) - : carry_sub_opt us vs = carry_sub carry_chain coeff coeff_mod us vs := - carry_sub_opt_cps_correct id us vs. - - Definition opp_opt_sig (us : digits) : { b : digits | b = opp coeff coeff_mod us }. - Proof. - eexists. - cbv [opp]. - rewrite <-sub_opt_correct. - reflexivity. - Defined. - - Definition opp_opt (us : digits) : digits - := Eval cbv [proj1_sig opp_opt_sig] in proj1_sig (opp_opt_sig us). - - Definition opp_opt_correct us - : opp_opt us = opp coeff coeff_mod us - := proj2_sig (opp_opt_sig us). - - Definition carry_opp_opt_sig (us : digits) : { b : digits | b = carry_opp carry_chain coeff coeff_mod us }. - Proof. - eexists. - cbv [carry_opp]. - rewrite <-carry_sub_opt_correct. - reflexivity. - Defined. - - Definition carry_opp_opt (us : digits) : digits - := Eval cbv [proj1_sig carry_opp_opt_sig] in proj1_sig (carry_opp_opt_sig us). - - Definition carry_opp_opt_correct us - : carry_opp_opt us = carry_opp carry_chain coeff coeff_mod us - := proj2_sig (carry_opp_opt_sig us). - -End Subtraction. - -Section Multiplication. - Context `{prm : PseudoMersenneBaseParams} {sc : SubtractionCoefficient} {cc : CarryChain limb_widths} - (* allows caller to precompute k and c *) - (k_ c_ : Z) (k_subst : k = k_) (c_subst : c = c_). - Local Notation digits := (tuple Z (length limb_widths)). - - Definition mul_bi'_step - (mul_bi' : nat -> list Z -> list Z -> list Z) - (i : nat) (vsr : list Z) (bs : list Z) - : list Z - := match vsr with - | [] => [] - | v :: vsr' => (v * crosscoef bs i (length vsr'))%Z :: mul_bi' i vsr' bs - end. - - Definition mul_bi'_opt_step_sig - (mul_bi' : nat -> list Z -> list Z -> list Z) - (i : nat) (vsr : list Z) (bs : list Z) - : { l : list Z | l = mul_bi'_step mul_bi' i vsr bs }. - Proof. - eexists. - cbv [mul_bi'_step]. - opt_step. - { reflexivity. } - { cbv [crosscoef]. - change Z.div with Z_div_opt. - change Z.mul with Z_mul_opt at 2. - change @nth_default with @nth_default_opt. - reflexivity. } - Defined. - - Definition mul_bi'_opt_step - (mul_bi' : nat -> list Z -> list Z -> list Z) - (i : nat) (vsr : list Z) (bs : list Z) - : list Z - := Eval cbv [proj1_sig mul_bi'_opt_step_sig] in - proj1_sig (mul_bi'_opt_step_sig mul_bi' i vsr bs). - - Fixpoint mul_bi'_opt - (i : nat) (vsr : list Z) (bs : list Z) {struct vsr} - : list Z - := mul_bi'_opt_step mul_bi'_opt i vsr bs. - - Definition mul_bi'_opt_correct - (i : nat) (vsr : list Z) (bs : list Z) - : mul_bi'_opt i vsr bs = mul_bi' bs i vsr. - Proof using Type. - revert i; induction vsr as [|vsr vsrs IHvsr]; intros. - { reflexivity. } - { simpl mul_bi'. - rewrite <- IHvsr; clear IHvsr. - unfold mul_bi'_opt, mul_bi'_opt_step. - apply f_equal2; [ | reflexivity ]. - cbv [crosscoef]. - change Z.div with Z_div_opt. - change Z.mul with Z_mul_opt at 2. - change @nth_default with @nth_default_opt. - reflexivity. } - Qed. - - Definition mul'_step - (mul' : list Z -> list Z -> list Z -> list Z) - (usr vs : list Z) (bs : list Z) - : list Z - := match usr with - | [] => [] - | u :: usr' => BaseSystem.add (mul_each u (mul_bi bs (length usr') vs)) (mul' usr' vs bs) - end. - - Lemma map_zeros : forall a n l, - List.map (Z.mul a) (zeros n ++ l) = zeros n ++ List.map (Z.mul a) l. - Proof using prm. - induction n; simpl; [ reflexivity | intros; apply f_equal2; [ omega | congruence ] ]. - Qed. - - Definition mul'_opt_step_sig - (mul' : list Z -> list Z -> list Z -> list Z) - (usr vs : list Z) (bs : list Z) - : { d : list Z | d = mul'_step mul' usr vs bs }. - Proof. - eexists. - cbv [mul'_step]. - match goal with - | [ |- _ = match ?e with nil => _ | _ => _ end :> ?T ] - => refine (_ : match e with nil => _ | _ => _ end = _); - destruct e - end. - { reflexivity. } - { cbv [mul_each mul_bi]. - rewrite <- mul_bi'_opt_correct. - rewrite map_zeros. - change @List.map with @map_opt. - cbv [zeros]. - reflexivity. } - Defined. - - Definition mul'_opt_step - (mul' : list Z -> list Z -> list Z -> list Z) - (usr vs : list Z) (bs : list Z) - : list Z - := Eval cbv [proj1_sig mul'_opt_step_sig] in proj1_sig (mul'_opt_step_sig mul' usr vs bs). - - Fixpoint mul'_opt - (usr vs : list Z) (bs : list Z) - : list Z - := mul'_opt_step mul'_opt usr vs bs. - - Definition mul'_opt_correct - (usr vs : list Z) (bs : list Z) - : mul'_opt usr vs bs = mul' bs usr vs. - Proof using prm. - revert vs; induction usr as [|usr usrs IHusr]; intros. - { reflexivity. } - { simpl. - rewrite <- IHusr; clear IHusr. - apply f_equal2; [ | reflexivity ]. - cbv [mul_each mul_bi]. - rewrite map_zeros. - rewrite <- mul_bi'_opt_correct. - cbv [zeros]. - reflexivity. } - Qed. - - Definition mul_opt_sig (us vs : digits) : { b : digits | b = mul us vs }. - Proof. - eexists. - cbv [mul ModularBaseSystemList.mul BaseSystem.mul mul_each mul_bi mul_bi' zeros reduce]. - rewrite <- from_list_default_eq with (d := 0%Z). - change (@from_list_default Z) with (@from_list_default_opt Z). - apply f_equal. - rewrite ext_base_alt by auto using limb_widths_pos with zarith. - rewrite <- mul'_opt_correct. - change @Pow2Base.base_from_limb_widths with base_from_limb_widths_opt. - rewrite Z.map_shiftl by apply k_nonneg. - rewrite c_subst. - fold k; rewrite k_subst. - change @List.map with @map_opt. - change @Z.shiftl_by with @Z_shiftl_by_opt. - reflexivity. - Defined. - - Definition mul_opt (us vs : digits) : digits - := Eval cbv [proj1_sig mul_opt_sig] in proj1_sig (mul_opt_sig us vs). - - Definition mul_opt_correct us vs - : mul_opt us vs = mul us vs - := proj2_sig (mul_opt_sig us vs). - - Definition carry_mul_opt_sig {T} (f:digits -> T) - (us vs : digits) : { x | x = f (carry_mul carry_chain us vs) }. - Proof. - eexists. - cbv [carry_mul]. - rewrite <-carry__opt_cps_correct, <-mul_opt_correct. - cbv [carry_sequence_opt_cps carry__opt_cps mul_opt]. - erewrite from_list_default_eq. - rewrite to_list_from_list. - reflexivity. - Grab Existential Variables. - rewrite mul'_opt_correct. - distr_length. - assert (0 < length limb_widths)%nat by (pose proof limb_widths_nonnil; destruct limb_widths; congruence || simpl; omega). - rewrite Min.min_l; break_match; try omega. - rewrite Max.max_l; omega. - Defined. - - Definition carry_mul_opt_cps {T} (f:digits -> T) (us vs : digits) : T - := Eval cbv [proj1_sig carry_mul_opt_sig] in proj1_sig (carry_mul_opt_sig f us vs). - - Definition carry_mul_opt_cps_correct {T} (f:digits -> T) (us vs : digits) - : carry_mul_opt_cps f us vs = f (carry_mul carry_chain us vs) - := proj2_sig (carry_mul_opt_sig f us vs). - - Definition carry_mul_opt := carry_mul_opt_cps id. - - Definition carry_mul_opt_correct (us vs : digits) - : carry_mul_opt us vs = carry_mul carry_chain us vs := - carry_mul_opt_cps_correct id us vs. - -End Multiplication. - -Import Morphisms. -Global Instance Proper_fold_chain {T} {Teq} {Teq_Equivalence : Equivalence Teq} - : Proper (Logic.eq - ==> (fun f g => forall x1 x2 y1 y2 : T, Teq x1 x2 -> Teq y1 y2 -> Teq (f x1 y1) (g x2 y2)) - ==> Logic.eq - ==> SetoidList.eqlistA Teq - ==> Teq) fold_chain. -Proof. - do 9 intro. - subst; induction y1; repeat intro; - unfold fold_chain; fold @fold_chain. - + inversion H; assumption || reflexivity. - + destruct a. - apply IHy1. - econstructor; try assumption. - apply H0; eapply Proper_nth_default; eauto; reflexivity. -Qed. - -Section PowInv. - Context `{prm : PseudoMersenneBaseParams} - (k_ c_ : Z) (k_subst : k = k_) (c_subst : c = c_) - {cc : CarryChain limb_widths}. - Local Notation digits := (tuple Z (length limb_widths)). - Context (one_ : digits) (one_subst : one = one_). - - Fixpoint fold_chain_opt {T} (id : T) op chain acc := - match chain with - | [] => match acc with - | [] => id - | ret :: _ => ret - end - | (i, j) :: chain' => - Let_In (op (nth_default id acc i) (nth_default id acc j)) - (fun ijx => fold_chain_opt id op chain' (ijx :: acc)) - end. - - Lemma fold_chain_opt_correct : forall {T} (id : T) op chain acc, - fold_chain_opt id op chain acc = fold_chain id op chain acc. - Proof using Type. - reflexivity. - Qed. - - Definition pow_opt_sig x chain : - {y | eq y (ModularBaseSystem.pow x chain)}. - Proof. - eexists. - cbv beta iota delta [ModularBaseSystem.pow]. - transitivity (fold_chain one_ (carry_mul_opt k_ c_) chain [x]). - Focus 2. { - apply Proper_fold_chain; auto; try reflexivity. - cbv [eq]; intros. - rewrite carry_mul_opt_correct by assumption. - rewrite carry_mul_rep, mul_rep by reflexivity. - congruence. - } Unfocus. - rewrite <-fold_chain_opt_correct. - reflexivity. - Defined. - - Definition pow_opt x chain : digits - := Eval cbv [proj1_sig pow_opt_sig] in (proj1_sig (pow_opt_sig x chain)). - - Definition pow_opt_correct x chain - : eq (pow_opt x chain) (ModularBaseSystem.pow x chain) - := Eval cbv [proj2_sig pow_opt_sig] in (proj2_sig (pow_opt_sig x chain)). - - Context {ec : ExponentiationChain (modulus - 2)}. - - Definition inv_opt_sig x: - {y | eq y (inv chain chain_correct x)}. - Proof. - eexists. - cbv [inv]. - rewrite <-pow_opt_correct. - reflexivity. - Defined. - - Definition inv_opt x : digits - := Eval cbv [proj1_sig inv_opt_sig] in (proj1_sig (inv_opt_sig x)). - - Definition inv_opt_correct x - : eq (inv_opt x) (inv chain chain_correct x) - := Eval cbv [proj2_sig inv_opt_sig] in (proj2_sig (inv_opt_sig x)). -End PowInv. - -Section Conversion. - - Definition convert'_opt_sig {lwA lwB} - (nonnegA : forall x, In x lwA -> 0 <= x) - (nonnegB : forall x, In x lwB -> 0 <= x) - bits_fit inp i out : - { y | y = convert' nonnegA nonnegB bits_fit inp i out}. - Proof. - eexists. - rewrite convert'_equation. - change sum_firstn with @sum_firstn_opt. - change length with length_opt. - change Z_le_dec with Z_le_dec_opt. - change Z.of_nat with Z_of_nat_opt. - change digit_index with digit_index_opt. - change bit_index with bit_index_opt. - change Z.min with Z_min_opt. - change (nth_default 0 lwA) with (nth_default_opt 0 lwA). - change (nth_default 0 lwB) with (nth_default_opt 0 lwB). - cbv [update_by_concat_bits concat_bits Z.pow2_mod]. - change Z.ones with Z_ones_opt. - change @update_nth with @update_nth_opt. - change plus with plus_opt. - change Z.sub with Z_sub_opt. - reflexivity. - Defined. - - Definition convert'_opt {lwA lwB} - (nonnegA : forall x, In x lwA -> 0 <= x) - (nonnegB : forall x, In x lwB -> 0 <= x) - bits_fit inp i out := - Eval cbv [proj1_sig convert'_opt_sig] in - proj1_sig (convert'_opt_sig nonnegA nonnegB bits_fit inp i out). - - Definition convert'_opt_correct {lwA lwB} - (nonnegA : forall x, In x lwA -> 0 <= x) - (nonnegB : forall x, In x lwB -> 0 <= x) - bits_fit inp i out : - convert'_opt nonnegA nonnegB bits_fit inp i out = convert' nonnegA nonnegB bits_fit inp i out := - Eval cbv [proj2_sig convert'_opt_sig] in - proj2_sig (convert'_opt_sig nonnegA nonnegB bits_fit inp i out). - - Context {modulus} (prm : PseudoMersenneBaseParams modulus) - {target_widths} (target_widths_nonneg : forall x, In x target_widths -> 0 <= x) (bits_eq : sum_firstn limb_widths (length limb_widths) = sum_firstn target_widths (length target_widths)). - Local Notation digits := (tuple Z (length limb_widths)). - Local Notation target_digits := (tuple Z (length target_widths)). - - Definition pack_opt_sig (x : digits) : { y | y = pack target_widths_nonneg bits_eq x}. - Proof. - eexists. - cbv [pack]. - rewrite <- from_list_default_eq with (d := 0%Z). - change @from_list_default with @from_list_default_opt. - cbv [ModularBaseSystemList.pack convert]. - change length with length_opt. - change sum_firstn with @sum_firstn_opt. - change zeros with zeros_opt. - reflexivity. - Defined. - - Definition pack_opt (x : digits) : target_digits := - Eval cbv [proj1_sig pack_opt_sig] in proj1_sig (pack_opt_sig x). - - Definition pack_correct (x : digits) : - pack_opt x = pack target_widths_nonneg bits_eq x - := Eval cbv [proj2_sig pack_opt_sig] in proj2_sig (pack_opt_sig x). - - Definition unpack_opt_sig (x : target_digits) : { y | y = unpack target_widths_nonneg bits_eq x}. - Proof. - eexists. - cbv [unpack]. - rewrite <- from_list_default_eq with (d := 0%Z). - change @from_list_default with @from_list_default_opt. - cbv [ModularBaseSystemList.unpack convert]. - change length with length_opt. - change sum_firstn with @sum_firstn_opt. - change zeros with zeros_opt. - reflexivity. - Defined. - - Definition unpack_opt (x : target_digits) : digits := - Eval cbv [proj1_sig unpack_opt_sig] in proj1_sig (unpack_opt_sig x). - - Definition unpack_correct (x : target_digits) : - unpack_opt x = unpack target_widths_nonneg bits_eq x - := Eval cbv [proj2_sig unpack_opt_sig] in proj2_sig (unpack_opt_sig x). - -End Conversion. - -Local Hint Resolve lt_1_length_limb_widths int_width_pos B_pos B_compat - c_reduce1 c_reduce2. - -Section Canonicalization. - Context `{prm : PseudoMersenneBaseParams} {sc : SubtractionCoefficient} - (* allows caller to precompute k and c *) - (k_ c_ : Z) (k_subst : k = k_) (c_subst : c = c_) - {int_width freeze_input_bound} - (preconditions : FreezePreconditions freeze_input_bound int_width). - Local Notation digits := (tuple Z (length limb_widths)). - - Definition carry_full_3_opt_sig - (us : list Z) - : { d : list Z | length us = length limb_widths - -> d = carry_full (carry_full (carry_full us)) }. - Proof. - eexists. - transitivity (carry_full_opt_cps c_ (carry_full_opt_cps c_ (carry_full_opt c_)) us). - Focus 2. { - rewrite !carry_full_opt_cps_correct; try rewrite carry_full_opt_correct; repeat (autorewrite with distr_length; rewrite ?length_carry_full; auto). - } - Unfocus. - reflexivity. - Defined. - - Definition carry_full_3_opt (us : list Z) : list Z - := Eval cbv [proj1_sig carry_full_3_opt_sig] in proj1_sig (carry_full_3_opt_sig us). - - Definition carry_full_3_opt_correct us - : length us = length limb_widths - -> carry_full_3_opt us = carry_full (carry_full (carry_full us)) - := proj2_sig (carry_full_3_opt_sig us). - - Lemma ge_modulus'_cps : forall {A} (f : Z -> A) (us : list Z) i b, - f (ge_modulus' id us b i) = ge_modulus' f us b i. - Proof using Type. - induction i; intros; simpl; cbv [Let_In cmovl cmovne]; break_if; try reflexivity; - apply IHi. - Qed. - - Definition ge_modulus_opt_sig (us : list Z) : - { a : Z | a = ge_modulus us}. - Proof. - eexists. - cbv [ge_modulus ge_modulus']. - change length with length_opt. - change nth_default with @nth_default_opt. - change minus with minus_opt. - reflexivity. - Defined. - - Definition ge_modulus_opt us : Z - := Eval cbv [proj1_sig ge_modulus_opt_sig] in proj1_sig (ge_modulus_opt_sig us). - - Definition ge_modulus_opt_correct us : - ge_modulus_opt us= ge_modulus us - := Eval cbv [proj2_sig ge_modulus_opt_sig] in proj2_sig (ge_modulus_opt_sig us). - - Definition conditional_subtract_modulus_opt_sig (f : list Z): - { g | g = conditional_subtract_modulus int_width f (ge_modulus f) }. - Proof. - eexists. - cbv [conditional_subtract_modulus]. - let LHS := match goal with |- ?LHS = ?RHS => LHS end in - let RHS := match goal with |- ?LHS = ?RHS => RHS end in - let RHSf := match (eval pattern (neg int_width (ge_modulus f)) in RHS) with ?RHSf _ => RHSf end in - change (LHS = Let_In (neg int_width (ge_modulus f)) RHSf). - cbv [ge_modulus]. - rewrite ge_modulus'_cps. - cbv beta iota delta [ge_modulus ge_modulus']. - change length with length_opt. - change nth_default with @nth_default_opt. - change @Pow2Base.base_from_limb_widths with base_from_limb_widths_opt. - change minus with minus_opt. - reflexivity. - Defined. - - Definition conditional_subtract_modulus_opt f : list Z - := Eval cbv [proj1_sig conditional_subtract_modulus_opt_sig] in proj1_sig (conditional_subtract_modulus_opt_sig f). - - Definition conditional_subtract_modulus_opt_correct f - : conditional_subtract_modulus_opt f = conditional_subtract_modulus int_width f (ge_modulus f) - := Eval cbv [proj2_sig conditional_subtract_modulus_opt_sig] in proj2_sig (conditional_subtract_modulus_opt_sig f). - - - Definition freeze_opt_sig (us : list Z) : - { b : list Z | length us = length limb_widths - -> b = ModularBaseSystemList.freeze int_width us }. - Proof. - eexists. - cbv [ModularBaseSystemList.freeze]. - rewrite <-conditional_subtract_modulus_opt_correct. - intros. - rewrite <-carry_full_3_opt_correct by auto. - let LHS := match goal with |- ?LHS = ?RHS => LHS end in - let RHS := match goal with |- ?LHS = ?RHS => RHS end in - let RHSf := match (eval pattern (carry_full_3_opt us) in RHS) with ?RHSf _ => RHSf end in - change (LHS = Let_In (carry_full_3_opt us) RHSf). - reflexivity. - Defined. - - Definition freeze_opt (us : list Z) : list Z - := Eval cbv beta iota delta [proj1_sig freeze_opt_sig] in proj1_sig (freeze_opt_sig us). - - Definition freeze_opt_correct us - : length us = length limb_widths - -> freeze_opt us = ModularBaseSystemList.freeze int_width us - := proj2_sig (freeze_opt_sig us). - -End Canonicalization. - -Section SquareRoots. - Context `{prm : PseudoMersenneBaseParams}. - Context {cc : CarryChain limb_widths}. - Local Notation digits := (tuple Z (length limb_widths)). - (* allows caller to precompute k and c *) - Context (k_ c_ : Z) (k_subst : k = k_) (c_subst : c = c_) - (one_ : digits) (one_subst : one = one_). - - (* TODO : where should this lemma go? Alternatively, is there a standard-library - tactic/lemma for this? *) - Lemma if_equiv : forall {A} (eqA : A -> A -> Prop) (x0 x1 : bool) y0 y1 z0 z1, - x0 = x1 -> eqA y0 y1 -> eqA z0 z1 -> - eqA (if x0 then y0 else z0) (if x1 then y1 else z1). - Proof using Type. - intros; repeat break_if; congruence. - Qed. - - Section SquareRoot3mod4. - Context {ec : ExponentiationChain (modulus / 4 + 1)}. - - Definition sqrt_3mod4_opt_sig (us : digits) : - { vs : digits | eq vs (sqrt_3mod4 chain chain_correct us)}. - Proof. - eexists; cbv [sqrt_3mod4]. - apply @pow_opt_correct; eassumption. - Defined. - - Definition sqrt_3mod4_opt us := Eval cbv [proj1_sig sqrt_3mod4_opt_sig] in - proj1_sig (sqrt_3mod4_opt_sig us). - - Definition sqrt_3mod4_opt_correct us - : eq (sqrt_3mod4_opt us) (sqrt_3mod4 chain chain_correct us) - := Eval cbv [proj2_sig sqrt_3mod4_opt_sig] in proj2_sig (sqrt_3mod4_opt_sig us). - - End SquareRoot3mod4. - - Section SquareRoot5mod8. - Context {ec : ExponentiationChain (modulus / 8 + 1)}. - Context (sqrt_m1 : digits) (sqrt_m1_correct : rep (mul sqrt_m1 sqrt_m1) (F.opp 1%F)). - Context {int_width freeze_input_bound} - (preconditions : FreezePreconditions freeze_input_bound int_width). - - Definition sqrt_5mod8_opt_sig (powx powx_squared us : digits) : - { vs : digits | - eq vs (sqrt_5mod8 int_width powx powx_squared chain chain_correct sqrt_m1 us)}. - Proof. - cbv [sqrt_5mod8]. - match goal with - |- appcontext[(if ?P then ?t else mul ?a ?b)] => - assert (eq (carry_mul_opt k_ c_ a b) (mul a b)) - by (rewrite carry_mul_opt_correct by auto; - cbv [eq]; rewrite carry_mul_rep, mul_rep; reflexivity) - end. - let RHS := match goal with |- {vs | eq vs ?RHS} => RHS end in - let RHSf := match (eval pattern powx in RHS) with ?RHSf _ => RHSf end in - change ({vs | eq vs (Let_In powx RHSf)}). - match goal with - | H : eq (?g powx) (?f powx) - |- {vs | eq vs (Let_In powx (fun x => if ?P then x else ?f x))} => - exists (Let_In powx (fun x => if P then x else g x)) - end. - break_if; try reflexivity. - cbv [Let_In]. - auto. - Defined. - - Definition sqrt_5mod8_opt powx powx_squared us := Eval cbv [proj1_sig sqrt_5mod8_opt_sig] in - proj1_sig (sqrt_5mod8_opt_sig powx powx_squared us). - - Definition sqrt_5mod8_opt_correct powx powx_squared us - : eq (sqrt_5mod8_opt powx powx_squared us) (ModularBaseSystem.sqrt_5mod8 int_width _ _ chain chain_correct sqrt_m1 us) - := Eval cbv [proj2_sig sqrt_5mod8_opt_sig] in proj2_sig (sqrt_5mod8_opt_sig powx powx_squared us). - - End SquareRoot5mod8. - -End SquareRoots. diff --git a/src/ModularArithmetic/ModularBaseSystemProofs.v b/src/ModularArithmetic/ModularBaseSystemProofs.v deleted file mode 100644 index 9b22187bd..000000000 --- a/src/ModularArithmetic/ModularBaseSystemProofs.v +++ /dev/null @@ -1,1145 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Coq.Lists.List. -Require Import Crypto.Algebra. -Require Import Crypto.BaseSystem. -Require Import Crypto.BaseSystemProofs. -Require Import Crypto.ModularArithmetic.ExtendedBaseVector. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystemList. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystem. -Require Import Crypto.Util.ListUtil Crypto.Util.CaseUtil Crypto.Util.ZUtil Crypto.Util.NatUtil. -Require Import Crypto.Util.AdditionChainExponentiation. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.Tactics.UniquePose. -Require Import Crypto.Util.Tactics.BreakMatch. -Require Import Crypto.Util.Tactics.SpecializeBy. -Require Import Crypto.Util.Notations. -Require Export Crypto.Util.FixCoqMistakes. -Local Open Scope Z_scope. - -Local Opaque add_to_nth carry_simple. - -Class CarryChain (limb_widths : list Z) := - { - carry_chain : list nat; - carry_chain_valid : forall i, In i carry_chain -> (i < length limb_widths)%nat - }. - - Class SubtractionCoefficient {m : positive} {prm : PseudoMersenneBaseParams m} := { - coeff : tuple Z (length limb_widths); - coeff_mod: decode coeff = 0%F - }. - - Class ExponentiationChain {m : positive} {prm : PseudoMersenneBaseParams m} (exp : Z) := { - chain : list (nat * nat); - chain_correct : fold_chain 0%N N.add chain (1%N :: nil) = Z.to_N exp - }. - - -Section FieldOperationProofs. - Context `{prm :PseudoMersenneBaseParams}. - - Local Arguments to_list {_ _} _. - Local Arguments from_list {_ _} _ _. - - Local Hint Unfold decode. - Local Notation "u ~= x" := (rep u x). - Local Notation digits := (tuple Z (length limb_widths)). - Local Hint Resolve (@limb_widths_nonneg _ prm) sum_firstn_limb_widths_nonneg. - - Local Hint Resolve log_cap_nonneg. - Local Hint Resolve base_from_limb_widths_length. - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation log_cap i := (nth_default 0 limb_widths i). - - Local Hint Unfold rep decode ModularBaseSystemList.decode. - - Lemma rep_decode : forall us x, us ~= x -> decode us = x. - Proof using Type. - autounfold; intuition. - Qed. - - Lemma decode_rep : forall us, rep us (decode us). - Proof using Type. - cbv [rep]; auto. - Qed. - - Lemma encode_eq : forall x : F modulus, - ModularBaseSystemList.encode x = BaseSystem.encode base (F.to_Z x) (2 ^ k). - Proof using Type. - cbv [ModularBaseSystemList.encode BaseSystem.encode encodeZ]; intros. - rewrite base_from_limb_widths_length. - apply encode'_spec; auto using Nat.eq_le_incl. - Qed. - - Lemma encode_rep : forall x : F modulus, encode x ~= x. - Proof using Type. - autounfold; cbv [encode]; intros. - rewrite to_list_from_list; autounfold. - rewrite encode_eq, encode_rep. - + apply F.of_Z_to_Z. - + apply bv. - + rewrite <-F.mod_to_Z. - match goal with |- appcontext [?a mod (Z.pos modulus)] => - pose proof (Z.mod_pos_bound a modulus modulus_pos) end. - pose proof lt_modulus_2k. - omega. - + eauto using base_upper_bound_compatible, limb_widths_nonneg. - Qed. - - Lemma bounded_encode : forall x, bounded limb_widths (to_list (encode x)). - Proof using Type. - intros. - cbv [encode]; rewrite to_list_from_list. - cbv [ModularBaseSystemList.encode]. - apply bounded_encodeZ; auto. - apply F.to_Z_range. - pose proof prime_modulus; prime_bound. - Qed. - - Lemma encode_range : forall x, - 0 <= BaseSystem.decode base (to_list (encode x)) < modulus. - Proof. - cbv [encode]; intros. - rewrite to_list_from_list. - rewrite encode_eq. - rewrite BaseSystemProofs.encode_rep; auto using F.to_Z_range, modulus_pos, bv. - + pose proof (F.to_Z_range x modulus_pos). - replace (2 ^ k) with (modulus + c) by (cbv[c]; ring). - pose proof c_pos; omega. - + apply base_upper_bound_compatible; auto. - Qed. - - Lemma add_rep : forall u v x y, u ~= x -> v ~= y -> - add u v ~= (x+y)%F. - Proof using Type. - autounfold; cbv [add]; intros. - rewrite to_list_from_list; autounfold. - rewrite add_rep, F.of_Z_add. - f_equal; assumption. - Qed. - - Lemma eq_rep_iff : forall u v, (eq u v <-> u ~= decode v). - Proof using Type. - reflexivity. - Qed. - - Lemma eq_dec : forall x y, Decidable.Decidable (eq x y). - Proof using Type. - intros. - destruct (F.eq_dec (decode x) (decode y)); [ left | right ]; congruence. - Qed. - - Lemma modular_base_system_add_monoid : @monoid digits eq add zero. - Proof using Type. - repeat match goal with - | |- _ => progress intro - | |- _ => cbv [zero]; rewrite encode_rep - | |- _ digits eq add => econstructor - | |- _ digits eq add _ => econstructor - | |- (_ + _)%F = decode (add ?a ?b) => rewrite (add_rep a b) by (try apply add_rep; reflexivity) - | |- eq _ _ => apply eq_rep_iff - | |- add _ _ ~= _ => apply add_rep - | |- decode (add _ _) = _ => apply add_rep - | |- add _ _ ~= decode _ => etransitivity - | x : digits |- ?x ~= _ => reflexivity - | |- _ => apply associative - | |- _ => apply left_identity - | |- _ => apply right_identity - | |- _ => solve [eauto using eq_Equivalence, eq_dec] - | |- _ => congruence - end. - Qed. - - Local Hint Resolve firstn_us_base_ext_base bv ExtBaseVector limb_widths_match_modulus. - Local Hint Extern 1 => apply limb_widths_match_modulus. - - Lemma reduce_rep : forall us, - BaseSystem.decode base (reduce us) mod modulus = - BaseSystem.decode (ext_base limb_widths) us mod modulus. - Proof. - cbv [reduce]; intros. - rewrite extended_shiftadd, base_from_limb_widths_length, pseudomersenne_add, BaseSystemProofs.add_rep. - change (List.map (Z.mul c)) with (BaseSystem.mul_each c). - rewrite mul_each_rep; auto. - Qed. - - Lemma mul_rep : forall u v x y, u ~= x -> v ~= y -> mul u v ~= (x*y)%F. - Proof using Type. - autounfold in *; unfold ModularBaseSystem.mul in *. - intuition idtac; subst. - rewrite to_list_from_list. - cbv [ModularBaseSystemList.mul ModularBaseSystemList.decode]. - rewrite F.of_Z_mod, reduce_rep, <-F.of_Z_mod. - pose proof (@base_from_limb_widths_length limb_widths). - rewrite @mul_rep by (eauto using ExtBaseVector || rewrite extended_base_length, !length_to_list; omega). - rewrite 2decode_short by (rewrite ?base_from_limb_widths_length; - auto using Nat.eq_le_incl, length_to_list with omega). - apply F.of_Z_mul. - Qed. - - Lemma modular_base_system_mul_monoid : @monoid digits eq mul one. - Proof using Type. - repeat match goal with - | |- _ => progress intro - | |- _ => cbv [one]; rewrite encode_rep - | |- _ digits eq mul => econstructor - | |- _ digits eq mul _ => econstructor - | |- (_ * _)%F = decode (mul ?a ?b) => rewrite (mul_rep a b) by (try apply mul_rep; reflexivity) - | |- eq _ _ => apply eq_rep_iff - | |- mul _ _ ~= _ => apply mul_rep - | |- decode (mul _ _) = _ => apply mul_rep - | |- mul _ _ ~= decode _ => etransitivity - | x : digits |- ?x ~= _ => reflexivity - | |- _ => apply associative - | |- _ => apply left_identity - | |- _ => apply right_identity - | |- _ => solve [eauto using eq_Equivalence, eq_dec] - | |- _ => congruence - end. - Qed. - - Lemma Fdecode_decode_mod : forall us x, - decode us = x -> BaseSystem.decode base (to_list us) mod modulus = F.to_Z x. - Proof using Type. - autounfold; intros. - rewrite <-H. - apply F.to_Z_of_Z. - Qed. - - Lemma sub_rep : forall mm pf u v x y, u ~= x -> v ~= y -> - ModularBaseSystem.sub mm pf u v ~= (x-y)%F. - Proof. - autounfold; cbv [sub]; intros. - rewrite to_list_from_list; autounfold. - cbv [ModularBaseSystemList.sub]. - rewrite BaseSystemProofs.sub_rep, BaseSystemProofs.add_rep. - rewrite F.of_Z_sub, F.of_Z_add, F.of_Z_mod. - apply Fdecode_decode_mod in pf; cbv [BaseSystem.decode] in *. - rewrite pf. rewrite Algebra.left_identity. - f_equal; assumption. - Qed. - - Lemma opp_rep : forall mm pf u x, u ~= x -> opp mm pf u ~= F.opp x. - Proof using Type. - cbv [opp rep]; intros. - rewrite sub_rep by (apply encode_rep || eassumption). - apply F.eq_to_Z_iff. - rewrite F.to_Z_opp. - rewrite <-Z.sub_0_l. - pose proof @F.of_Z_sub. - transitivity (F.to_Z (F.of_Z modulus (0 - F.to_Z x))); - [ rewrite F.of_Z_sub, F.of_Z_to_Z; reflexivity | ]. - rewrite F.to_Z_of_Z. reflexivity. - Qed. - - Section PowInv. - Context (modulus_gt_2 : 2 < modulus). - - Lemma scalarmult_rep : forall u x n, u ~= x -> - (@ScalarMult.scalarmult_ref digits mul one n u) ~= (x ^ (N.of_nat n))%F. - Proof using Type. - induction n; intros. - + cbv [N.to_nat ScalarMult.scalarmult_ref]. rewrite F.pow_0_r. - apply encode_rep. - + unfold ScalarMult.scalarmult_ref. - fold (@ScalarMult.scalarmult_ref digits mul one). - rewrite Nnat.Nat2N.inj_succ, <-N.add_1_l, F.pow_add_r, F.pow_1_r. - apply mul_rep; auto. - Qed. - - Lemma pow_rep : forall chain u x, u ~= x -> - pow u chain ~= F.pow x (fold_chain 0%N N.add chain (1%N :: nil)). - Proof using Type. - cbv [pow rep]; intros. - erewrite (@fold_chain_exp _ _ _ _ modular_base_system_mul_monoid) - by (apply @ScalarMult.scalarmult_ref_is_scalarmult; apply modular_base_system_mul_monoid). - etransitivity; [ apply scalarmult_rep; eassumption | ]. - rewrite Nnat.N2Nat.id. - reflexivity. - Qed. - - Lemma inv_rep : forall chain pf u x, u ~= x -> - inv chain pf u ~= F.inv x. - Proof using modulus_gt_2. - cbv [inv]; intros. - rewrite (@F.Fq_inv_fermat _ prime_modulus modulus_gt_2). - etransitivity; [ apply pow_rep; eassumption | ]. - congruence. - Qed. - - End PowInv. - - - Import Morphisms. - - Global Instance encode_Proper : Proper (Logic.eq ==> eq) encode. - Proof using Type. - repeat intro; cbv [eq]. - rewrite !encode_rep. assumption. - Qed. - - Global Instance add_Proper : Proper (eq ==> eq ==> eq) add. - Proof using Type. - repeat intro. - cbv beta delta [eq] in *. - erewrite !add_rep; cbv [rep] in *; try reflexivity; assumption. - Qed. - - Global Instance sub_Proper mm mm_correct - : Proper (eq ==> eq ==> eq) (sub mm mm_correct). - Proof using Type. - repeat intro. - cbv beta delta [eq] in *. - erewrite !sub_rep; cbv [rep] in *; try reflexivity; assumption. - Qed. - - Global Instance opp_Proper mm mm_correct - : Proper (eq ==> eq) (opp mm mm_correct). - Proof using Type. - cbv [opp]; repeat intro. - apply sub_Proper; assumption || reflexivity. - Qed. - - Global Instance mul_Proper : Proper (eq ==> eq ==> eq) mul. - Proof using Type. - repeat intro. - cbv beta delta [eq] in *. - erewrite !mul_rep; cbv [rep] in *; try reflexivity; assumption. - Qed. - - Global Instance pow_Proper : Proper (eq ==> Logic.eq ==> eq) pow. - Proof using Type. - repeat intro. - cbv beta delta [eq] in *. - erewrite !pow_rep; cbv [rep] in *; subst; try reflexivity. - congruence. - Qed. - - Global Instance inv_Proper chain chain_correct : Proper (eq ==> eq) (inv chain chain_correct). - Proof using Type. - cbv [inv]; repeat intro. - apply pow_Proper; assumption || reflexivity. - Qed. - - Global Instance div_Proper : Proper (eq ==> eq ==> eq) div. - Proof using Type. - cbv [div]; repeat intro; congruence. - Qed. - - Section FieldProofs. - Context (modulus_gt_2 : 2 < modulus) - {sc : SubtractionCoefficient} - {ec : ExponentiationChain (modulus - 2)}. - - Lemma _zero_neq_one : not (eq zero one). - Proof using Type. - cbv [eq zero one]; erewrite !encode_rep. - pose proof (@F.field_modulo modulus prime_modulus). - apply zero_neq_one. - Qed. - - Lemma modular_base_system_field : - @field digits eq zero one (opp coeff coeff_mod) add (sub coeff coeff_mod) mul (inv chain chain_correct) div. - Proof using modulus_gt_2. - eapply (Field.isomorphism_to_subfield_field (phi := decode) (fieldR := @F.field_modulo modulus prime_modulus)). - Grab Existential Variables. - + intros; eapply encode_rep. - + intros; eapply encode_rep. - + intros; eapply encode_rep. - + intros; eapply inv_rep; auto. - + intros; eapply mul_rep; auto. - + intros; eapply sub_rep; auto using coeff_mod. - + intros; eapply add_rep; auto. - + intros; eapply opp_rep; auto using coeff_mod. - + eapply _zero_neq_one. - + trivial. - Qed. -End FieldProofs. - -End FieldOperationProofs. -Opaque encode add mul sub inv pow. - -Section CarryProofs. - Context `{prm : PseudoMersenneBaseParams}. - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation log_cap i := (nth_default 0 limb_widths i). - Local Notation "u ~= x" := (rep u x). - Local Hint Resolve (@limb_widths_nonneg _ prm) sum_firstn_limb_widths_nonneg. - Local Hint Resolve log_cap_nonneg. - - Lemma base_length_lt_pred : (pred (length base) < length base)%nat. - Proof using Type. - pose proof limb_widths_nonnil; rewrite base_from_limb_widths_length. - destruct limb_widths; congruence || distr_length. - Qed. - Hint Resolve base_length_lt_pred. - - Definition carry_done us := forall i, (i < length base)%nat -> - 0 <= nth_default 0 us i /\ Z.shiftr (nth_default 0 us i) (log_cap i) = 0. - - Lemma carry_done_bounds : forall us, (length us = length base) -> - (carry_done us <-> forall i, 0 <= nth_default 0 us i < 2 ^ log_cap i). - Proof using Type. - intros ? ?; unfold carry_done; split; [ intros Hcarry_done i | intros Hbounds i i_lt ]. - + destruct (lt_dec i (length base)) as [i_lt | i_nlt]. - - specialize (Hcarry_done i i_lt). - split; [ intuition | ]. - destruct Hcarry_done as [Hnth_nonneg Hshiftr_0]. - apply Z.shiftr_eq_0_iff in Hshiftr_0. - destruct Hshiftr_0 as [nth_0 | [] ]; [ rewrite nth_0; zero_bounds | ]. - apply Z.log2_lt_pow2; auto. - - rewrite nth_default_out_of_bounds by omega. - split; zero_bounds. - + specialize (Hbounds i). - split; [ intuition | ]. - destruct Hbounds as [nth_nonneg nth_lt_pow2]. - apply Z.shiftr_eq_0_iff. - apply Z.le_lteq in nth_nonneg; destruct nth_nonneg; try solve [left; auto]. - right; split; auto. - apply Z.log2_lt_pow2; auto. - Qed. - - Lemma carry_decode_eq_reduce : forall us, - (length us = length limb_widths) -> - BaseSystem.decode base (carry_and_reduce (pred (length limb_widths)) us) mod modulus - = BaseSystem.decode base us mod modulus. - Proof using Type. - cbv [carry_and_reduce]; intros. - rewrite carry_gen_decode_eq; auto. - distr_length. - assert (0 < length limb_widths)%nat by (pose proof limb_widths_nonnil; - destruct limb_widths; distr_length; congruence). - break_match; repeat rewrite ?pred_mod, ?Nat.succ_pred,?Nat.mod_same in * by omega; - try omega. - rewrite !nth_default_base by (auto || destruct (length limb_widths); auto). - rewrite sum_firstn_0. - autorewrite with zsimplify. - match goal with |- appcontext[2 ^ ?a * ?b * 2 ^ ?c] => - replace (2 ^ a * b * 2 ^ c) with (2 ^ (a + c) * b) end. - { rewrite <-sum_firstn_succ by (apply nth_error_Some_nth_default; destruct (length limb_widths); auto). - rewrite Nat.succ_pred by omega. - remember (pred (length limb_widths)) as pred_len. - fold k. - rewrite <-Z.mul_sub_distr_r. - replace (c - 2 ^ k) with (modulus * -1) by (cbv [c]; ring). - rewrite <-Z.mul_assoc. - apply Z.mod_add_l'. - pose proof prime_modulus. Z.prime_bound. } - { rewrite Z.pow_add_r; auto using log_cap_nonneg, sum_firstn_limb_widths_nonneg. - rewrite <-!Z.mul_assoc. - apply Z.mul_cancel_l; try ring. - apply Z.pow_nonzero; (omega || auto using log_cap_nonneg). } - Qed. - - Lemma carry_rep : forall i us x, - (length us = length limb_widths)%nat -> - (i < length limb_widths)%nat -> - forall pf1 pf2, - from_list _ us pf1 ~= x -> from_list _ (carry i us) pf2 ~= x. - Proof using Type. - cbv [carry rep decode]; intros. - rewrite to_list_from_list. - pose proof carry_decode_eq_reduce. pose proof (@carry_simple_decode_eq limb_widths). - - specialize_by eauto. - cbv [ModularBaseSystemList.carry]. - break_match; subst; eauto. - apply F.eq_of_Z_iff. - rewrite to_list_from_list. - apply carry_decode_eq_reduce. auto. - cbv [ModularBaseSystemList.decode]. - apply F.eq_of_Z_iff. - rewrite to_list_from_list, carry_simple_decode_eq; try omega; distr_length; auto. - Qed. - Hint Resolve carry_rep. - - Lemma decode_mod_Fdecode : forall u, length u = length limb_widths -> - BaseSystem.decode base u mod modulus= F.to_Z (decode (from_list_default 0 _ u)). - Proof using Type. - intros. - rewrite <-(to_list_from_list _ u) with (pf := H). - erewrite Fdecode_decode_mod by reflexivity. - rewrite to_list_from_list. - rewrite from_list_default_eq with (pf := H). - reflexivity. - Qed. - - Lemma carry_sequence_rep : forall is us x, - (forall i, In i is -> (i < length limb_widths)%nat) -> - us ~= x -> forall pf, from_list _ (carry_sequence is (to_list _ us)) pf ~= x. - Proof using Type. - induction is; intros. - + cbv [carry_sequence fold_right]. rewrite from_list_to_list. assumption. - + simpl. apply carry_rep with (pf1 := length_carry_sequence (length_to_list us)); - auto using length_carry_sequence, length_to_list, in_eq. - apply IHis; auto using in_cons. - Qed. - - Context `{cc : CarryChain limb_widths}. - Lemma carry_mul_rep : forall us vs x y, - rep us x -> rep vs y -> - rep (carry_mul carry_chain us vs) (x * y)%F. - Proof using Type. - cbv [carry_mul]; intros; apply carry_sequence_rep; - auto using carry_chain_valid, mul_rep. - Qed. - - Lemma carry_sub_rep : forall coeff coeff_mod a b, - eq - (carry_sub carry_chain coeff coeff_mod a b) - (sub coeff coeff_mod a b). - Proof using Type. - cbv [carry_sub carry_]; intros. - eapply carry_sequence_rep; auto using carry_chain_valid. - reflexivity. - Qed. - - Lemma carry_add_rep : forall a b, - eq (carry_add carry_chain a b) (add a b). - Proof using Type. - cbv [carry_add carry_]; intros. - eapply carry_sequence_rep; auto using carry_chain_valid. - reflexivity. - Qed. - - Lemma carry_opp_rep : forall coeff coeff_mod a, - eq - (carry_opp carry_chain coeff coeff_mod a) - (opp coeff coeff_mod a). - Proof using Type. - cbv [carry_opp opp]; intros. - apply carry_sub_rep. - Qed. - -End CarryProofs. - -Hint Rewrite @length_carry_and_reduce @length_carry : distr_length. - -Class FreezePreconditions `{prm : PseudoMersenneBaseParams} B int_width := - { - lt_1_length_limb_widths : (1 < length limb_widths)%nat; - int_width_pos : 0 < int_width; - B_le_int_width : B <= int_width; - B_pos : 0 < B; - B_compat : forall w, In w limb_widths -> w < B; - (* on the first reduce step, we add at most one bit of width to the first digit *) - c_reduce1 : c * ((2 ^ B) >> nth_default 0 limb_widths (pred (length limb_widths))) <= 2 ^ (nth_default 0 limb_widths 0); - (* on the second reduce step, we add at most one bit of width to the first digit, - and leave room to carry c one more time after the highest bit is carried *) - c_reduce2 : c <= 2 ^ (nth_default 0 limb_widths 0) - c - }. - -Section CanonicalizationProofs. - Context `{freeze_pre : FreezePreconditions}. - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation digits := (tuple Z (length limb_widths)). - Local Hint Resolve (@limb_widths_nonneg _ prm) sum_firstn_limb_widths_nonneg. - Local Hint Resolve log_cap_nonneg. - Local Notation "u [ i ]" := (nth_default 0 u i). - Local Notation "u {{ i }}" := (carry_sequence (make_chain i) u) (at level 30). (* Can't rely on [Reserved Notation]: https://coq.inria.fr/bugs/show_bug.cgi?id=4970 *) - - Lemma nth_default_carry_and_reduce_full : forall n i us, - (carry_and_reduce i us) [n] - = if lt_dec n (length us) - then - (if eq_nat_dec n (i mod length limb_widths) - then Z.pow2_mod (us [n]) (limb_widths [n]) - else us [n]) + - if eq_nat_dec n (S (i mod length limb_widths) mod length limb_widths) - then c * (us [i mod length limb_widths]) >> (limb_widths [i mod length limb_widths]) - else 0 - else 0. - Proof using Type. - cbv [carry_and_reduce]; intros. - autorewrite with push_nth_default. - reflexivity. - Qed. - Hint Rewrite @nth_default_carry_and_reduce_full : push_nth_default. - - Lemma nth_default_carry_full : forall n i us, - length us = length limb_widths -> - (carry i us) [n] - = if lt_dec n (length us) - then - if eq_nat_dec i (pred (length limb_widths)) - then (if eq_nat_dec n i - then Z.pow2_mod (us [n]) (limb_widths [n]) - else us [n]) + - if eq_nat_dec n 0 - then c * ((us [i]) >> (limb_widths [i])) - else 0 - else if eq_nat_dec n i - then Z.pow2_mod (us [n]) (limb_widths [n]) - else us [n] + - if eq_nat_dec n (S i) - then (us [i]) >> (limb_widths [i]) - else 0 - else 0. - Proof using Type*. - intros. - cbv [carry]. - break_innermost_match_step. - + subst i. - pose proof lt_1_length_limb_widths. - autorewrite with push_nth_default natsimplify. - destruct (eq_nat_dec (length limb_widths) (length us)); congruence. - + autorewrite with push_nth_default; reflexivity. - Qed. - Hint Rewrite @nth_default_carry_full : push_nth_default. - - Lemma nth_default_carry_sequence_make_chain_full : forall i n us, - length us = length limb_widths -> - (i <= length limb_widths)%nat -> - us {{ i }} [n] - = if lt_dec n (length limb_widths) - then - if eq_nat_dec i 0 - then nth_default 0 us n - else - if lt_dec i (length limb_widths) - then - if lt_dec n i - then - if eq_nat_dec n (pred i) - then Z.pow2_mod (us {{ pred i }} [n]) (limb_widths [n]) - else us{{ pred i }} [n] - else us{{ pred i}} [n] + - (if eq_nat_dec n i - then (us{{ pred i}} [pred i]) >> (limb_widths [pred i]) - else 0) - else - if lt_dec n (pred i) - then us {{ pred i }} [n] + - (if eq_nat_dec n 0 - then c * (us{{ pred i}} [pred i]) >> (limb_widths [pred i]) - else 0) - else Z.pow2_mod (us {{ pred i }} [n]) (limb_widths [n]) - else 0. - Proof using Type*. - induction i; intros; cbv [carry_sequence]. - + cbv [pred make_chain fold_right]. - break_match; subst; omega || reflexivity || auto using Z.add_0_r. - apply nth_default_out_of_bounds. omega. - + replace (make_chain (S i)) with (i :: make_chain i) by reflexivity. - rewrite fold_right_cons. - pose proof lt_1_length_limb_widths. - autorewrite with push_nth_default natsimplify; - rewrite ?Nat.pred_succ; fold (carry_sequence (make_chain i) us); - rewrite length_carry_sequence; auto. - repeat (break_innermost_match_step; try omega). - Qed. - - Lemma nth_default_carry : forall i us, - length us = length limb_widths -> - (i < length us)%nat -> - nth_default 0 (carry i us) i - = Z.pow2_mod (us [i]) (limb_widths [i]). - Proof using Type*. - intros; pose proof lt_1_length_limb_widths; autorewrite with push_nth_default natsimplify; break_match; omega. - Qed. - Hint Rewrite @nth_default_carry using (omega || distr_length; omega) : push_nth_default. - - Lemma pow_limb_widths_gt_1 : forall i, (i < length limb_widths)%nat -> - 1 < 2 ^ limb_widths [i]. - Proof using Type. - intros. - apply Z.pow_gt_1; try omega. - apply nth_default_preserves_properties_length_dep; intros; try omega. - auto using limb_widths_pos. - Qed. - - Lemma carry_sequence_nil_l : forall us, carry_sequence nil us = us. - Proof using Type. - reflexivity. - Qed. - - Ltac bound_during_loop := - repeat match goal with - | |- _ => progress (intros; subst) - | |- _ => unique pose proof lt_1_length_limb_widths - | |- _ => unique pose proof c_reduce2 - | |- _ => break_innermost_match_step; try omega - | |- _ => break_innermost_match_hyps_step; try omega - | |- _ => progress simpl pred in * - | |- _ => progress rewrite ?Z.add_0_r, ?Z.sub_0_r in * - | |- _ => rewrite nth_default_out_of_bounds by omega - | |- _ => rewrite nth_default_carry_sequence_make_chain_full by auto - | H : forall n, 0 <= _ [n] < _ |- appcontext [ _ [?n] ] => pose proof (H (pred n)); specialize (H n) - | H : forall n, (n < ?m)%nat -> 0 <= _ [n] < _ |- appcontext [ _ [?n] ] => pose proof (H (pred n)); specialize (H n); specialize_by omega - | |- appcontext [make_chain 0] => simpl make_chain; rewrite carry_sequence_nil_l - | |- 0 <= ?a + c * ?b < 2 * ?d => unique assert (c * b <= d); - [ | solve [pose proof c_pos; rewrite <-Z.add_diag; split; zero_bounds] ] - | |- c * (?e >> (limb_widths[?i])) <= ?b => - pose proof (Z.shiftr_le e (2 ^ B) (limb_widths [i])); specialize_by (auto || omega); - replace (limb_widths [i]) with (limb_widths [pred (length limb_widths)]) in * by (f_equal; omega); - etransitivity; [ | apply c_reduce1]; apply Z.mul_le_mono_pos_l; try apply c_pos; omega - | H : 0 <= _ < ?b - (?c >> ?d) |- 0 <= _ + (?e >> ?d) < ?b => - pose proof (Z.shiftr_le e c d); specialize_by (auto || omega); solve [split; zero_bounds] - | IH : forall n, _ -> 0 <= ?u {{ ?i }} [n] < _ - |- 0 <= ?u {{ ?i }} [?n] < _ => specialize (IH n) - | IH : forall n, _ -> 0 <= ?u {{ ?i }} [n] < _ - |- appcontext [(?u {{ ?i }} [?n]) >> _] => pose proof (IH 0%nat); pose proof (IH (S n)); specialize (IH n); specialize_by omega - | H : 0 <= ?a < 2 ^ ?n + ?x |- appcontext [?a >> ?n] => - assert (x < 2 ^ n) by (omega || auto using pow_limb_widths_gt_1); - unique assert (0 <= a < 2 * 2 ^ n) by omega - | H : 0 <= ?a < 2 * 2 ^ ?n |- appcontext [?a >> ?n] => - pose proof c_pos; - apply Z.lt_mul_2_pow_2_shiftr in H; (break_innermost_match_step || break_innermost_match_hyps_step); rewrite H; omega - | H : 0 <= ?a < 2 ^ ?n |- appcontext [?a >> ?n] => - pose proof c_pos; - apply Z.lt_pow_2_shiftr in H; rewrite H; omega - | |- 0 <= Z.pow2_mod _ _ < c => - rewrite Z.pow2_mod_spec, Z.lt_mul_2_mod_sub; auto; omega - | |- _ => apply Z.pow2_mod_pos_bound, limb_widths_pos, nth_default_preserves_properties_length_dep; [tauto | omega] - | |- 0 <= 0 < _ => solve[split; zero_bounds] - | |- _ => omega - end. - - Lemma bound_during_first_loop : forall us, - length us = length limb_widths -> - (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < 2 ^ B - if eq_nat_dec n 0 then 0 else ((2 ^ B) >> (limb_widths [pred n]))) -> - forall i n, - (i <= length limb_widths)%nat -> - 0 <= us{{i}}[n] < if eq_nat_dec i 0 then us[n] + 1 else - if lt_dec i (length limb_widths) - then - if lt_dec n i - then 2 ^ (limb_widths [n]) - else if eq_nat_dec n i - then 2 ^ B - else us[n] + 1 - else - if eq_nat_dec n 0 - then 2 * 2 ^ limb_widths [n] - else 2 ^ limb_widths [n]. - Proof using Type*. - induction i; bound_during_loop. - Qed. - - Lemma bound_after_loop_length_preconditions : forall us (Hlength : length us = length limb_widths) - {bound bound' bound'' : list Z -> nat -> Z} - {X Y : list Z -> nat -> nat -> Z} f, - (forall us, length us = length limb_widths - -> (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < bound' us n) - -> forall i n, (i <= length limb_widths)%nat - -> 0 <= us{{i}}[n] < if eq_nat_dec i 0 then X us i n else - if lt_dec i (length limb_widths) - then Y us i n - else bound'' us n) -> - ((forall n, (n < length limb_widths)%nat -> 0 <= us [n] < bound us n) - -> forall n, (n < length limb_widths)%nat -> 0 <= (f us) [n] < bound' (f us) n) -> - length (f us) = length limb_widths -> - (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < bound us n) - -> forall n, (n < length limb_widths)%nat -> 0 <= (carry_full (f us)) [n] < bound'' (f us) n. - Proof using Type*. - pose proof lt_1_length_limb_widths. - cbv [carry_full full_carry_chain]; intros ? ? ? ? ? ? ? ? Hloop Hfbound Hflength Hbound n. - specialize (Hfbound Hbound). - specialize (Hloop (f us) Hflength Hfbound (length limb_widths) n). - specialize_by omega. - repeat (omega || break_innermost_match_step || break_innermost_match_hyps_step). - Qed. - - Lemma bound_after_loop : forall us (Hlength : length us = length limb_widths) - {bound bound' bound'' : list Z -> nat -> Z} - {X Y : list Z -> nat -> nat -> Z} f, - (forall us, length us = length limb_widths - -> (forall n, 0 <= us [n] < bound' us n) - -> forall i n, (i <= length limb_widths)%nat - -> 0 <= us{{i}}[n] < if eq_nat_dec i 0 then X us i n else - if lt_dec i (length limb_widths) - then Y us i n - else bound'' us n) -> - ((forall n, (n < length limb_widths)%nat -> 0 <= us [n] < bound us n) - -> forall n, 0 <= (f us) [n] < bound' (f us) n) - -> length (f us) = length limb_widths - -> (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < bound us n) - -> forall n, 0 <= (carry_full (f us)) [n] < bound'' (f us) n. - Proof using Type*. - pose proof lt_1_length_limb_widths. - cbv [carry_full full_carry_chain]; intros ? ? ? ? ? ? ? ? Hloop Hfbound Hflength Hbound n. - specialize (Hfbound Hbound). - specialize (Hloop (f us) Hflength Hfbound (length limb_widths) n). - specialize_by omega. - repeat (omega || break_innermost_match_step || break_innermost_match_hyps_step). - Qed. - - Lemma bound_after_first_loop_pre : forall us, - length us = length limb_widths -> - (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < 2 ^ B - if eq_nat_dec n 0 then 0 else ((2 ^ B) >> (limb_widths [pred n]))) -> - forall n, (n < length limb_widths)%nat -> - 0 <= (carry_full us)[n] < - if eq_nat_dec n 0 - then 2 * 2 ^ limb_widths [n] - else 2 ^ limb_widths [n]. - Proof using Type*. - intros ? ?. - apply (bound_after_loop_length_preconditions us H id bound_during_first_loop); auto. - Qed. - - Lemma bound_after_first_loop : forall us, - length us = length limb_widths -> - (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < 2 ^ B - if eq_nat_dec n 0 then 0 else ((2 ^ B) >> (limb_widths [pred n]))) -> - forall n, - 0 <= (carry_full us)[n] < - if eq_nat_dec n 0 - then 2 * 2 ^ limb_widths [n] - else 2 ^ limb_widths [n]. - Proof using Type*. - intros. - destruct (lt_dec n (length limb_widths)); - auto using bound_after_first_loop_pre. - rewrite !nth_default_out_of_bounds by (rewrite ?length_carry_full; omega). - autorewrite with zsimplify. - rewrite Z.pow_0_r. - break_innermost_match_step; omega. - Qed. - - Lemma bound_during_second_loop : forall us, - length us = length limb_widths -> - (forall n, 0 <= us [n] < if eq_nat_dec n 0 then 2 * 2 ^ limb_widths [n] else 2 ^ limb_widths [n]) -> - forall i n, - (i <= length limb_widths)%nat -> - 0 <= us{{i}}[n] < if eq_nat_dec i 0 then us[n] + 1 else - if lt_dec i (length limb_widths) - then - if lt_dec n i - then 2 ^ (limb_widths [n]) - else if eq_nat_dec n i - then 2 * 2 ^ limb_widths [n] - else us[n] + 1 - else - if eq_nat_dec n 0 - then 2 ^ limb_widths [n] + c - else 2 ^ limb_widths [n]. - Proof using Type*. - induction i; bound_during_loop. - Qed. - - Lemma bound_after_second_loop : forall us, - length us = length limb_widths -> - (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < 2 ^ B - if eq_nat_dec n 0 then 0 else ((2 ^ B) >> (limb_widths [pred n]))) -> - forall n, - 0 <= (carry_full (carry_full us)) [n] < - if eq_nat_dec n 0 - then 2 ^ limb_widths [n] + c - else 2 ^ limb_widths [n]. - Proof using Type*. - intros ? ?; apply (bound_after_loop us H carry_full bound_during_second_loop); - auto using length_carry_full, bound_after_first_loop. - Qed. - - Lemma bound_during_third_loop : forall us, - length us = length limb_widths -> - (forall n, 0 <= us [n] < if eq_nat_dec n 0 then 2 ^ limb_widths [n] + c else 2 ^ limb_widths [n]) -> - forall i n, - (i <= length limb_widths)%nat -> - 0 <= us{{i}}[n] < if eq_nat_dec i 0 then us[n] + 1 else - if lt_dec i (length limb_widths) - then - if Z_lt_dec (us [0]) (2 ^ limb_widths [0]) - then - 2 ^ limb_widths [n] - else - if eq_nat_dec n 0 - then c - else - if lt_dec n i - then 2 ^ limb_widths [n] - else if eq_nat_dec n i - then 2 ^ limb_widths [n] + 1 - else us[n] + 1 - else - 2 ^ limb_widths [n]. - Proof using Type*. - induction i; bound_during_loop. - Qed. - - Lemma bound_after_third_loop : forall us, - length us = length limb_widths -> - (forall n, (n < length limb_widths)%nat -> 0 <= us [n] < 2 ^ B - if eq_nat_dec n 0 then 0 else ((2 ^ B) >> (limb_widths [pred n]))) -> - forall n, - 0 <= (carry_full (carry_full (carry_full us))) [n] < 2 ^ limb_widths [n]. - Proof using Type*. - intros ? ?. - apply (bound_after_loop us H (fun x => carry_full (carry_full x)) bound_during_third_loop); - auto using length_carry_full, bound_after_second_loop. - Qed. - - Local Notation initial_bounds u := - (forall n : nat, (n < length limb_widths)%nat -> - 0 <= to_list (length limb_widths) u [n] < - 2 ^ B - - (if eq_nat_dec n 0 - then 0 - else (2 ^ B) >> (limb_widths [pred n]))). - Local Notation minimal_rep u := ((bounded limb_widths (to_list (length limb_widths) u)) - /\ (ge_modulus (to_list _ u) = 0)). - - Lemma decode_bitwise_eq_iff : forall u v, minimal_rep u -> minimal_rep v -> - (fieldwise Logic.eq u v <-> - decode_bitwise limb_widths (to_list _ u) = decode_bitwise limb_widths (to_list _ v)). - Proof using Type. - intros. - rewrite !decode_bitwise_spec by (tauto || auto using length_to_list). - rewrite fieldwise_to_list_iff. - split; intros. - + apply decode_Proper; auto. - + apply Forall2_forall_iff with (d := 0); intros; repeat rewrite @length_to_list in *; auto. - erewrite digit_select with (us := to_list _ u) by intuition eauto. - erewrite digit_select with (us := to_list _ v) by intuition eauto. - rewrite H1; reflexivity. - Qed. - - Lemma c_upper_bound : c - 1 < 2 ^ limb_widths[0]. - Proof using Type*. - pose proof c_reduce2. pose proof c_pos. - omega. - Qed. - Hint Resolve c_upper_bound. - - Lemma minimal_rep_encode : forall x, minimal_rep (encode x). - Proof using Type*. - split; intros; auto using bounded_encode. - apply ge_modulus_spec; auto using bounded_encode, length_to_list. - apply encode_range. - Qed. - - Lemma encode_minimal_rep : forall u x, rep u x -> minimal_rep u -> - fieldwise Logic.eq u (encode x). - Proof using Type*. - intros. - apply decode_bitwise_eq_iff; auto using minimal_rep_encode. - rewrite !decode_bitwise_spec by (intuition auto; distr_length; try apply minimal_rep_encode). - apply Fdecode_decode_mod in H. - pose proof (Fdecode_decode_mod _ _ (encode_rep x)). - rewrite Z.mod_small in H by (apply ge_modulus_spec; distr_length; intuition auto). - rewrite Z.mod_small in H1 by (apply ge_modulus_spec; distr_length; auto using c_upper_bound; apply minimal_rep_encode). - congruence. - Qed. - - Lemma bounded_canonical : forall u v x y, rep u x -> rep v y -> - minimal_rep u -> minimal_rep v -> - (x = y <-> fieldwise Logic.eq u v). - Proof using Type*. - intros. - eapply encode_minimal_rep in H1; eauto. - eapply encode_minimal_rep in H2; eauto. - split; intros; subst. - + etransitivity; eauto; symmetry; eauto. - + assert (fieldwise Logic.eq (encode x) (encode y)) by - (transitivity u; [symmetry; eauto | ]; transitivity v; eauto). - apply decode_bitwise_eq_iff in H4; try apply minimal_rep_encode. - rewrite !decode_bitwise_spec in H4 by (auto; distr_length; apply minimal_rep_encode). - apply F.eq_to_Z_iff. - erewrite <-!Fdecode_decode_mod by eapply encode_rep. - congruence. - Qed. - - Lemma int_width_compat : forall x, In x limb_widths -> x < int_width. - Proof using Type*. - intros. apply B_compat in H. - eapply Z.lt_le_trans; eauto using B_le_int_width. - Qed. - - Lemma minimal_rep_freeze : forall u, initial_bounds u -> - minimal_rep (freeze int_width u). - Proof using Type*. - repeat match goal with - | |- _ => progress (cbv [freeze ModularBaseSystemList.freeze]) - | |- _ => progress intros - | |- minimal_rep _ => split - | |- _ => rewrite to_list_from_list - | |- _ => apply bound_after_third_loop - | |- _ => apply conditional_subtract_lt_modulus - | |- _ => apply conditional_subtract_modulus_preserves_bounded - | |- bounded _ (carry_full _) => apply bounded_iff - | |- _ => solve [auto using Z.lt_le_incl, int_width_pos, int_width_compat, lt_1_length_limb_widths, length_carry_full, length_to_list] - end. - Qed. - - Lemma freeze_decode : forall u, - BaseSystem.decode base (to_list _ (freeze int_width u)) mod modulus = - BaseSystem.decode base (to_list _ u) mod modulus. - Proof using Type*. - repeat match goal with - | |- _ => progress cbv [freeze ModularBaseSystemList.freeze] - | |- _ => progress intros - | |- _ => rewrite <-Z.add_opp_r, <-Z.mul_opp_l - | |- _ => rewrite Z.mod_add by (pose proof prime_modulus; prime_bound) - | |- _ => rewrite to_list_from_list - | |- _ => rewrite conditional_subtract_modulus_spec by - (auto using Z.lt_le_incl, int_width_pos, int_width_compat, lt_1_length_limb_widths, length_carry_full, length_to_list, ge_modulus_01) - end. - rewrite !decode_mod_Fdecode by auto using length_carry_full, length_to_list. - cbv [carry_full]. - apply F.eq_to_Z_iff. - rewrite <-@to_list_from_list with (pf := length_carry_sequence (length_carry_sequence (length_to_list _))). - rewrite from_list_default_eq with (pf := length_carry_sequence (length_to_list _)). - rewrite carry_sequence_rep; try reflexivity; try apply make_chain_lt. - cbv [rep]. - rewrite <-from_list_default_eq with (d := 0). - erewrite <-to_list_from_list with (pf := length_carry_sequence (length_to_list _)). - rewrite from_list_default_eq with (pf := length_carry_sequence (length_to_list _)). - rewrite carry_sequence_rep; try reflexivity; try apply make_chain_lt. - cbv [rep]. - rewrite carry_sequence_rep; try reflexivity; try apply make_chain_lt. - rewrite from_list_default_eq with (pf := length_to_list _). - rewrite from_list_to_list; reflexivity. - Qed. - - Lemma freeze_rep : forall u x, rep u x -> rep (freeze int_width u) x. - Proof using Type*. - cbv [rep]; intros. - apply F.eq_to_Z_iff. - erewrite <-!Fdecode_decode_mod by eauto. - apply freeze_decode. - Qed. - - Lemma freeze_canonical : forall u v x y, rep u x -> rep v y -> - initial_bounds u -> - initial_bounds v -> - (x = y <-> fieldwise Logic.eq (freeze int_width u) (freeze int_width v)). - Proof using Type*. - intros; apply bounded_canonical; auto using freeze_rep, minimal_rep_freeze. - Qed. - -End CanonicalizationProofs. - -Section SquareRootProofs. - Context `{freeze_pre : FreezePreconditions}. - Local Notation "u ~= x" := (rep u x). - Local Notation digits := (tuple Z (length limb_widths)). - Local Notation base := (base_from_limb_widths limb_widths). - Local Hint Resolve (@limb_widths_nonneg _ prm) sum_firstn_limb_widths_nonneg. - - Definition freeze_input_bounds n := - (2 ^ B - - (if eq_nat_dec n 0 - then 0 - else (2 ^ B) >> (nth_default 0 limb_widths (pred n)))). - Definition bounded_by u bounds := - (forall n : nat, (n < length limb_widths)%nat -> - 0 <= nth_default 0 (to_list (length limb_widths) u) n < bounds n). - - Lemma eqb_true_iff : forall u v x y, - bounded_by u freeze_input_bounds -> bounded_by v freeze_input_bounds -> - u ~= x -> v ~= y -> (x = y <-> eqb int_width u v = true). - Proof using Type*. - cbv [eqb freeze_input_bounds]. intros. - rewrite fieldwiseb_fieldwise by (apply Z.eqb_eq). - eauto using freeze_canonical. - Qed. - - Lemma eqb_false_iff : forall u v x y, - bounded_by u freeze_input_bounds -> bounded_by v freeze_input_bounds -> - u ~= x -> v ~= y -> (x <> y <-> eqb int_width u v = false). - Proof using Type*. - intros. - case_eq (eqb int_width u v). - + rewrite <-eqb_true_iff by eassumption; split; intros; - congruence || contradiction. - + split; intros; auto. - intro Hfalse_eq; - rewrite (eqb_true_iff u v) in Hfalse_eq by eassumption. - congruence. - Qed. - - Section Sqrt3mod4. - Context (modulus_3mod4 : modulus mod 4 = 3). - Context {ec : ExponentiationChain (modulus / 4 + 1)}. - - Lemma sqrt_3mod4_correct : forall u x, u ~= x -> - (sqrt_3mod4 chain chain_correct u) ~= F.sqrt_3mod4 x. - Proof using Type. - repeat match goal with - | |- _ => progress (cbv [sqrt_3mod4 F.sqrt_3mod4]; intros) - | |- _ => rewrite @F.pow_2_r in * - | |- _ => rewrite eqb_correct in * by eassumption - | |- _ => rewrite <-chain_correct; apply pow_rep; eassumption - end. - Qed. - End Sqrt3mod4. - - Section Sqrt5mod8. - Context (modulus_5mod8 : modulus mod 8 = 5). - Context {ec : ExponentiationChain (modulus / 8 + 1)}. - Context (sqrt_m1 : digits) (sqrt_m1_correct : mul sqrt_m1 sqrt_m1 ~= F.opp 1%F). - - Lemma sqrt_5mod8_correct : forall u x powx powx_squared, u ~= x -> - bounded_by u freeze_input_bounds -> - bounded_by powx_squared freeze_input_bounds -> - ModularBaseSystem.eq powx (pow u chain) -> - ModularBaseSystem.eq powx_squared (mul powx powx) -> - (sqrt_5mod8 int_width powx powx_squared chain chain_correct sqrt_m1 u) ~= F.sqrt_5mod8 (decode sqrt_m1) x. - Proof using freeze_pre. - cbv [sqrt_5mod8 F.sqrt_5mod8]. - intros. - repeat match goal with - | |- _ => progress (cbv [sqrt_5mod8 F.sqrt_5mod8]; intros) - | |- _ => rewrite @F.pow_2_r in * - | |- _ => rewrite eqb_correct in * by eassumption - | |- (if eqb _ ?a ?b then _ else _) ~= - (if dec (?c = _) then _ else _) => - assert (a ~= c) by - (cbv [rep]; rewrite <-chain_correct, <-pow_rep, <-mul_rep; - eassumption); break_innermost_match - | |- _ => apply mul_rep; try reflexivity; - rewrite <-chain_correct, <-pow_rep; eassumption - | |- _ => rewrite <-chain_correct, <-pow_rep; eassumption - | H : eqb _ ?a ?b = true, H1 : ?b ~= ?y, H2 : ?a ~= ?x |- _ => - rewrite <-(eqb_true_iff a b x y) in H by eassumption - | H : eqb _ ?a ?b = false, H1 : ?b ~= ?y, H2 : ?a ~= ?x |- _ => - rewrite <-(eqb_false_iff a b x y) in H by eassumption - | |- _ => congruence - end. - Qed. - End Sqrt5mod8. - -End SquareRootProofs. - -Section ConversionProofs. - Context `{prm :PseudoMersenneBaseParams}. - Context {target_widths} - (target_widths_nonneg : forall x, In x target_widths -> 0 <= x) - (bits_eq : sum_firstn limb_widths (length limb_widths) = - sum_firstn target_widths (length target_widths)). - Local Notation target_base := (base_from_limb_widths target_widths). - - Lemma pack_rep : forall w, - bounded limb_widths (to_list _ w) -> - bounded target_widths (to_list _ w) -> - rep w (F.of_Z modulus - (BaseSystem.decode - target_base - (to_list _ (pack target_widths_nonneg bits_eq w)))). - Proof using Type. - intros; cbv [pack ModularBaseSystemList.pack rep]. - rewrite Tuple.to_list_from_list. - apply F.eq_to_Z_iff. - rewrite F.to_Z_of_Z. - rewrite <-Conversion.convert_correct; auto using length_to_list. - Qed. - - Lemma unpack_rep : forall w, - bounded target_widths (to_list _ w) -> - rep (unpack target_widths_nonneg bits_eq w) - (F.of_Z modulus (BaseSystem.decode target_base (to_list _ w))). - Proof using Type. - intros; cbv [unpack ModularBaseSystemList.unpack rep]. - apply F.eq_to_Z_iff. - rewrite <-from_list_default_eq with (d := 0). - rewrite <-decode_mod_Fdecode by apply Conversion.length_convert. - rewrite F.to_Z_of_Z. - rewrite <-Conversion.convert_correct; auto using length_to_list. - Qed. - - -End ConversionProofs. diff --git a/src/ModularArithmetic/ModularBaseSystemWord.v b/src/ModularArithmetic/ModularBaseSystemWord.v deleted file mode 100644 index 9283bfb30..000000000 --- a/src/ModularArithmetic/ModularBaseSystemWord.v +++ /dev/null @@ -1,23 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Coq.Lists.List. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.Notations. -Require Import Bedrock.Word. -Local Open Scope Z_scope. - -Section conditional_subtract_modulus. - Context {int_width num_limbs : nat}. - Local Notation limb := (word int_width). - Local Notation digits := (tuple limb num_limbs). - Local Notation zero := (natToWord int_width 0). - Local Notation one := (natToWord int_width 1). - Local Notation "u [ i ]" := (nth_default zero u i). - Context (modulus : digits). - Context (ge_modulusW : digits -> limb) (negW : limb -> limb). - - Definition conditional_subtract_modulusW (us : digits) := - (* [and_term] is all ones if us' is full, so the subtractions subtract q overall. - Otherwise, it's all zeroes, and the subtractions do nothing. *) - map2 (fun x y => wminus x y) us (map (wand (negW (ge_modulusW us))) modulus). - -End conditional_subtract_modulus.
\ No newline at end of file diff --git a/src/ModularArithmetic/Pow2Base.v b/src/ModularArithmetic/Pow2Base.v deleted file mode 100644 index 0175018f8..000000000 --- a/src/ModularArithmetic/Pow2Base.v +++ /dev/null @@ -1,89 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. -Require Import Crypto.Util.ListUtil. -Require Import Crypto.Util.ZUtil. -Require Crypto.BaseSystem. -Require Import Coq.Lists.List. - -Local Open Scope Z_scope. - -Section Pow2Base. - Context (limb_widths : list Z). - Local Notation "w[ i ]" := (nth_default 0 limb_widths i). - - Fixpoint base_from_limb_widths limb_widths := - match limb_widths with - | nil => nil - | w :: lw => 1 :: map (Z.mul (two_p w)) (base_from_limb_widths lw) - end. - - Local Notation base := (base_from_limb_widths limb_widths). - - - Definition bounded us := forall i, 0 <= nth_default 0 us i < 2 ^ w[i]. - - Definition upper_bound := 2 ^ (sum_firstn limb_widths (length limb_widths)). - - Function decode_bitwise' us i acc := - match i with - | O => acc - | S i' => decode_bitwise' us i' (Z.lor (nth_default 0 us i') (Z.shiftl acc w[i'])) - end. - - Definition decode_bitwise us := decode_bitwise' us (length us) 0. - - (* i is current index, counts down *) - Fixpoint encode' z i := - match i with - | O => nil - | S i' => let lw := sum_firstn limb_widths in - encode' z i' ++ (Z.shiftr (Z.land z (Z.ones (lw i))) (lw i')) :: nil - end. - - Definition encodeZ x:= encode' x (length limb_widths). - - (** ** Carrying *) - Section carrying. - (** Here we implement addition and multiplication with simple - carrying. *) - Notation log_cap i := (nth_default 0 limb_widths i). - - Definition add_to_nth n (x:Z) xs := - update_nth n (fun y => x + y) xs. - Definition carry_single i := fun di => - (Z.pow2_mod di (log_cap i), - Z.shiftr di (log_cap i)). - - (* [fi] is fed [length us] and [S i] and produces the index of - the digit to which value should be added; - [fc] modifies the carried value before adding it to that digit *) - Definition carry_gen fc fi i := fun us => - let i := fi i in - let di := nth_default 0 us i in - let '(di', ci) := carry_single i di in - let us' := set_nth i di' us in - add_to_nth (fi (S i)) (fc ci) us'. - - (* carry_simple does not modify the carried value, and always adds it - to the digit with index [S i] *) - Definition carry_simple := carry_gen (fun ci => ci) (fun i => i). - - Definition carry_simple_sequence is us := fold_right carry_simple us is. - - Fixpoint make_chain i := - match i with - | O => nil - | S i' => i' :: make_chain i' - end. - - Definition full_carry_chain := make_chain (length limb_widths). - - Definition carry_simple_full := carry_simple_sequence full_carry_chain. - - Definition carry_simple_add us vs := carry_simple_full (BaseSystem.add us vs). - - Definition carry_simple_sub us vs := carry_simple_full (BaseSystem.sub us vs). - - Definition carry_simple_mul out_base us vs := carry_simple_full (BaseSystem.mul out_base us vs). - End carrying. - -End Pow2Base. diff --git a/src/ModularArithmetic/Pow2BaseProofs.v b/src/ModularArithmetic/Pow2BaseProofs.v deleted file mode 100644 index 7a5bb4255..000000000 --- a/src/ModularArithmetic/Pow2BaseProofs.v +++ /dev/null @@ -1,1557 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.micromega.Psatz. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Coq.Lists.List. -Require Import Coq.funind.Recdef. -Require Import Crypto.Util.ListUtil Crypto.Util.ZUtil Crypto.Util.NatUtil. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.Tactics.SpecializeBy. -Require Import Crypto.Util.Tactics.BreakMatch. -Require Import Crypto.Util.Tactics.UniquePose. -Require Import Crypto.Util.Tactics.RewriteHyp. -Require Import Crypto.ModularArithmetic.Pow2Base Crypto.BaseSystemProofs. -Require Import Crypto.Util.Notations. -Require Export Crypto.Util.Bool. -Require Export Crypto.Util.FixCoqMistakes. -Require Crypto.BaseSystem. -Local Open Scope Z_scope. - -Create HintDb simpl_add_to_nth discriminated. -Create HintDb push_upper_bound discriminated. -Create HintDb pull_upper_bound discriminated. -Create HintDb push_base_from_limb_widths discriminated. -Create HintDb pull_base_from_limb_widths discriminated. - -Hint Extern 1 => progress autorewrite with push_upper_bound in * : push_upper_bound. -Hint Extern 1 => progress autorewrite with pull_upper_bound in * : pull_upper_bound. -Hint Extern 1 => progress autorewrite with push_base_from_limb_widths in * : push_base_from_limb_widths. -Hint Extern 1 => progress autorewrite with pull_base_from_limb_widths in * : pull_base_from_limb_widths. - -Section Pow2BaseProofs. - Context {limb_widths} (limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w). - Local Notation base := (base_from_limb_widths limb_widths). - - Lemma base_from_limb_widths_length ls : length (base_from_limb_widths ls) = length ls. - Proof using Type. - clear limb_widths limb_widths_nonneg. - induction ls; [ reflexivity | simpl in * ]. - autorewrite with distr_length; auto. - Qed. - Hint Rewrite base_from_limb_widths_length : distr_length. - - Lemma base_from_limb_widths_cons : forall l0 l, - base_from_limb_widths (l0 :: l) = 1 :: map (Z.mul (two_p l0)) (base_from_limb_widths l). - Proof using Type. reflexivity. Qed. - Hint Rewrite base_from_limb_widths_cons : push_base_from_limb_widths. - Hint Rewrite <- base_from_limb_widths_cons : pull_base_from_limb_widths. - - Lemma base_from_limb_widths_nil : base_from_limb_widths nil = nil. - Proof using Type. reflexivity. Qed. - Hint Rewrite base_from_limb_widths_nil : push_base_from_limb_widths. - - Lemma firstn_base_from_limb_widths : forall n, firstn n (base_from_limb_widths limb_widths) = base_from_limb_widths (firstn n limb_widths). - Proof using Type. - clear limb_widths_nonneg. (* don't use this in the inductive hypothesis *) - induction limb_widths as [|l ls IHls]; intros [|n]; try reflexivity. - autorewrite with push_base_from_limb_widths push_firstn; boring. - Qed. - Hint Rewrite <- @firstn_base_from_limb_widths : push_base_from_limb_widths. - Hint Rewrite <- @firstn_base_from_limb_widths : pull_firstn. - Hint Rewrite @firstn_base_from_limb_widths : pull_base_from_limb_widths. - Hint Rewrite @firstn_base_from_limb_widths : push_firstn. - - Lemma sum_firstn_limb_widths_nonneg : forall n, 0 <= sum_firstn limb_widths n. - Proof using Type*. - unfold sum_firstn; intros. - apply fold_right_invariant; try omega. - eauto using Z.add_nonneg_nonneg, limb_widths_nonneg, In_firstn. - Qed. Hint Resolve sum_firstn_limb_widths_nonneg. - - Lemma two_sum_firstn_limb_widths_pos n : 0 < 2^sum_firstn limb_widths n. - Proof using Type*. auto with zarith. Qed. - - Lemma two_sum_firstn_limb_widths_nonzero n : 2^sum_firstn limb_widths n <> 0. - Proof using Type*. pose proof (two_sum_firstn_limb_widths_pos n); omega. Qed. - - Lemma base_from_limb_widths_step : forall i b w, (S i < length limb_widths)%nat -> - nth_error base i = Some b -> - nth_error limb_widths i = Some w -> - nth_error base (S i) = Some (two_p w * b). - Proof using Type. - clear limb_widths_nonneg. (* don't use this in the inductive hypothesis *) - induction limb_widths; intros ? ? ? ? nth_err_w nth_err_b; - unfold base_from_limb_widths in *; fold base_from_limb_widths in *; - [rewrite (@nil_length0 Z) in *; omega | ]. - simpl in *. - case_eq i; intros; subst. - + subst; apply nth_error_first in nth_err_w. - apply nth_error_first in nth_err_b; subst. - apply map_nth_error. - case_eq l; intros; subst; [simpl in *; omega | ]. - unfold base_from_limb_widths; fold base_from_limb_widths. - reflexivity. - + simpl in nth_err_w. - apply nth_error_map in nth_err_w. - destruct nth_err_w as [x [A B] ]. - subst. - replace (two_p w * (two_p a * x)) with (two_p a * (two_p w * x)) by ring. - apply map_nth_error. - apply IHl; auto. omega. - Qed. - - - Lemma nth_error_base : forall i, (i < length limb_widths)%nat -> - nth_error base i = Some (two_p (sum_firstn limb_widths i)). - Proof using Type*. - induction i; intros. - + unfold sum_firstn, base_from_limb_widths in *; case_eq limb_widths; try reflexivity. - intro lw_nil; rewrite lw_nil, (@nil_length0 Z) in *; omega. - + assert (i < length limb_widths)%nat as lt_i_length by omega. - specialize (IHi lt_i_length). - destruct (nth_error_length_exists_value _ _ lt_i_length) as [w nth_err_w]. - erewrite base_from_limb_widths_step; eauto. - f_equal. - simpl. - destruct (NPeano.Nat.eq_dec i 0). - - subst; unfold sum_firstn; simpl. - apply nth_error_exists_first in nth_err_w. - destruct nth_err_w as [l' lw_destruct]; subst. - simpl; ring_simplify. - f_equal; ring. - - erewrite sum_firstn_succ; eauto. - symmetry. - apply two_p_is_exp; auto using sum_firstn_limb_widths_nonneg. - apply limb_widths_nonneg. - eapply nth_error_value_In; eauto. - Qed. - - Lemma nth_default_base : forall d i, (i < length limb_widths)%nat -> - nth_default d base i = 2 ^ (sum_firstn limb_widths i). - Proof using Type*. - intros ? ? i_lt_length. - apply nth_error_value_eq_nth_default. - rewrite nth_error_base, two_p_correct by assumption. - reflexivity. - Qed. - - Lemma base_succ : forall i, ((S i) < length limb_widths)%nat -> - nth_default 0 base (S i) mod nth_default 0 base i = 0. - Proof using Type*. - intros. - repeat rewrite nth_default_base by omega. - apply Z.mod_same_pow. - split; [apply sum_firstn_limb_widths_nonneg | ]. - destruct (NPeano.Nat.eq_dec i 0); subst. - + case_eq limb_widths; intro; unfold sum_firstn; simpl; try omega; intros l' lw_eq. - apply Z.add_nonneg_nonneg; try omega. - apply limb_widths_nonneg. - rewrite lw_eq. - apply in_eq. - + assert (i < length limb_widths)%nat as i_lt_length by omega. - apply nth_error_length_exists_value in i_lt_length. - destruct i_lt_length as [x nth_err_x]. - erewrite sum_firstn_succ; eauto. - apply nth_error_value_In in nth_err_x. - apply limb_widths_nonneg in nth_err_x. - omega. - Qed. - - Lemma nth_error_subst : forall i b, nth_error base i = Some b -> - b = 2 ^ (sum_firstn limb_widths i). - Proof using Type*. - intros i b nth_err_b. - pose proof (nth_error_value_length _ _ _ _ nth_err_b). - rewrite base_from_limb_widths_length in *. - rewrite nth_error_base in nth_err_b by assumption. - rewrite two_p_correct in nth_err_b. - congruence. - Qed. - - Lemma base_positive : forall b : Z, In b base -> b > 0. - Proof using Type*. - intros b In_b_base. - apply In_nth_error_value in In_b_base. - destruct In_b_base as [i nth_err_b]. - apply nth_error_subst in nth_err_b. - rewrite nth_err_b. - apply Z.gt_lt_iff. - apply Z.pow_pos_nonneg; omega || auto using sum_firstn_limb_widths_nonneg. - Qed. - - Lemma b0_1 : forall x : Z, limb_widths <> nil -> nth_default x base 0 = 1. - Proof using Type. - case_eq limb_widths; intros; [congruence | reflexivity]. - Qed. - - Lemma base_from_limb_widths_app : forall l0 l - (l0_nonneg : forall x, In x l0 -> 0 <= x) - (l_nonneg : forall x, In x l -> 0 <= x), - base_from_limb_widths (l0 ++ l) - = base_from_limb_widths l0 ++ map (Z.mul (two_p (sum_firstn l0 (length l0)))) (base_from_limb_widths l). - Proof using Type. - induction l0 as [|?? IHl0]. - { simpl; intros; rewrite <- map_id at 1; apply map_ext; intros; omega. } - { simpl; intros; rewrite !IHl0, !map_app, map_map, sum_firstn_succ_cons, two_p_is_exp by auto with znonzero. - do 2 f_equal; apply map_ext; intros; lia. } - Qed. - - Lemma skipn_base_from_limb_widths : forall n, skipn n (base_from_limb_widths limb_widths) = map (Z.mul (two_p (sum_firstn limb_widths n))) (base_from_limb_widths (skipn n limb_widths)). - Proof using Type*. - intro n; pose proof (base_from_limb_widths_app (firstn n limb_widths) (skipn n limb_widths)) as H. - specialize_by eauto using In_firstn, In_skipn. - autorewrite with simpl_firstn simpl_skipn in *. - rewrite H, skipn_app, skipn_all by auto with arith distr_length; clear H. - simpl; distr_length. - apply Min.min_case_strong; intro; - unfold sum_firstn; autorewrite with natsimplify simpl_skipn simpl_firstn; - reflexivity. - Qed. - Hint Rewrite <- @skipn_base_from_limb_widths : push_base_from_limb_widths. - Hint Rewrite <- @skipn_base_from_limb_widths : pull_skipn. - Hint Rewrite @skipn_base_from_limb_widths : pull_base_from_limb_widths. - Hint Rewrite @skipn_base_from_limb_widths : push_skipn. - - Lemma pow2_mod_bounded :forall lw us i, (forall w, In w lw -> 0 <= w) -> bounded lw us -> - Z.pow2_mod (nth_default 0 us i) (nth_default 0 lw i) = nth_default 0 us i. - Proof using Type. - clear. - repeat match goal with - | |- _ => progress (cbv [bounded]; intros) - | |- _ => break_if - | |- _ => apply Z.bits_inj' - | |- _ => rewrite Z.testbit_pow2_mod by (apply nth_default_preserves_properties; auto; omega) - | |- _ => reflexivity - end. - specialize (H0 i). - symmetry. - rewrite <- (Z.mod_pow2_bits_high (nth_default 0 us i) (nth_default 0 lw i) n); - [ rewrite Z.mod_small by omega; reflexivity | ]. - split; try omega. - apply nth_default_preserves_properties; auto; omega. - Qed. - - Lemma pow2_mod_bounded_iff :forall lw us, (forall w, In w lw -> 0 <= w) -> (bounded lw us <-> - (forall i, Z.pow2_mod (nth_default 0 us i) (nth_default 0 lw i) = nth_default 0 us i)). - Proof using Type. - clear. - split; intros; auto using pow2_mod_bounded. - cbv [bounded]; intros. - assert (0 <= nth_default 0 lw i) by (apply nth_default_preserves_properties; auto; omega). - split. - + specialize (H0 i). - rewrite Z.pow2_mod_spec in H0 by assumption. - apply Z.mod_small_iff in H0; [ | apply Z.pow_nonzero; (assumption || omega)]. - destruct H0; try omega. - pose proof (Z.pow_nonneg 2 (nth_default 0 lw i)). - specialize_by omega; omega. - + apply Z.testbit_false_bound; auto. - intros. - rewrite <-H0. - rewrite Z.testbit_pow2_mod by assumption. - break_if; reflexivity || omega. - Qed. - - Lemma bounded_nil_iff : forall us, bounded nil us <-> (forall u, In u us -> u = 0). - Proof using Type. - clear. - split; cbv [bounded]; intros. - + edestruct (In_nth_error_value us u); try assumption. - specialize (H x). - replace u with (nth_default 0 us x) by (auto using nth_error_value_eq_nth_default). - rewrite nth_default_nil, Z.pow_0_r in H. - omega. - + rewrite nth_default_nil, Z.pow_0_r. - apply nth_default_preserves_properties; try omega. - intros. - apply H in H0. - omega. - Qed. - - Lemma bounded_iff : forall lw us, bounded lw us <-> forall i, 0 <= nth_default 0 us i < 2 ^ nth_default 0 lw i. - Proof using Type. - clear. - cbv [bounded]; intros. - reflexivity. - Qed. - - Lemma digit_select : forall us i, bounded limb_widths us -> - nth_default 0 us i = Z.pow2_mod (BaseSystem.decode base us >> sum_firstn limb_widths i) (nth_default 0 limb_widths i). - Proof using Type*. - intro; revert limb_widths limb_widths_nonneg; induction us; intros. - + rewrite nth_default_nil, decode_nil, Z.shiftr_0_l, Z.pow2_mod_spec, Z.mod_0_l by - (try (apply Z.pow_nonzero; try omega); apply nth_default_preserves_properties; auto; omega). - reflexivity. - + destruct i. - - rewrite nth_default_cons, sum_firstn_0, Z.shiftr_0_r. - destruct limb_widths as [|w lw]. - * cbv [base_from_limb_widths]. - rewrite <-pow2_mod_bounded with (lw := nil); rewrite bounded_nil_iff in *; auto using in_cons; - try solve [intros; exfalso; eauto using in_nil]. - rewrite !nth_default_nil, decode_base_nil; auto. - cbv. auto using in_eq. - * rewrite nth_default_cons, base_from_limb_widths_cons, peel_decode. - fold (BaseSystem.mul_each (two_p w)). - rewrite <-mul_each_base, mul_each_rep. - rewrite two_p_correct, (Z.mul_comm (2 ^ w)). - rewrite <-Z.shiftl_mul_pow2 by auto using in_eq. - rewrite bounded_iff in *. - specialize (H 0%nat); rewrite !nth_default_cons in H. - rewrite <-Z.lor_shiftl by (auto using in_eq; omega). - apply Z.bits_inj'; intros. - rewrite Z.testbit_pow2_mod by auto using in_eq. - break_if. { - autorewrite with Ztestbit; break_match; - try rewrite Z.testbit_neg_r with (n := n - w) by omega; - autorewrite with bool_congr; - f_equal; ring. - } { - replace a with (a mod 2 ^ w) by (auto using Z.mod_small). - apply Z.mod_pow2_bits_high. split; auto using in_eq; omega. - } - - rewrite nth_default_cons_S. - destruct limb_widths as [|w lw]. - * cbv [base_from_limb_widths]. - rewrite <-pow2_mod_bounded with (lw := nil); rewrite bounded_nil_iff in *; auto using in_cons. - rewrite sum_firstn_nil, !nth_default_nil, decode_base_nil, Z.shiftr_0_r. - apply nth_default_preserves_properties; intros; auto using in_cons. - f_equal; auto using in_cons. - * rewrite sum_firstn_succ_cons, nth_default_cons_S, base_from_limb_widths_cons, peel_decode. - fold (BaseSystem.mul_each (two_p w)). - rewrite <-mul_each_base, mul_each_rep. - rewrite two_p_correct, (Z.mul_comm (2 ^ w)). - rewrite <-Z.shiftl_mul_pow2 by auto using in_eq. - rewrite bounded_iff in *. - rewrite Z.shiftr_add_shiftl_high by first - [ pose proof (sum_firstn_nonnegative i lw); split; auto using in_eq; specialize_by auto using in_cons; omega - | specialize (H 0%nat); rewrite !nth_default_cons in H; omega ]. - rewrite IHus with (limb_widths := lw) by - (auto using in_cons; rewrite ?bounded_iff; intro j; specialize (H (S j)); - rewrite !nth_default_cons_S in H; assumption). - repeat f_equal; try ring. - Qed. - - Lemma nth_default_limb_widths_nonneg : forall i, 0 <= nth_default 0 limb_widths i. - Proof using Type*. - intros; apply nth_default_preserves_properties; auto; omega. - Qed. Hint Resolve nth_default_limb_widths_nonneg. - - Lemma parity_decode : forall x, - (0 < nth_default 0 limb_widths 0) -> - length x = length limb_widths -> - Z.odd (BaseSystem.decode base x) = Z.odd (nth_default 0 x 0). - Proof using Type*. - intros. - destruct limb_widths, x; simpl in *; try discriminate; try reflexivity. - rewrite peel_decode, nth_default_cons. - fold (BaseSystem.mul_each (two_p z)). - rewrite <-mul_each_base, mul_each_rep. - rewrite Z.odd_add_mul_even; [ f_equal; ring | ]. - rewrite <-Z.even_spec, two_p_correct. - apply Z.even_pow. - rewrite @nth_default_cons in *; auto. - Qed. - - Lemma decode_firstn_pow2_mod : forall us i, - (i <= length us)%nat -> - length us = length limb_widths -> - bounded limb_widths us -> - BaseSystem.decode' base (firstn i us) = Z.pow2_mod (BaseSystem.decode' base us) (sum_firstn limb_widths i). - Proof using Type*. - intros; induction i; - repeat match goal with - | |- _ => rewrite sum_firstn_0, decode_nil, Z.pow2_mod_0_r; reflexivity - | |- _ => progress distr_length - | |- _ => progress autorewrite with simpl_firstn - | |- _ => rewrite firstn_succ with (d := 0) - | |- _ => rewrite set_higher - | |- _ => rewrite nth_default_base - | |- _ => rewrite IHi - | |- _ => rewrite <-Z.lor_shiftl by (rewrite ?Z.pow2_mod_spec; try apply Z.mod_pos_bound; zero_bounds) - | |- appcontext[min ?x ?y] => (rewrite Nat.min_l by omega || rewrite Nat.min_r by omega) - | |- appcontext[2 ^ ?a * _] => rewrite (Z.mul_comm (2 ^ a)); rewrite <-Z.shiftl_mul_pow2 - | |- _ => solve [auto] - | |- _ => lia - end. - rewrite digit_select by assumption; apply Z.bits_inj'. - repeat match goal with - | |- _ => progress intros - | |- _ => progress autorewrite with Ztestbit - | |- _ => rewrite Z.testbit_pow2_mod by (omega || trivial) - | |- _ => break_if; try omega - | H : ?a < ?b |- appcontext[Z.testbit _ (?a - ?b)] => - rewrite (Z.testbit_neg_r _ (a-b)) by omega - | |- _ => reflexivity - | |- _ => solve [f_equal; ring] - | |- _ => rewrite sum_firstn_succ_default in *; - pose proof (nth_default_limb_widths_nonneg i); omega - end. - Qed. - - Lemma testbit_decode_firstn_high : forall us i n, - (i <= length us)%nat -> - length us = length limb_widths -> - bounded limb_widths us -> - sum_firstn limb_widths i <= n -> - Z.testbit (BaseSystem.decode base (firstn i us)) n = false. - Proof using Type*. - repeat match goal with - | |- _ => progress intros - | |- _ => progress autorewrite with Ztestbit - | |- _ => rewrite decode_firstn_pow2_mod - | |- _ => rewrite Z.testbit_pow2_mod - | |- _ => break_if - | |- _ => assumption - | |- _ => solve [auto] - | H : ?a <= ?b |- 0 <= ?b => assert (0 <= a) by (omega || auto); omega - end. - Qed. - - Lemma testbit_decode_high : forall us n, - length us = length limb_widths -> - bounded limb_widths us -> - sum_firstn limb_widths (length us) <= n -> - Z.testbit (BaseSystem.decode base us) n = false. - Proof using Type*. - intros. - erewrite <-(firstn_all _ us) by reflexivity. - auto using testbit_decode_firstn_high. - Qed. - - (** TODO: Figure out how to automate and clean up this proof *) - Lemma decode_nonneg : forall us, - length us = length limb_widths -> - bounded limb_widths us -> - 0 <= BaseSystem.decode base us. - Proof using Type*. - intros. - unfold bounded, BaseSystem.decode, BaseSystem.decode' in *; simpl in *. - pose 0 as zero. - assert (0 <= zero) by reflexivity. - replace base with (map (Z.mul (two_p zero)) base) - by (etransitivity; [ | apply map_id ]; apply map_ext; auto with zarith). - clearbody zero. - revert dependent zero. - generalize dependent limb_widths. - induction us as [|u us IHus]; intros [|w limb_widths'] ?? Hbounded ??; simpl in *; - try (reflexivity || congruence). - pose proof (Hbounded 0%nat) as Hbounded0. - pose proof (fun n => Hbounded (S n)) as HboundedS. - unfold nth_default, nth_error in Hbounded0. - unfold nth_default in HboundedS. - rewrite map_map. - unfold BaseSystem.accumulate at 1; simpl. - assert (0 < two_p zero) by (rewrite two_p_equiv; auto with zarith). - replace (map (fun x => two_p zero * (two_p w * x)) (base_from_limb_widths limb_widths')) with (map (Z.mul (two_p (zero + w))) (base_from_limb_widths limb_widths')) - by (apply map_ext; rewrite two_p_is_exp by auto with zarith omega; auto with zarith). - change 0 with (0 + 0) at 1. - apply Z.add_le_mono; simpl in *; auto with zarith. - Qed. - - Lemma decode_upper_bound : forall us, - length us = length limb_widths -> - bounded limb_widths us -> - 0 <= BaseSystem.decode base us < upper_bound limb_widths. - Proof using Type*. - cbv [upper_bound]; intros. - split. - { apply decode_nonneg; auto. } - { apply Z.testbit_false_bound; auto; intros. - rewrite testbit_decode_high; auto; - replace (length us) with (length limb_widths); try omega. } - Qed. - - Lemma decode_firstn_succ : forall us i, - (S i <= length us)%nat -> - bounded limb_widths us -> - length us = length limb_widths -> - BaseSystem.decode base (firstn (S i) us) = - Z.lor (BaseSystem.decode base (firstn i us)) (nth_default 0 us i << sum_firstn limb_widths i). - Proof using Type*. - repeat match goal with - | |- _ => progress intros - | |- _ => progress autorewrite with Ztestbit - | |- _ => progress change BaseSystem.decode with BaseSystem.decode' - | |- _ => rewrite sum_firstn_succ_default in * - | |- _ => apply Z.bits_inj' - | |- _ => break_if - | |- appcontext [Z.testbit _ (?a - sum_firstn ?l ?i)] => - destruct (Z_le_dec (sum_firstn l i) a); - [ rewrite (testbit_decode_firstn_high _ i a) - | rewrite (Z.testbit_neg_r _ (a - sum_firstn l i))] - | |- appcontext [Z.testbit (BaseSystem.decode' _ (firstn ?i _)) _] => - rewrite (decode_firstn_pow2_mod _ i) - | |- _ => rewrite digit_select by auto - | |- _ => rewrite Z.testbit_pow2_mod - | |- _ => assumption - | |- _ => reflexivity - | |- _ => omega - | |- _ => f_equal; ring - | |- _ => solve [auto] - | |- _ => solve [zero_bounds] - | H : appcontext [nth_default 0 limb_widths ?i] |- _ => - pose proof (nth_default_limb_widths_nonneg i); omega - | |- appcontext [nth_default 0 limb_widths ?i] => - pose proof (nth_default_limb_widths_nonneg i); omega - end. - Qed. - - Lemma testbit_decode_digit_select : forall us n i, - bounded limb_widths us -> - sum_firstn limb_widths i <= n < sum_firstn limb_widths (S i) -> - Z.testbit (BaseSystem.decode base us) n = Z.testbit (nth_default 0 us i) (n - sum_firstn limb_widths i). - Proof using Type*. - repeat match goal with - | |- _ => progress intros - | |- _ => erewrite digit_select by eauto - | |- _ => progress rewrite sum_firstn_succ_default in * - | |- _ => progress autorewrite with Ztestbit - | |- _ => break_if - | |- _ => omega - | |- _ => solve [f_equal;ring] - end. - Qed. - - Lemma testbit_bounded_high : forall i n us, bounded limb_widths us -> - nth_default 0 limb_widths i <= n -> - Z.testbit (nth_default 0 us i) n = false. - Proof using Type*. - repeat match goal with - | |- _ => progress intros - | |- _ => break_if - | |- _ => omega - | |- _ => reflexivity - | |- _ => assumption - | |- _ => apply nth_default_limb_widths_nonneg; auto - | H : nth_default 0 limb_widths ?i <= ?n |- 0 <= ?n => etransitivity; [ | eapply H] - | |- _ => erewrite <-pow2_mod_bounded by eauto; rewrite Z.testbit_pow2_mod - end. - Qed. - - Lemma decode_shift_app : forall us0 us1, (length (us0 ++ us1) <= length limb_widths)%nat -> - BaseSystem.decode base (us0 ++ us1) = (BaseSystem.decode (base_from_limb_widths (firstn (length us0) limb_widths)) us0) + ((BaseSystem.decode (base_from_limb_widths (skipn (length us0) limb_widths)) us1) << sum_firstn limb_widths (length us0)). - Proof using Type*. - unfold BaseSystem.decode; intros us0 us1 ?. - assert (0 <= sum_firstn limb_widths (length us0)) by auto using sum_firstn_nonnegative. - rewrite decode'_splice; autorewrite with push_firstn. - apply Z.add_cancel_l. - autorewrite with pull_base_from_limb_widths Zshift_to_pow zsimplify. - rewrite decode'_map_mul, two_p_correct; nia. - Qed. - - Lemma decode_shift : forall us u0, (length (u0 :: us) <= length limb_widths)%nat -> - BaseSystem.decode base (u0 :: us) = u0 + ((BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us) << (nth_default 0 limb_widths 0)). - Proof using Type*. - intros; etransitivity; [ apply (decode_shift_app (u0::nil)); assumption | ]. - transitivity (u0 * 1 + 0 + ((BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us) << (nth_default 0 limb_widths 0 + 0))); [ | autorewrite with zsimplify; reflexivity ]. - destruct limb_widths; distr_length; reflexivity. - Qed. - - Lemma upper_bound_nil : upper_bound nil = 1. - Proof using Type. reflexivity. Qed. - - Lemma upper_bound_cons x xs : 0 <= x -> 0 <= sum_firstn xs (length xs) -> upper_bound (x::xs) = 2^x * upper_bound xs. - Proof using Type. - intros Hx Hxs. - unfold upper_bound; simpl. - autorewrite with simpl_sum_firstn pull_Zpow. - reflexivity. - Qed. - - Lemma upper_bound_app xs ys : 0 <= sum_firstn xs (length xs) -> 0 <= sum_firstn ys (length ys) -> upper_bound (xs ++ ys) = upper_bound xs * upper_bound ys. - Proof using Type. - intros Hxs Hys. - unfold upper_bound; simpl. - autorewrite with distr_length simpl_sum_firstn pull_Zpow. - reflexivity. - Qed. - - Lemma bounded_nil_r : forall l, (forall x, In x l -> 0 <= x) -> bounded l nil. - Proof using Type. - cbv [bounded]; intros. - rewrite nth_default_nil. - apply nth_default_preserves_properties; intros; split; zero_bounds. - Qed. - - Section make_base_vector. - Local Notation k := (sum_firstn limb_widths (length limb_widths)). - Context (limb_widths_match_modulus : forall i j, - (i < length base)%nat -> - (j < length base)%nat -> - (i + j >= length base)%nat -> - let w_sum := sum_firstn limb_widths in - k + w_sum (i + j - length base)%nat <= w_sum i + w_sum j) - (limb_widths_good : forall i j, (i + j < length limb_widths)%nat -> - sum_firstn limb_widths (i + j) <= - sum_firstn limb_widths i + sum_firstn limb_widths j). - - Lemma base_matches_modulus: forall i j, - (i < length base)%nat -> - (j < length base)%nat -> - (i+j >= length base)%nat-> - let b := nth_default 0 base in - let r := (b i * b j) / (2^k * b (i+j-length base)%nat) in - b i * b j = r * (2^k * b (i+j-length base)%nat). - Proof using limb_widths_match_modulus limb_widths_nonneg. - intros. - rewrite (Z.mul_comm r). - subst r. - rewrite base_from_limb_widths_length in *; - assert (i + j - length limb_widths < length limb_widths)%nat by omega. - rewrite Z.mul_div_eq by (apply Z.gt_lt_iff; subst b; rewrite ?nth_default_base; zero_bounds; - assumption). - rewrite (Zminus_0_l_reverse (b i * b j)) at 1. - f_equal. - subst b. - repeat rewrite nth_default_base by auto. - do 2 rewrite <- Z.pow_add_r by auto using sum_firstn_limb_widths_nonneg. - symmetry. - apply Z.mod_same_pow. - split. - + apply Z.add_nonneg_nonneg; auto using sum_firstn_limb_widths_nonneg. - + auto using limb_widths_match_modulus. - Qed. - - Lemma base_good : forall i j : nat, - (i + j < length base)%nat -> - let b := nth_default 0 base in - let r := b i * b j / b (i + j)%nat in - b i * b j = r * b (i + j)%nat. - Proof using limb_widths_good limb_widths_nonneg. - intros; subst b r. - clear limb_widths_match_modulus. - rewrite base_from_limb_widths_length in *. - repeat rewrite nth_default_base by omega. - rewrite (Z.mul_comm _ (2 ^ (sum_firstn limb_widths (i+j)))). - rewrite Z.mul_div_eq by (apply Z.gt_lt_iff; zero_bounds; - auto using sum_firstn_limb_widths_nonneg). - rewrite <- Z.pow_add_r by auto using sum_firstn_limb_widths_nonneg. - rewrite Z.mod_same_pow; try ring. - split; [ auto using sum_firstn_limb_widths_nonneg | ]. - apply limb_widths_good. - assumption. - Qed. - End make_base_vector. -End Pow2BaseProofs. -Hint Rewrite base_from_limb_widths_cons base_from_limb_widths_nil : push_base_from_limb_widths. -Hint Rewrite <- base_from_limb_widths_cons : pull_base_from_limb_widths. - -Hint Rewrite <- @firstn_base_from_limb_widths : push_base_from_limb_widths. -Hint Rewrite <- @firstn_base_from_limb_widths : pull_firstn. -Hint Rewrite @firstn_base_from_limb_widths : pull_base_from_limb_widths. -Hint Rewrite @firstn_base_from_limb_widths : push_firstn. -Hint Rewrite <- @skipn_base_from_limb_widths : push_base_from_limb_widths. -Hint Rewrite <- @skipn_base_from_limb_widths : pull_skipn. -Hint Rewrite @skipn_base_from_limb_widths : pull_base_from_limb_widths. -Hint Rewrite @skipn_base_from_limb_widths : push_skipn. - -Hint Rewrite @base_from_limb_widths_length : distr_length. -Hint Rewrite @upper_bound_nil @upper_bound_cons @upper_bound_app using solve [ eauto with znonzero ] : push_upper_bound. -Hint Rewrite <- @upper_bound_cons @upper_bound_app using solve [ eauto with znonzero ] : pull_upper_bound. - -Section BitwiseDecodeEncode. - Context {limb_widths} (limb_widths_nonnil : limb_widths <> nil) - (limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w) - (limb_widths_good : forall i j, (i + j < length limb_widths)%nat -> - sum_firstn limb_widths (i + j) <= - sum_firstn limb_widths i + sum_firstn limb_widths j). - Local Hint Resolve limb_widths_nonneg. - Local Hint Resolve nth_default_limb_widths_nonneg. - Local Hint Resolve sum_firstn_limb_widths_nonneg. - Local Notation "w[ i ]" := (nth_default 0 limb_widths i). - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation upper_bound := (upper_bound limb_widths). - - Lemma encode'_spec : forall x i, (i <= length limb_widths)%nat -> - encode' limb_widths x i = BaseSystem.encode' base x upper_bound i. - Proof using limb_widths_nonneg. - induction i; intros. - + rewrite encode'_zero. reflexivity. - + rewrite encode'_succ, <-IHi by omega. - simpl; do 2 f_equal. - rewrite Z.land_ones, Z.shiftr_div_pow2 by auto. - match goal with H : (S _ <= length limb_widths)%nat |- _ => - apply le_lt_or_eq in H; destruct H end. - - repeat f_equal; rewrite nth_default_base by (omega || auto); reflexivity. - - repeat f_equal; try solve [rewrite nth_default_base by (omega || auto); reflexivity]. - rewrite nth_default_out_of_bounds by (distr_length; omega). - unfold Pow2Base.upper_bound. - congruence. - Qed. - - Lemma length_encode' : forall lw z i, length (encode' lw z i) = i. - Proof using Type. - induction i; intros; simpl encode'; distr_length. - Qed. - Hint Rewrite length_encode' : distr_length. - - Lemma bounded_encode' : forall z i, (0 <= z) -> - bounded (firstn i limb_widths) (encode' limb_widths z i). - Proof using limb_widths_nonneg. - intros; induction i; simpl encode'; - repeat match goal with - | |- _ => progress intros - | |- _ => progress autorewrite with push_nth_default in * - | |- _ => progress autorewrite with Ztestbit - | |- _ => progress rewrite ?firstn_O, ?Nat.sub_diag in * - | |- _ => rewrite Z.testbit_pow2_mod by auto - | |- _ => rewrite Z.ones_spec by zero_bounds - | |- _ => rewrite sum_firstn_succ_default - | |- _ => rewrite nth_default_out_of_bounds by distr_length - | |- _ => break_if; distr_length - | |- _ => apply bounded_nil_r - | |- appcontext[nth_default _ (_ :: nil) ?i] => case_eq i; intros; autorewrite with push_nth_default - | |- Z.pow2_mod (?a >> ?b) _ = (?a >> ?b) => apply Z.bits_inj' - | IH : forall i, _ = nth_default 0 (encode' _ _ _) i - |- appcontext[nth_default 0 limb_widths ?i] => specialize (IH i) - | H : In _ (firstn _ _) |- _ => apply In_firstn in H - | H1 : ~ (?a < ?b)%nat, H2 : (?a < S ?b)%nat |- _ => - progress replace a with b in * by omega - | H : bounded _ _ |- bounded _ _ => - apply pow2_mod_bounded_iff; rewrite pow2_mod_bounded_iff in H - | |- _ => solve [auto] - | |- _ => contradiction - | |- _ => reflexivity - end. - Qed. - - Lemma bounded_encodeZ : forall z, (0 <= z) -> - bounded limb_widths (encodeZ limb_widths z). - Proof using limb_widths_nonneg. - cbv [encodeZ]; intros. - pose proof (bounded_encode' z (length limb_widths)) as Hencode'. - rewrite firstn_all in Hencode'; auto. - Qed. - - Lemma base_upper_bound_compatible : @base_max_succ_divide base upper_bound. - Proof using limb_widths_nonneg. - unfold base_max_succ_divide; intros i lt_Si_length. - rewrite base_from_limb_widths_length in lt_Si_length. - rewrite Nat.lt_eq_cases in lt_Si_length; destruct lt_Si_length; - rewrite !nth_default_base by (omega || auto). - + erewrite sum_firstn_succ by (eapply nth_error_Some_nth_default with (x := 0); omega). - rewrite Z.pow_add_r; eauto. - apply Z.divide_factor_r. - + rewrite nth_default_out_of_bounds by (distr_length; omega). - unfold Pow2Base.upper_bound. - replace (length limb_widths) with (S (pred (length limb_widths))) by omega. - replace i with (pred (length limb_widths)) by omega. - erewrite sum_firstn_succ by (eapply nth_error_Some_nth_default with (x := 0); omega). - rewrite Z.pow_add_r; eauto. - apply Z.divide_factor_r. - Qed. - Hint Resolve base_upper_bound_compatible. - - Lemma encodeZ_spec : forall x, - BaseSystem.decode base (encodeZ limb_widths x) = x mod upper_bound. - Proof. - intros. - assert (length base = length limb_widths) by distr_length. - unfold encodeZ; rewrite encode'_spec by omega. - erewrite BaseSystemProofs.encode'_spec; unfold Pow2Base.upper_bound; - zero_bounds; intros; eauto using base_positive, b0_1. { - rewrite nth_default_out_of_bounds by omega. - reflexivity. - } { - econstructor; try apply base_good; - eauto using base_positive, b0_1. - } - Qed. - - Lemma encodeZ_length : forall x, length (encodeZ limb_widths x) = length limb_widths. - Proof using limb_widths_nonneg. - cbv [encodeZ]; intros. - rewrite encode'_spec by omega. - apply encode'_length. - Qed. - - Definition decode_bitwise'_invariant us i acc := - forall n, 0 <= n -> Z.testbit acc n = Z.testbit (BaseSystem.decode base us) (n + sum_firstn limb_widths i). - - Lemma decode_bitwise'_invariant_step : forall us, - length us = length limb_widths -> - bounded limb_widths us -> - forall i acc, decode_bitwise'_invariant us (S i) acc -> - decode_bitwise'_invariant us i (Z.lor (nth_default 0 us i) (acc << nth_default 0 limb_widths i)). - Proof using limb_widths_nonneg. - repeat match goal with - | |- _ => progress cbv [decode_bitwise'_invariant]; intros - | |- _ => erewrite testbit_bounded_high by (omega || eauto) - | |- _ => progress autorewrite with Ztestbit - | |- _ => progress rewrite sum_firstn_succ_default - | |- appcontext[Z.testbit _ ?n] => rewrite (Z.testbit_neg_r _ n) by omega - | H : forall n, 0 <= n -> Z.testbit _ n = _ |- _ => rewrite H by omega - | |- _ => solve [f_equal; ring] - | |- appcontext[Z.testbit _ (?x + sum_firstn limb_widths ?i)] => - erewrite testbit_decode_digit_select with (i0 := i) by - (eauto; rewrite sum_firstn_succ_default; omega) - | |- appcontext[Z.testbit _ (?a - ?b)] => destruct (Z_lt_dec a b) - | _ => progress break_if - end. - Qed. - - Lemma decode_bitwise'_invariant_holds : forall i us acc, - length us = length limb_widths -> - bounded limb_widths us -> - decode_bitwise'_invariant us i acc -> - decode_bitwise'_invariant us 0 (decode_bitwise' limb_widths us i acc). - Proof using limb_widths_nonneg. - repeat match goal with - | |- _ => progress intros - | |- _ => solve [auto using decode_bitwise'_invariant_step] - | |- appcontext[decode_bitwise' ?a ?b ?c ?d] => - functional induction (decode_bitwise' a b c d) - end. - Qed. - - Lemma decode_bitwise_spec : forall us, bounded limb_widths us -> - length us = length limb_widths -> - decode_bitwise limb_widths us = BaseSystem.decode base us. - Proof using limb_widths_nonneg. - repeat match goal with - | |- _ => progress cbv [decode_bitwise decode_bitwise'_invariant] in * - | |- _ => progress intros - | |- _ => rewrite sum_firstn_0 - | |- _ => erewrite testbit_decode_high by (assumption || omega) - | H0 : ?P ?x , H1 : ?P ?x -> _ |- _ => specialize (H1 H0) - | H : _ -> forall n, 0 <= n -> Z.testbit _ n = _ |- _ => rewrite H - | |- decode_bitwise' ?a ?b ?c ?d = _ => - let H := fresh "H" in - pose proof (decode_bitwise'_invariant_holds c b d) as H; - apply Z.bits_inj' - | |- _ => apply Z.testbit_0_l - | |- _ => assumption - | |- _ => solve [f_equal; ring] - end. - Qed. - -End BitwiseDecodeEncode. - -Section UniformBase. - Context {width : Z} (limb_width_nonneg : 0 <= width). - Context (limb_widths : list Z) - (limb_widths_uniform : forall w, In w limb_widths -> w = width). - Local Notation base := (base_from_limb_widths limb_widths). - - Lemma bounded_uniform : forall us, (length us <= length limb_widths)%nat -> - (bounded limb_widths us <-> (forall u, In u us -> 0 <= u < 2 ^ width)). - Proof using Type*. - cbv [bounded]; split; intro A; intros. - + let G := fresh "G" in - match goal with H : In _ us |- _ => - eapply In_nth in H; destruct H as [? G]; destruct G as [? G]; - rewrite <-nth_default_eq in G; rewrite <-G end. - specialize (A x). - split; try eapply A. - eapply Z.lt_le_trans; try apply A. - apply nth_default_preserves_properties; [ | apply Z.pow_le_mono_r; omega ] . - intros; apply Z.eq_le_incl. - f_equal; auto. - + apply nth_default_preserves_properties_length_dep; - try solve [apply nth_default_preserves_properties; split; zero_bounds; rewrite limb_widths_uniform; auto || omega]. - intros; apply nth_default_preserves_properties_length_dep; try solve [intros; omega]. - let x := fresh "x" in intro x; intros; - replace x with width; try symmetry; auto. - Qed. - - Lemma uniform_limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w. - Proof using Type*. - intros. - replace w with width by (symmetry; auto). - assumption. - Qed. - - Lemma nth_default_uniform_base_full : forall i, - nth_default 0 limb_widths i = if lt_dec i (length limb_widths) - then width else 0. - Admitted. - - Lemma nth_default_uniform_base : forall i, (i < length limb_widths)%nat -> - nth_default 0 limb_widths i = width. - Proof using Type*. - intros; rewrite nth_default_uniform_base_full. - edestruct lt_dec; omega. - Qed. - - Lemma sum_firstn_uniform_base : forall i, (i <= length limb_widths)%nat -> - sum_firstn limb_widths i = Z.of_nat i * width. - Proof using limb_widths_uniform. - clear limb_width_nonneg. (* clear this before induction so we don't depend on this *) - induction limb_widths as [|x xs IHxs]; (intros [|i] ?); - simpl @length in *; - autorewrite with simpl_sum_firstn push_Zof_nat zsimplify; - try reflexivity; - try omega. - assert (x = width) by auto with datatypes; subst. - rewrite IHxs by auto with datatypes omega; omega. - Qed. - - Lemma sum_firstn_uniform_base_strong : forall i, (length limb_widths <= i)%nat -> - sum_firstn limb_widths i = Z.of_nat (length limb_widths) * width. - Proof using limb_widths_uniform. - intros; rewrite sum_firstn_all, sum_firstn_uniform_base by omega; reflexivity. - Qed. - - Lemma upper_bound_uniform : upper_bound limb_widths = 2^(Z.of_nat (length limb_widths) * width). - Proof using limb_widths_uniform. - unfold upper_bound; rewrite sum_firstn_uniform_base_strong by omega; reflexivity. - Qed. - - (* TODO : move *) - Lemma decode_truncate_base : forall us bs, BaseSystem.decode bs us = BaseSystem.decode (firstn (length us) bs) us. - Proof using Type. - clear. - induction us; intros. - + rewrite !decode_nil; reflexivity. - + distr_length. - destruct bs. - - rewrite firstn_nil, !decode_base_nil; reflexivity. - - rewrite firstn_cons, !peel_decode. - f_equal. - apply IHus. - Qed. - - (* TODO : move *) - Lemma tl_repeat : forall {A} xs n (x : A), (forall y, In y xs -> y = x) -> - (n < length xs)%nat -> - firstn n xs = firstn n (tl xs). - Proof using Type. - intros. - erewrite (repeat_spec_eq xs) by first [ eassumption | reflexivity ]. - rewrite ListUtil.tl_repeat. - autorewrite with push_firstn. - apply f_equal; omega *. - Qed. - - Lemma decode_tl_base : forall us, (length us < length limb_widths)%nat -> - BaseSystem.decode base us = BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us. - Proof using limb_widths_uniform. - intros. - match goal with |- BaseSystem.decode ?b1 _ = BaseSystem.decode ?b2 _ => - rewrite (decode_truncate_base _ b1), (decode_truncate_base _ b2) end. - rewrite !firstn_base_from_limb_widths. - do 2 f_equal. - eauto using tl_repeat. - Qed. - - Lemma decode_shift_uniform_tl : forall us u0, (length (u0 :: us) <= length limb_widths)%nat -> - BaseSystem.decode base (u0 :: us) = u0 + ((BaseSystem.decode (base_from_limb_widths (tl limb_widths)) us) << width). - Proof using Type*. - intros. - rewrite <- (nth_default_uniform_base 0) by distr_length. - rewrite decode_shift by auto using uniform_limb_widths_nonneg. - reflexivity. - Qed. - - Lemma decode_shift_uniform_app : forall us0 us1, (length (us0 ++ us1) <= length limb_widths)%nat -> - BaseSystem.decode base (us0 ++ us1) = (BaseSystem.decode (base_from_limb_widths (firstn (length us0) limb_widths)) us0) + ((BaseSystem.decode (base_from_limb_widths (skipn (length us0) limb_widths)) us1) << (Z.of_nat (length us0) * width)). - Proof using Type*. - intros. - rewrite <- sum_firstn_uniform_base by (distr_length; omega). - rewrite decode_shift_app by auto using uniform_limb_widths_nonneg. - reflexivity. - Qed. - - Lemma decode_shift_uniform : forall us u0, (length (u0 :: us) <= length limb_widths)%nat -> - BaseSystem.decode base (u0 :: us) = u0 + ((BaseSystem.decode base us) << width). - Proof using Type*. - intros. - rewrite decode_tl_base with (us := us) by distr_length. - apply decode_shift_uniform_tl; assumption. - Qed. - -End UniformBase. - -Hint Rewrite @upper_bound_uniform using solve [ auto with datatypes ] : push_upper_bound. - -Section SplitIndex. - (* This section defines [split_index], which for a list of bounded digits - splits a bit index in the decoded value into a digit index and a bit - index within the digit. Examples: - limb_widths [4;4] : split_index 6 = (1,2) - limb_widths [26,25,26] : split_index 30 = (1,4) - limb_widths [26,25,26] : split_index 51 = (2,0) - *) - Local Notation "u # i" := (nth_default 0 u i). - - Function split_index' i index lw := - match lw with - | nil => (index, i) - | w :: lw' => if Z_lt_dec i w then (index, i) - else split_index' (i - w) (S index) lw' - end. - - Lemma split_index'_ge_index : forall i index lw, (index <= fst (split_index' i index lw))%nat. - Proof. - intros; functional induction (split_index' i index lw); - repeat match goal with - | |- _ => omega - | |- _ => progress (simpl fst; simpl snd) - end. - Qed. - - Lemma split_index'_done_case : forall i index lw, 0 <= i -> - (forall x, In x lw -> 0 <= x) -> - if Z_lt_dec i (sum_firstn lw (length lw)) - then (fst (split_index' i index lw) - index < length lw)%nat - else (fst (split_index' i index lw) - index = length lw)%nat. - Proof. - intros; functional induction (split_index' i index lw); - repeat match goal with - | |- _ => break_if - | |- _ => rewrite sum_firstn_nil in * - | |- _ => rewrite sum_firstn_succ_cons in * - | |- _ => progress distr_length - | |- _ => progress (simpl fst; simpl snd) - | H : appcontext [split_index' ?a ?b ?c] |- _ => - unique pose proof (split_index'_ge_index a b c) - | H : appcontext [sum_firstn ?l ?i] |- _ => - let H0 := fresh "H" in - assert (forall x, In x l -> 0 <= x) by auto using in_cons; - unique pose proof (sum_firstn_limb_widths_nonneg H0 i) - | |- _ => progress specialize_by assumption - | |- _ => progress specialize_by omega - | |- _ => omega - end. - Qed. - - Lemma snd_split_index'_nonneg : forall index lw i, (0 <= i) -> - (0 <= snd (split_index' i index lw)). - Proof. - intros; functional induction (split_index' i index lw); - repeat match goal with - | |- _ => omega - | H : ?P -> ?G |- ?G => apply H - | |- _ => progress (simpl fst; simpl snd) - end. - Qed. - - Lemma snd_split_index'_small : forall i index lw, 0 <= i < sum_firstn lw (length lw) -> - (snd (split_index' i index lw) < lw # (fst (split_index' i index lw) - index)). - Proof. - intros; functional induction (split_index' i index lw); - try match goal with |- appcontext [split_index' ?a ?b ?c] => - pose proof (split_index'_ge_index a b c) end; - repeat match goal with - | |- _ => progress autorewrite with push_nth_default distr_length in * - | |- _ => rewrite Nat.sub_diag - | |- _ => rewrite sum_firstn_nil in * - | |- _ => rewrite sum_firstn_succ_cons in * - | |- _ => progress (simpl fst; simpl snd) - | H : _ -> ?x < _ |- ?x < _ => eapply Z.lt_le_trans; [ apply H; omega | ] - | |- ?xs # (?a - S ?b) <= (_ :: ?xs) # (?a - ?b) => - replace (a - b)%nat with (S (a - S b))%nat - | |- _ => omega - end. - Qed. - - Lemma split_index'_correct : forall i index lw, - sum_firstn lw (fst (split_index' i index lw) - index) + (snd (split_index' i index lw)) = i. - Proof. - intros; functional induction (split_index' i index lw); - repeat match goal with - | |- _ => omega - | |- _ => rewrite Nat.sub_diag - | |- _ => progress rewrite ?sum_firstn_nil, ?sum_firstn_0, ?sum_firstn_succ_cons - | |- _ => progress (simpl fst; simpl snd) - | |- appcontext[(fst (split_index' ?i (S ?idx) ?lw) - ?idx)%nat] => - pose proof (split_index'_ge_index i (S idx) lw); - replace (fst (split_index' i (S idx) lw) - idx)%nat with - (S (fst (split_index' i (S idx) lw) - S idx))%nat - end. - Qed. - - Context limb_widths - (limb_widths_pos : forall w, In w limb_widths -> 0 <= w). - Local Hint Resolve limb_widths_pos. - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation bitsIn lw := (sum_firstn lw (length lw)). - - Definition split_index i := split_index' i 0 limb_widths. - Definition digit_index i := fst (split_index i). - Definition bit_index i := snd (split_index i). - - Lemma testbit_decode : forall us n, - 0 <= n < bitsIn limb_widths -> - length us = length limb_widths -> - bounded limb_widths us -> - Z.testbit (BaseSystem.decode base us) n = Z.testbit (us # digit_index n) (bit_index n). - Proof using Type*. - cbv [digit_index bit_index split_index]; intros. - pose proof (split_index'_correct n 0 limb_widths). - pose proof (snd_split_index'_nonneg 0 limb_widths n). - specialize_by assumption. - repeat match goal with - | |- _ => progress autorewrite with Ztestbit natsimplify in * - | |- _ => erewrite digit_select by eauto - | |- _ => break_if - | |- _ => rewrite Z.testbit_pow2_mod by auto using nth_default_limb_widths_nonneg - | |- _ => omega - | |- _ => f_equal; omega - end. - destruct (Z_lt_dec n (bitsIn limb_widths)). { - pose proof (snd_split_index'_small n 0 limb_widths). - specialize_by omega. - rewrite Nat.sub_0_r in *. - omega. - } { - apply testbit_decode_high; auto. - replace (length us) with (length limb_widths) in *. - omega. - } - Qed. - - Lemma testbit_decode_full : forall us n, - length us = length limb_widths -> - bounded limb_widths us -> - Z.testbit (BaseSystem.decode base us) n = - if Z_le_dec 0 n - then (if Z_lt_dec n (bitsIn limb_widths) - then Z.testbit (us # digit_index n) (bit_index n) - else false) - else false. - Proof using Type*. - repeat match goal with - | |- _ => progress intros - | |- _ => break_if - | |- _ => apply Z.testbit_neg_r; lia - | |- _ => apply testbit_decode_high; auto; - try match goal with H : length _ = length limb_widths |- _ => rewrite H end; lia - | |- _ => auto using testbit_decode - end. - Qed. - - Lemma bit_index_nonneg : forall i, 0 <= i -> 0 <= bit_index i. - Proof using Type. - apply snd_split_index'_nonneg. - Qed. - - Lemma digit_index_lt_length : forall i, 0 <= i < bitsIn limb_widths -> - (digit_index i < length limb_widths)%nat. - Proof using Type*. - cbv [bit_index digit_index split_index]; intros. - pose proof (split_index'_done_case i 0 limb_widths). - specialize_by lia. specialize_by eauto. - break_if; lia. - Qed. - - Lemma bit_index_not_done : forall i, 0 <= i < bitsIn limb_widths -> - (bit_index i < limb_widths # digit_index i). - Proof using Type. - - cbv [bit_index digit_index split_index]; intros. - eapply Z.lt_le_trans; try apply (snd_split_index'_small i 0 limb_widths); try assumption. - rewrite Nat.sub_0_r; lia. - Qed. - - Lemma split_index_eqn : forall i, 0 <= i < bitsIn limb_widths -> - sum_firstn limb_widths (digit_index i) + bit_index i = i. - Proof using Type. - cbv [bit_index digit_index split_index]; intros. - etransitivity;[ | apply (split_index'_correct i 0 limb_widths) ]. - repeat f_equal; omega. - Qed. - - Lemma rem_bits_in_digit_pos : forall i, 0 <= i < bitsIn limb_widths -> - 0 < (limb_widths # digit_index i) - bit_index i. - Proof using Type. - repeat match goal with - | |- _ => progress intros - | |- 0 < ?a - ?b => destruct (Z_lt_dec b a); [ lia | exfalso ] - | H : ~ (bit_index ?i < limb_widths # digit_index ?i) |- _ => - pose proof (bit_index_not_done i); specialize_by omega; omega - end. - Qed. - - - Lemma rem_bits_in_digit_le_rem_bits : forall i, 0 <= i < bitsIn limb_widths -> - i + ((limb_widths # digit_index i) - bit_index i) <= bitsIn limb_widths. - Proof using Type*. - intros. - rewrite <-(split_index_eqn i) at 1 by lia. - match goal with - | |- ?a + ?b + (?c - ?b) <= _ => replace (a + b + (c - b)) with (c + a) by ring - end. - rewrite <-sum_firstn_succ_default. - apply sum_firstn_prefix_le; auto. - pose proof (digit_index_lt_length i H); lia. - Qed. - - - Lemma same_digit : forall i j, 0 <= i <= j -> - j < bitsIn limb_widths -> - j < i + ((limb_widths # (digit_index i)) - bit_index i) -> - (digit_index i = digit_index j)%nat. - Proof using Type*. - intros. - pose proof (split_index_eqn i). - pose proof (split_index_eqn j). - specialize_by lia. - apply le_antisym. { - eapply sum_firstn_pos_lt_succ; eauto; try (apply digit_index_lt_length; auto; lia). - rewrite sum_firstn_succ_default. - eapply Z.le_lt_trans; [ | apply Z.add_lt_mono_r; apply bit_index_not_done; lia ]. - pose proof (bit_index_nonneg i). - specialize_by lia. - lia. - } { - eapply sum_firstn_pos_lt_succ; eauto; try (apply digit_index_lt_length; auto; lia). - rewrite <-H2 in H1 at 1. - match goal with - | H : _ < ?a + ?b + (?c - ?b) |- _ => replace (a + b + (c - b)) with (c + a) in H by ring; - rewrite <-sum_firstn_succ_default in H - end. - rewrite <-H3 in H1. - pose proof (bit_index_nonneg j). specialize_by lia. - lia. - } - Qed. - - Lemma same_digit_bit_index_sub : forall i j, 0 <= i <= j -> j < bitsIn limb_widths -> - digit_index i = digit_index j -> - bit_index j - bit_index i = j - i. - Proof using Type. - intros. - pose proof (split_index_eqn i). - pose proof (split_index_eqn j). - specialize_by lia. - rewrite H1 in *. - lia. - Qed. - -End SplitIndex. - -Section carrying_helper. - Context {limb_widths} (limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w). - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation log_cap i := (nth_default 0 limb_widths i). - - Lemma update_nth_sum : forall n f us, (n < length us \/ n >= length limb_widths)%nat -> - BaseSystem.decode base (update_nth n f us) = - (let v := nth_default 0 us n in f v - v) * nth_default 0 base n + BaseSystem.decode base us. - Proof using Type. - intros. - unfold BaseSystem.decode. - destruct H as [H|H]. - { nth_inbounds; auto. (* TODO(andreser): nth_inbounds should do this auto*) - erewrite nth_error_value_eq_nth_default by eassumption. - unfold splice_nth. - rewrite <- (firstn_skipn n us) at 3. - do 2 rewrite decode'_splice. - remember (length (firstn n us)) as n0. - ring_simplify. - remember (BaseSystem.decode' (firstn n0 base) (firstn n us)). - rewrite (skipn_nth_default n us 0) by omega. - erewrite (nth_error_value_eq_nth_default _ _ us) by eassumption. - rewrite firstn_length in Heqn0. - rewrite Min.min_l in Heqn0 by omega; subst n0. - destruct (le_lt_dec (length limb_widths) n). { - rewrite (@nth_default_out_of_bounds _ _ base) by (distr_length; auto). - rewrite skipn_all by (rewrite base_from_limb_widths_length; omega). - do 2 rewrite decode_base_nil. - ring_simplify; auto. - } { - rewrite (skipn_nth_default n base 0) by (distr_length; omega). - do 2 rewrite decode'_cons. - ring_simplify; ring. - } } - { rewrite (nth_default_out_of_bounds _ base) by (distr_length; omega); ring_simplify. - etransitivity; rewrite BaseSystem.decode'_truncate; [ reflexivity | ]. - apply f_equal. - autorewrite with push_firstn simpl_update_nth. - rewrite update_nth_out_of_bounds by (distr_length; omega * ). - reflexivity. } - Qed. - - Lemma unfold_add_to_nth n x - : forall xs, - add_to_nth n x xs - = match n with - | O => match xs with - | nil => nil - | x'::xs' => x + x'::xs' - end - | S n' => match xs with - | nil => nil - | x'::xs' => x'::add_to_nth n' x xs' - end - end. - Proof using Type. - induction n; destruct xs; reflexivity. - Qed. - - Lemma simpl_add_to_nth_0 x - : forall xs, - add_to_nth 0 x xs - = match xs with - | nil => nil - | x'::xs' => x + x'::xs' - end. - Proof using Type. intro; rewrite unfold_add_to_nth; reflexivity. Qed. - - Lemma simpl_add_to_nth_S x n - : forall xs, - add_to_nth (S n) x xs - = match xs with - | nil => nil - | x'::xs' => x'::add_to_nth n x xs' - end. - Proof using Type. intro; rewrite unfold_add_to_nth; reflexivity. Qed. - - Hint Rewrite @simpl_set_nth_S @simpl_set_nth_0 : simpl_add_to_nth. - - Lemma add_to_nth_cons : forall x u0 us, add_to_nth 0 x (u0 :: us) = x + u0 :: us. - Proof using Type. reflexivity. Qed. - - Hint Rewrite @add_to_nth_cons : simpl_add_to_nth. - - Lemma cons_add_to_nth : forall n f y us, - y :: add_to_nth n f us = add_to_nth (S n) f (y :: us). - Proof using Type. - induction n; boring. - Qed. - - Hint Rewrite <- @cons_add_to_nth : simpl_add_to_nth. - - Lemma add_to_nth_nil : forall n f, add_to_nth n f nil = nil. - Proof using Type. - induction n; boring. - Qed. - - Hint Rewrite @add_to_nth_nil : simpl_add_to_nth. - - Lemma add_to_nth_set_nth n x xs - : add_to_nth n x xs - = set_nth n (x + nth_default 0 xs n) xs. - Proof using Type. - revert xs; induction n; destruct xs; - autorewrite with simpl_set_nth simpl_add_to_nth; - try rewrite IHn; - reflexivity. - Qed. - Lemma add_to_nth_update_nth n x xs - : add_to_nth n x xs - = update_nth n (fun y => x + y) xs. - Proof using Type. - revert xs; induction n; destruct xs; - autorewrite with simpl_update_nth simpl_add_to_nth; - try rewrite IHn; - reflexivity. - Qed. - - Lemma length_add_to_nth i x xs : length (add_to_nth i x xs) = length xs. - Proof using Type. unfold add_to_nth; distr_length; reflexivity. Qed. - - Hint Rewrite @length_add_to_nth : distr_length. - - Lemma set_nth_sum : forall n x us, (n < length us \/ n >= length limb_widths)%nat -> - BaseSystem.decode base (set_nth n x us) = - (x - nth_default 0 us n) * nth_default 0 base n + BaseSystem.decode base us. - Proof using Type. intros; unfold set_nth; rewrite update_nth_sum by assumption; reflexivity. Qed. - - Lemma add_to_nth_sum : forall n x us, (n < length us \/ n >= length limb_widths)%nat -> - BaseSystem.decode base (add_to_nth n x us) = - x * nth_default 0 base n + BaseSystem.decode base us. - Proof using Type. intros; rewrite add_to_nth_set_nth, set_nth_sum; try ring_simplify; auto. Qed. - - Lemma add_to_nth_nth_default_full : forall n x l i d, - nth_default d (add_to_nth n x l) i = - if lt_dec i (length l) then - if (eq_nat_dec i n) then x + nth_default d l i - else nth_default d l i - else d. - Proof using Type. intros; rewrite add_to_nth_update_nth; apply update_nth_nth_default_full; assumption. Qed. - Hint Rewrite @add_to_nth_nth_default_full : push_nth_default. - - Lemma add_to_nth_nth_default : forall n x l i, (0 <= i < length l)%nat -> - nth_default 0 (add_to_nth n x l) i = - if (eq_nat_dec i n) then x + nth_default 0 l i else nth_default 0 l i. - Proof using Type. intros; rewrite add_to_nth_update_nth; apply update_nth_nth_default; assumption. Qed. - Hint Rewrite @add_to_nth_nth_default using omega : push_nth_default. - - Lemma log_cap_nonneg : forall i, 0 <= log_cap i. - Proof using Type*. - unfold nth_default; intros. - case_eq (nth_error limb_widths i); intros; try omega. - apply limb_widths_nonneg. - eapply nth_error_value_In; eauto. - Qed. Local Hint Resolve log_cap_nonneg. -End carrying_helper. - -Hint Rewrite @simpl_set_nth_S @simpl_set_nth_0 : simpl_add_to_nth. -Hint Rewrite @add_to_nth_cons : simpl_add_to_nth. -Hint Rewrite <- @cons_add_to_nth : simpl_add_to_nth. -Hint Rewrite @add_to_nth_nil : simpl_add_to_nth. -Hint Rewrite @length_add_to_nth : distr_length. -Hint Rewrite @add_to_nth_nth_default_full : push_nth_default. -Hint Rewrite @add_to_nth_nth_default using (omega || distr_length; omega) : push_nth_default. - -Section carrying. - Context {limb_widths} (limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w). - Local Notation base := (base_from_limb_widths limb_widths). - Local Notation log_cap i := (nth_default 0 limb_widths i). - Local Hint Resolve limb_widths_nonneg sum_firstn_limb_widths_nonneg. - - Lemma length_carry_gen : forall fc fi i us, length (carry_gen limb_widths fc fi i us) = length us. - Proof using Type. intros; unfold carry_gen, carry_single; distr_length; reflexivity. Qed. - - Hint Rewrite @length_carry_gen : distr_length. - - Lemma length_carry_simple : forall i us, length (carry_simple limb_widths i us) = length us. - Proof using Type. intros; unfold carry_simple; distr_length; reflexivity. Qed. - Hint Rewrite @length_carry_simple : distr_length. - - Lemma nth_default_base_succ : forall i, (S i < length limb_widths)%nat -> - nth_default 0 base (S i) = 2 ^ log_cap i * nth_default 0 base i. - Proof using Type*. - intros. - rewrite !nth_default_base, <- Z.pow_add_r by (omega || eauto using log_cap_nonneg). - autorewrite with simpl_sum_firstn; reflexivity. - Qed. - - Lemma carry_gen_decode_eq : forall fc fi i' us - (i := fi i') - (Si := fi (S i)), - (length us = length limb_widths) -> - BaseSystem.decode base (carry_gen limb_widths fc fi i' us) - = (fc (nth_default 0 us i / 2 ^ log_cap i) * - (if eq_nat_dec Si (S i) - then if lt_dec (S i) (length limb_widths) - then 2 ^ log_cap i * nth_default 0 base i - else 0 - else nth_default 0 base Si) - - 2 ^ log_cap i * (nth_default 0 us i / 2 ^ log_cap i) * nth_default 0 base i) - + BaseSystem.decode base us. - Proof using Type*. - intros fc fi i' us i Si H; intros. - destruct (eq_nat_dec 0 (length limb_widths)); - [ destruct limb_widths, us, i; simpl in *; try congruence; - break_match; - unfold carry_gen, carry_single, add_to_nth; - autorewrite with zsimplify simpl_nth_default simpl_set_nth simpl_update_nth distr_length; - reflexivity - | ]. - (*assert (0 <= i < length limb_widths)%nat by (subst i; auto with arith).*) - assert (0 <= log_cap i) by auto using log_cap_nonneg. - assert (2 ^ log_cap i <> 0) by (apply Z.pow_nonzero; lia). - unfold carry_gen, carry_single. - change (i' mod length limb_widths)%nat with i. - rewrite add_to_nth_sum by (rewrite length_set_nth; omega). - rewrite set_nth_sum by omega. - unfold Z.pow2_mod. - rewrite Z.land_ones by auto using log_cap_nonneg. - rewrite Z.shiftr_div_pow2 by auto using log_cap_nonneg. - change (fi i') with i. - subst Si. - repeat first [ ring - | match goal with H : _ = _ |- _ => rewrite !H in * end - | rewrite nth_default_base_succ by omega - | rewrite !(nth_default_out_of_bounds _ base) by (distr_length; omega) - | rewrite !(nth_default_out_of_bounds _ us) by omega - | rewrite Z.mod_eq by assumption - | progress distr_length - | progress autorewrite with natsimplify zsimplify in * - | progress break_match ]. - Qed. - - Lemma carry_simple_decode_eq : forall i us, - (length us = length limb_widths) -> - (i < (pred (length limb_widths)))%nat -> - BaseSystem.decode base (carry_simple limb_widths i us) = BaseSystem.decode base us. - Proof using Type*. - unfold carry_simple; intros; rewrite carry_gen_decode_eq by assumption. - autorewrite with natsimplify. - break_match; try lia; autorewrite with zsimplify; lia. - Qed. - - - Lemma length_carry_simple_sequence : forall is us, length (carry_simple_sequence limb_widths is us) = length us. - Proof using Type. - unfold carry_simple_sequence. - induction is; [ reflexivity | simpl; intros ]. - distr_length. - congruence. - Qed. - Hint Rewrite @length_carry_simple_sequence : distr_length. - - Lemma length_make_chain : forall i, length (make_chain i) = i. - Proof using Type. induction i; simpl; congruence. Qed. - Hint Rewrite @length_make_chain : distr_length. - - Lemma length_full_carry_chain : length (full_carry_chain limb_widths) = length limb_widths. - Proof using Type. unfold full_carry_chain; distr_length; reflexivity. Qed. - Hint Rewrite @length_full_carry_chain : distr_length. - - Lemma length_carry_simple_full us : length (carry_simple_full limb_widths us) = length us. - Proof using Type. unfold carry_simple_full; distr_length; reflexivity. Qed. - Hint Rewrite @length_carry_simple_full : distr_length. - - (* TODO : move? *) - Lemma make_chain_lt : forall x i : nat, In i (make_chain x) -> (i < x)%nat. - Proof using Type. - induction x; simpl; intuition auto with arith lia. - Qed. - - Lemma nth_default_carry_gen_full fc fi d i n us - : nth_default d (carry_gen limb_widths fc fi i us) n - = if lt_dec n (length us) - then (if eq_nat_dec n (fi i) - then Z.pow2_mod (nth_default 0 us n) (log_cap n) - else nth_default 0 us n) + - if eq_nat_dec n (fi (S (fi i))) - then fc (nth_default 0 us (fi i) >> log_cap (fi i)) - else 0 - else d. - Proof using Type. - unfold carry_gen, carry_single. - intros; autorewrite with push_nth_default natsimplify distr_length. - edestruct (lt_dec n (length us)) as [H|H]; [ | reflexivity ]. - rewrite !(@nth_default_in_bounds Z 0 d) by assumption. - repeat break_match; subst; try omega; try rewrite_hyp *; omega. - Qed. - - Hint Rewrite @nth_default_carry_gen_full : push_nth_default. - - Lemma nth_default_carry_simple_full : forall d i n us, - nth_default d (carry_simple limb_widths i us) n - = if lt_dec n (length us) - then if eq_nat_dec n i - then Z.pow2_mod (nth_default 0 us n) (log_cap n) - else nth_default 0 us n + - if eq_nat_dec n (S i) then nth_default 0 us i >> log_cap i else 0 - else d. - Proof using Type. - intros; unfold carry_simple; autorewrite with push_nth_default. - repeat break_match; try omega; try reflexivity. - Qed. - - Hint Rewrite @nth_default_carry_simple_full : push_nth_default. - - Lemma nth_default_carry_gen - : forall fc fi i us, - (0 <= i < length us)%nat - -> nth_default 0 (carry_gen limb_widths fc fi i us) i - = (if eq_nat_dec i (fi i) - then Z.pow2_mod (nth_default 0 us i) (log_cap i) - else nth_default 0 us i) + - if eq_nat_dec i (fi (S (fi i))) - then fc (nth_default 0 us (fi i) >> log_cap (fi i)) - else 0. - Proof using Type. - intros; autorewrite with push_nth_default natsimplify; break_match; omega. - Qed. - Hint Rewrite @nth_default_carry_gen using (omega || distr_length; omega) : push_nth_default. - - Lemma nth_default_carry_simple - : forall i us, - (0 <= i < length us)%nat - -> nth_default 0 (carry_simple limb_widths i us) i - = Z.pow2_mod (nth_default 0 us i) (log_cap i). - Proof using Type. - intros; autorewrite with push_nth_default natsimplify; break_match; omega. - Qed. - Hint Rewrite @nth_default_carry_simple using (omega || distr_length; omega) : push_nth_default. -End carrying. - -Hint Rewrite @length_carry_gen : distr_length. -Hint Rewrite @length_carry_simple @length_carry_simple_sequence @length_make_chain @length_full_carry_chain @length_carry_simple_full : distr_length. -Hint Rewrite @nth_default_carry_simple_full @nth_default_carry_gen_full : push_nth_default. -Hint Rewrite @nth_default_carry_simple @nth_default_carry_gen using (omega || distr_length; omega) : push_nth_default. diff --git a/src/ModularArithmetic/PseudoMersenneBaseParamProofs.v b/src/ModularArithmetic/PseudoMersenneBaseParamProofs.v deleted file mode 100644 index 85ed920a2..000000000 --- a/src/ModularArithmetic/PseudoMersenneBaseParamProofs.v +++ /dev/null @@ -1,99 +0,0 @@ -Require Import Coq.ZArith.Zpower Coq.ZArith.ZArith. -Require Import Coq.Lists.List. -Require Import Crypto.Util.ListUtil Crypto.Util.CaseUtil Crypto.Util.ZUtil. -Require Import Crypto.ModularArithmetic.ExtendedBaseVector. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.BaseSystem. -Require Import Crypto.BaseSystemProofs. -Require Import Crypto.ModularArithmetic.Pow2Base. -Require Import Crypto.ModularArithmetic.Pow2BaseProofs. -Require Crypto.BaseSystem. -Local Open Scope Z_scope. - -Section PseudoMersenneBaseParamProofs. - Context `{prm : PseudoMersenneBaseParams}. - Local Notation base := (base_from_limb_widths limb_widths). - - Lemma limb_widths_nonneg : forall w, In w limb_widths -> 0 <= w. - Proof using Type. auto using Z.lt_le_incl, limb_widths_pos. Qed. - - Lemma k_nonneg : 0 <= k. - Proof using Type. apply sum_firstn_limb_widths_nonneg, limb_widths_nonneg. Qed. - - Lemma lt_modulus_2k : modulus < 2 ^ k. - Proof using Type. - replace (2 ^ k) with (modulus + c) by (unfold c; ring). - pose proof c_pos; omega. - Qed. Hint Resolve lt_modulus_2k. - - Lemma modulus_pos : 0 < modulus. - Proof using Type*. - pose proof (NumTheoryUtil.lt_1_p _ prime_modulus); omega. - Qed. Hint Resolve modulus_pos. - - Lemma modulus_nonzero : Z.pos modulus <> 0. - Proof using Type*. - - pose proof (Znumtheory.prime_ge_2 _ prime_modulus); omega. - Qed. - - (* a = r + s(2^k) = r + s(2^k - c + c) = r + s(2^k - c) + cs = r + cs *) - Lemma pseudomersenne_add: forall x y, (x + ((2^k) * y)) mod modulus = (x + (c * y)) mod modulus. - Proof using Type. - intros. - replace (2^k) with ((2^k - c) + c) by ring. - rewrite Z.mul_add_distr_r, Zplus_mod. - unfold c. - rewrite Z.sub_sub_distr, Z.sub_diag. - rewrite Z.mul_comm, Z.mod_add_l; auto using modulus_nonzero. - rewrite <- Zplus_mod; auto. - Qed. - - Lemma pseudomersenne_add': forall x y0 y1 z, (z - x + ((2^k) * y0 * y1)) mod modulus = (c * y0 * y1 - x + z) mod modulus. - Proof using Type. - intros; rewrite <- !Z.add_opp_r, <- !Z.mul_assoc, pseudomersenne_add; apply f_equal2; omega. - Qed. - - Lemma extended_shiftadd: forall (us : digits), - decode (ext_base limb_widths) us = - decode base (firstn (length base) us) - + (2 ^ k * decode base (skipn (length base) us)). - Proof using Type. - intros. - unfold decode; rewrite <- mul_each_rep. - rewrite ext_base_alt by apply limb_widths_nonneg. - fold k; fold (mul_each (2 ^ k) base). - rewrite base_mul_app. - rewrite <- mul_each_rep; auto. - Qed. - - Global Instance bv : BaseSystem.BaseVector base := { - base_positive := base_positive limb_widths_nonneg; - b0_1 := fun x => b0_1 x limb_widths_nonnil; - base_good := base_good limb_widths_nonneg limb_widths_good - }. - - Lemma nth_default_base_positive : forall i, (i < length base)%nat -> - nth_default 0 base i > 0. - Proof using Type. - intros. - pose proof (nth_error_length_exists_value _ _ H). - destruct H0. - pose proof (nth_error_value_In _ _ _ H0). - pose proof (BaseSystem.base_positive _ H1). - unfold nth_default. - rewrite H0; auto. - Qed. - - Lemma base_succ_div_mult : forall i, ((S i) < length base)%nat -> - nth_default 0 base (S i) = nth_default 0 base i * - (nth_default 0 base (S i) / nth_default 0 base i). - Proof using Type. - intros. - apply Z_div_exact_2; try (apply nth_default_base_positive; omega). - apply base_succ; distr_length; eauto using limb_widths_nonneg. - Qed. - -End PseudoMersenneBaseParamProofs. diff --git a/src/ModularArithmetic/PseudoMersenneBaseParams.v b/src/ModularArithmetic/PseudoMersenneBaseParams.v deleted file mode 100644 index 6f6fd6556..000000000 --- a/src/ModularArithmetic/PseudoMersenneBaseParams.v +++ /dev/null @@ -1,24 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Coq.Lists.List. -Require Import Crypto.Util.ListUtil. -Require Crypto.BaseSystem. -Local Open Scope Z_scope. - -Class PseudoMersenneBaseParams (modulus : positive) := { - limb_widths : list Z; - limb_widths_pos : forall w, In w limb_widths -> 0 < w; - limb_widths_nonnil : limb_widths <> nil; - limb_widths_good : forall i j, (i + j < length limb_widths)%nat -> - sum_firstn limb_widths (i + j) <= - sum_firstn limb_widths i + sum_firstn limb_widths j; - prime_modulus : Znumtheory.prime (Z.pos modulus); - k := sum_firstn limb_widths (length limb_widths); - c := 2 ^ k - (Z.pos modulus); - c_pos : 0 < c; - limb_widths_match_modulus : forall i j, - (i < length limb_widths)%nat -> - (j < length limb_widths)%nat -> - (i + j >= length limb_widths)%nat -> - let w_sum := sum_firstn limb_widths in - k + w_sum (i + j - length limb_widths)%nat <= w_sum i + w_sum j -}. diff --git a/src/EdDSARepChange.v b/src/Primitives/EdDSARepChange.v index 0a214dc88..1ad4611be 100644 --- a/src/EdDSARepChange.v +++ b/src/Primitives/EdDSARepChange.v @@ -1,7 +1,7 @@ Require Import Crypto.Util.FixCoqMistakes. Require Import Crypto.Spec.EdDSA Bedrock.Word. Require Import Coq.Classes.Morphisms Coq.Relations.Relation_Definitions. -Require Import Crypto.Algebra. Import Monoid Group ScalarMult. +Require Import Crypto.Algebra.Monoid Crypto.Algebra.Group Crypto.Algebra.ScalarMult. Require Import Crypto.Util.Decidable Crypto.Util.Option. Require Import Crypto.Util.Tactics.SetEvars. Require Import Crypto.Util.Tactics.SubstEvars. @@ -10,7 +10,7 @@ Require Import Crypto.Util.Tactics.SpecializeBy. Require Import Coq.omega.Omega. Require Import Crypto.Util.Notations. Require Import Crypto.Util.Option Crypto.Util.Logic Crypto.Util.Relations Crypto.Util.WordUtil Util.LetIn Util.NatUtil. -Require Import Crypto.Spec.ModularArithmetic Crypto.ModularArithmetic.PrimeFieldTheorems. +Require Import Crypto.Spec.ModularArithmetic Crypto.Arithmetic.PrimeFieldTheorems. Import NPeano. Import Notations. @@ -102,7 +102,7 @@ Section EdDSA. Proof using Type*. exact (proj2_sig verify'_sig). Qed. Section ChangeRep. - Context {Erep ErepEq ErepAdd ErepId ErepOpp} {Agroup:@group Erep ErepEq ErepAdd ErepId ErepOpp}. + Context {Erep ErepEq ErepAdd ErepId ErepOpp} {Agroup:@Algebra.Hierarchy.group Erep ErepEq ErepAdd ErepId ErepOpp}. Context {EToRep} {Ahomom:@is_homomorphism E Eeq Eadd Erep ErepEq ErepAdd EToRep}. Context {ERepEnc : Erep -> word b} diff --git a/src/MxDHRepChange.v b/src/Primitives/MxDHRepChange.v index 995c11409..9f0276ef8 100644 --- a/src/MxDHRepChange.v +++ b/src/Primitives/MxDHRepChange.v @@ -1,12 +1,12 @@ Require Import Crypto.Spec.MxDH. -Require Import Crypto.Algebra Crypto.Algebra.Monoid Crypto.Algebra.Group Crypto.Algebra.Ring Crypto.Algebra.Field. -Require Import Crypto.Util.Tuple. +Require Import Crypto.Algebra.Monoid Crypto.Algebra.Group Crypto.Algebra.Ring Crypto.Algebra.Field. +Require Import Crypto.Util.Tuple Crypto.Util.Prod. Require Import Crypto.Util.Tactics.DestructHead. Require Import Crypto.Util.Tactics.BreakMatch. Section MxDHRepChange. - Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {Fcswap:bool->F*F->F*F->(F*F)*(F*F)} {Fa24:F} {tb1:nat->bool}. - Context {K Keq Kzero Kone Kopp Kadd Ksub Kmul Kinv Kdiv} {impl_field:@Algebra.field K Keq Kzero Kone Kopp Kadd Ksub Kmul Kinv Kdiv} {Keq_dec:Decidable.DecidableRel Keq} {Kcswap:bool->K*K->K*K->(K*K)*(K*K)} {Ka24:K} {tb2:nat->bool}. + Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {Fcswap:bool->F*F->F*F->(F*F)*(F*F)} {Fa24:F} {tb1:nat->bool}. + Context {K Keq Kzero Kone Kopp Kadd Ksub Kmul Kinv Kdiv} {impl_field:@Algebra.Hierarchy.field K Keq Kzero Kone Kopp Kadd Ksub Kmul Kinv Kdiv} {Keq_dec:Decidable.DecidableRel Keq} {Kcswap:bool->K*K->K*K->(K*K)*(K*K)} {Ka24:K} {tb2:nat->bool}. Context {FtoK} {homom:@Ring.is_homomorphism F Feq Fone Fadd Fmul K Keq Kone Kadd Kmul FtoK}. @@ -121,7 +121,7 @@ Section MxDHRepChange. Proper (loopiter_eq ==> eq ==> loopiter_eq) (loopiter K Kzero Kone Kadd Ksub Kmul Kinv Ka24 Kcswap a b c). Proof using Kcswap_correct Keq_dec impl_field. unfold loopiter; intros [? ?] [? ?] [[[] []] ?]; repeat intro ; cbv [fst snd] in * |-; subst. - repeat VerdiTactics.break_match; subst; repeat (VerdiTactics.find_injection; intros; subst). + repeat (break_match; break_match_hyps). split; [|reflexivity]. etransitivity; [|etransitivity]; [ | eapply Proper_ladderstep | ]; [eapply eq_subrelation; [ exact _ | symmetry; eassumption ] @@ -129,8 +129,7 @@ Section MxDHRepChange. | eapply eq_subrelation; [exact _ | eassumption ] ]; rewrite !Kcswap_correct in *; match goal with [H: (if ?b then _ else _) = _ |- _] => destruct b end; - repeat (VerdiTactics.find_injection; intros; subst); - split; simpl; eauto. + destruct_head prod; inversion_prod; subst; eauto. Qed. Lemma MxDHRepChange b (x:F) : @@ -152,7 +151,7 @@ Section MxDHRepChange. { destruct_head' prod; destruct Hrel as [[[] []] ?]; simpl in *; subst. rewrite !Fcswap_correct, !Kcswap_correct in *. match goal with [H: (if ?b then _ else _) = _ |- _] => destruct b end; - repeat (VerdiTactics.find_injection; intros; subst); + destruct_head prod; inversion_prod; subst; repeat match goal with [H: Keq (FtoK ?x) (?kx)|- _ ] => rewrite <- H end; t. } diff --git a/src/Reflection/Z/Inline.v b/src/Reflection/Z/Inline.v deleted file mode 100644 index 989286232..000000000 --- a/src/Reflection/Z/Inline.v +++ /dev/null @@ -1,7 +0,0 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Inline. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Util. - -Definition InlineConst {t} (e : Expr base_type op t) : Expr base_type op t - := @InlineConst base_type op (is_const) t e. diff --git a/src/Reflection/Z/InlineWf.v b/src/Reflection/Z/InlineWf.v deleted file mode 100644 index 5d5eb0617..000000000 --- a/src/Reflection/Z/InlineWf.v +++ /dev/null @@ -1,11 +0,0 @@ -Require Import Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Wf. -Require Import Crypto.Reflection.InlineWf. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Inline. - -Definition Wf_InlineConst {t} (e : Expr base_type op t) (Hwf : Wf e) - : Wf (InlineConst e) - := @Wf_InlineConst _ _ _ t e Hwf. - -Hint Resolve Wf_InlineConst : wf. diff --git a/src/Reflection/Z/Reify.v b/src/Reflection/Z/Reify.v deleted file mode 100644 index 0573501b7..000000000 --- a/src/Reflection/Z/Reify.v +++ /dev/null @@ -1,59 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Crypto.ModularArithmetic.ModularBaseSystemListZOperations. -Require Import Crypto.Reflection.InputSyntax. -Require Import Crypto.Reflection.Z.Syntax. -Require Import Crypto.Reflection.Z.Syntax.Equality. -Require Import Crypto.Reflection.Z.Syntax.Util. -Require Import Crypto.Reflection.WfReflective. -Require Import Crypto.Reflection.Reify. -Require Import Crypto.Reflection.Inline. -Require Import Crypto.Reflection.InlineInterp. -Require Import Crypto.Reflection.Linearize. -Require Import Crypto.Reflection.LinearizeInterp. -Require Import Crypto.Reflection.Eta. -Require Import Crypto.Reflection.EtaInterp. - -Ltac base_reify_op op op_head extra ::= - lazymatch op_head with - | @Z.add => constr:(reify_op op op_head 2 (Add TZ TZ TZ)) - | @Z.mul => constr:(reify_op op op_head 2 (Mul TZ TZ TZ)) - | @Z.sub => constr:(reify_op op op_head 2 (Sub TZ TZ TZ)) - | @Z.shiftl => constr:(reify_op op op_head 2 (Shl TZ TZ TZ)) - | @Z.shiftr => constr:(reify_op op op_head 2 (Shr TZ TZ TZ)) - | @Z.land => constr:(reify_op op op_head 2 (Land TZ TZ TZ)) - | @Z.lor => constr:(reify_op op op_head 2 (Lor TZ TZ TZ)) - | @Z.opp => constr:(reify_op op op_head 1 (Opp TZ TZ)) - | @ModularBaseSystemListZOperations.cmovne => constr:(reify_op op op_head 4 (Cmovne TZ TZ TZ TZ TZ)) - | @ModularBaseSystemListZOperations.cmovl => constr:(reify_op op op_head 4 (Cmovle TZ TZ TZ TZ TZ)) - | @ModularBaseSystemListZOperations.neg - => lazymatch extra with - | @ModularBaseSystemListZOperations.neg ?int_width _ - => constr:(reify_op op op_head 1 (Neg TZ TZ int_width)) - | _ => fail 100 "Anomaly: In Reflection.Z.base_reify_op: head is neg but body is wrong:" extra - end - end. -Ltac base_reify_type T ::= - lazymatch T with - | Z => TZ - end. -Ltac Reify' e := Reflection.Reify.Reify' base_type interp_base_type op e. -Ltac Reify e := - let v := Reflection.Reify.Reify base_type interp_base_type op make_const e in - constr:(ExprEta v). -Ltac prove_ExprEta_Compile_correct := - fun _ - => intros; - rewrite ?InterpExprEta; - prove_compile_correct_using ltac:(fun _ => apply make_const_correct) (). - -Ltac Reify_rhs := - Reflection.Reify.Reify_rhs_gen Reify prove_ExprEta_Compile_correct interp_op ltac:(fun tac => tac ()). - -Ltac prereify_context_variables := - Reflection.Reify.prereify_context_variables interp_base_type. -Ltac reify_context_variable := - Reflection.Reify.reify_context_variable base_type interp_base_type op. -Ltac lazy_reify_context_variable := - Reflection.Reify.lazy_reify_context_variable base_type interp_base_type op. -Ltac reify_context_variables := - Reflection.Reify.reify_context_variables base_type interp_base_type op. diff --git a/src/Spec/CompleteEdwardsCurve.v b/src/Spec/CompleteEdwardsCurve.v index daaa2ed74..83e5645d5 100644 --- a/src/Spec/CompleteEdwardsCurve.v +++ b/src/Spec/CompleteEdwardsCurve.v @@ -1,4 +1,4 @@ -Require Crypto.CompleteEdwardsCurve.Pre. +Require Crypto.Curves.Edwards.Pre. Require Crypto.Util.Decidable. Module E. @@ -10,7 +10,7 @@ Module E. *) Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {char_ge_3 : @Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos BinNat.N.two)} {Feq_dec:Decidable.DecidableRel Feq}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. diff --git a/src/Spec/Ed25519.v b/src/Spec/Ed25519.v index 2a2847a31..b8526bb0e 100644 --- a/src/Spec/Ed25519.v +++ b/src/Spec/Ed25519.v @@ -2,7 +2,8 @@ Require Import Crypto.Spec.ModularArithmetic. Require Import Crypto.Spec.CompleteEdwardsCurve. Require Import Crypto.Spec.EdDSA. -Require ModularArithmetic.PrimeFieldTheorems. (* to know that Z mod p is a field *) +Require Crypto.Arithmetic.PrimeFieldTheorems. (* to know that Z mod p is a field *) +Require Crypto.Curves.Edwards.AffineProofs. (* these 2 proofs can be generated using https://github.com/andres-erbsen/safecurves-primes *) Axiom prime_q : Znumtheory.prime (2^255-19). Global Existing Instance prime_q. @@ -83,7 +84,7 @@ Section Ed25519. Definition ed25519 (l_order_B: E.eq(F:=Fq)(Fone:=F.one) (mul (BinInt.Z.to_nat l) B)%E zero) : EdDSA (E:=E) (Eadd:=add) (Ezero:=zero) (EscalarMult:=mul) (B:=B) - (Eopp:=Crypto.CompleteEdwardsCurve.CompleteEdwardsCurveTheorems.E.opp(nonzero_a:=nonzero_a)) (* TODO: move defn *) + (Eopp:=Crypto.Curves.Edwards.AffineProofs.E.opp(nonzero_a:=nonzero_a)) (* TODO: move defn *) (Eeq:=E.eq) (* TODO: move defn *) (l:=l) (b:=b) (n:=n) (c:=c) (Eenc:=Eenc) (Senc:=Senc) (H:=SHA512). diff --git a/src/Spec/EdDSA.v b/src/Spec/EdDSA.v index 67a1014f6..82a9ba6cc 100644 --- a/src/Spec/EdDSA.v +++ b/src/Spec/EdDSA.v @@ -1,7 +1,7 @@ Require Bedrock.Word Crypto.Util.WordUtil. Require Coq.ZArith.Znumtheory Coq.ZArith.BinInt. Require Coq.Numbers.Natural.Peano.NPeano. -Require Crypto.CompleteEdwardsCurve.CompleteEdwardsCurveTheorems. +Require Crypto.Algebra.ScalarMult. Require Import Omega. (* TODO: remove this import when we drop 8.4 *) @@ -41,7 +41,7 @@ Section EdDSA. {Senc : F l -> Word.word b} (* normative encoding of scalars *) := { - EdDSA_group:@Algebra.group E Eeq Eadd Ezero Eopp; + EdDSA_group:@Algebra.Hierarchy.group E Eeq Eadd Ezero Eopp; EdDSA_scalarmult:@Algebra.ScalarMult.is_scalarmult E Eeq Eadd Ezero EscalarMult; EdDSA_c_valid : c = 2 \/ c = 3; diff --git a/src/Spec/Encoding.v b/src/Spec/Encoding.v deleted file mode 100644 index b063b638f..000000000 --- a/src/Spec/Encoding.v +++ /dev/null @@ -1,8 +0,0 @@ -Class CanonicalEncoding (T B:Type) := { - enc : T -> B ; - dec : B -> option T ; - encoding_valid : forall x, dec (enc x) = Some x ; - encoding_canonical : forall x_enc x, dec x_enc = Some x -> enc x = x_enc -}. - -Notation "'canonical' 'encoding' 'of' T 'as' B" := (CanonicalEncoding T B) (at level 50).
\ No newline at end of file diff --git a/src/Spec/ModularArithmetic.v b/src/Spec/ModularArithmetic.v index ed6a0c4a2..cb57b4547 100644 --- a/src/Spec/ModularArithmetic.v +++ b/src/Spec/ModularArithmetic.v @@ -1,6 +1,6 @@ Require Coq.ZArith.Znumtheory Coq.Numbers.BinNums. -Require Crypto.ModularArithmetic.Pre. +Require Crypto.Arithmetic.ModularArithmeticPre. Delimit Scope positive_scope with positive. Bind Scope positive_scope with BinPos.positive. @@ -33,7 +33,7 @@ Global Set Printing Coercions. Module F. Definition F (m : BinPos.positive) := { z : BinInt.Z | z = z mod m }. - Local Obligation Tactic := cbv beta; auto using Pre.Z_mod_mod. + Local Obligation Tactic := cbv beta; auto using ModularArithmeticPre.Z_mod_mod. Program Definition of_Z m (a:BinNums.Z) : F m := a mod m. Definition to_Z {m} (a:F m) : BinNums.Z := proj1_sig a. @@ -51,14 +51,14 @@ Module F. | inv zero = zero /\ ( Znumtheory.prime m -> forall a, a <> zero -> mul (inv a) a = one ) - } := Pre.inv_impl. + } := ModularArithmeticPre.inv_impl. Definition inv : F m -> F m := Eval hnf in proj1_sig inv_with_spec. Definition div (a b:F m) : F m := mul a (inv b). Definition pow_with_spec : { pow : F m -> BinNums.N -> F m | forall a, pow a 0%N = one /\ forall x, pow a (1 + x)%N = mul a (pow a x) - } := Pre.pow_impl. + } := ModularArithmeticPre.pow_impl. Definition pow : F m -> BinNums.N -> F m := Eval hnf in proj1_sig pow_with_spec. End FieldOperations. diff --git a/src/Spec/ModularWordEncoding.v b/src/Spec/ModularWordEncoding.v deleted file mode 100644 index 5b0bdb545..000000000 --- a/src/Spec/ModularWordEncoding.v +++ /dev/null @@ -1,40 +0,0 @@ -Require Import Coq.ZArith.ZArith. -Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Bedrock.Word. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.NatUtil. -Require Import Crypto.Util.WordUtil. -Require Import Crypto.Spec.Encoding. -Require Crypto.Encoding.ModularWordEncodingPre. - -Local Open Scope nat_scope. - -Section ModularWordEncoding. - Context {m : positive} {sz : nat} {m_pos : (0 < m)%Z} {bound_check : Z.to_nat m < 2 ^ sz}. - - Definition Fm_enc (x : F m) : word sz := NToWord sz (Z.to_N (F.to_Z x)). - - Definition Fm_dec (x_ : word sz) : option (F m) := - let z := Z.of_N (wordToN (x_)) in - if Z_lt_dec z m - then Some (F.of_Z m z) - else None - . - - Definition sign_bit (x : F m) := - match (Fm_enc x) with - | Word.WO => false - | Word.WS b _ w' => b - end. - - Global Instance modular_word_encoding : canonical encoding of F m as word sz := { - enc := Fm_enc; - dec := Fm_dec; - encoding_valid := - @ModularWordEncodingPre.Fm_encoding_valid m sz m_pos bound_check; - encoding_canonical := - @ModularWordEncodingPre.Fm_encoding_canonical m sz bound_check - }. - -End ModularWordEncoding.
\ No newline at end of file diff --git a/src/Spec/MontgomeryCurve.v b/src/Spec/MontgomeryCurve.v index e5ed281f9..ff6d3a080 100644 --- a/src/Spec/MontgomeryCurve.v +++ b/src/Spec/MontgomeryCurve.v @@ -1,4 +1,4 @@ -Require Crypto.Algebra Crypto.Algebra.Field. +Require Crypto.Algebra.Field. Require Crypto.Util.GlobalSettings. Require Crypto.Util.Tactics.DestructHead Crypto.Util.Sum Crypto.Util.Prod. @@ -6,7 +6,7 @@ Module M. Section MontgomeryCurve. Import BinNat. Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} - {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} + {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. diff --git a/src/Spec/MxDH.v b/src/Spec/MxDH.v index 27f5f9a7f..d70521581 100644 --- a/src/Spec/MxDH.v +++ b/src/Spec/MxDH.v @@ -1,9 +1,9 @@ -Require Crypto.Algebra. +Require Crypto.Algebra.Hierarchy. Require Import Crypto.Util.Notations. Module MxDH. (* from RFC7748 *) Section MontgomeryLadderKeyExchange. - Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq}. + Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. Local Infix "+" := Fadd. Local Infix "*" := Fmul. Local Infix "-" := Fsub. Local Infix "/" := Fdiv. diff --git a/src/Test/Curve25519SpecTestVectors.v b/src/Spec/Test/X25519.v index 15ca468c1..15ca468c1 100644 --- a/src/Test/Curve25519SpecTestVectors.v +++ b/src/Spec/Test/X25519.v diff --git a/src/Spec/WeierstrassCurve.v b/src/Spec/WeierstrassCurve.v index eebc79df4..226ec6616 100644 --- a/src/Spec/WeierstrassCurve.v +++ b/src/Spec/WeierstrassCurve.v @@ -1,4 +1,4 @@ -Require Crypto.WeierstrassCurve.Pre. +Require Crypto.Curves.Weierstrass.Pre. Module W. Section WeierstrassCurves. @@ -9,7 +9,7 @@ Module W. * <http://cs.ucsb.edu/~koc/ccs130h/2013/EllipticHyperelliptic-CohenFrey.pdf> (page 79) *) - Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))}. + Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))}. Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope. Local Notation "x =? y" := (Decidable.dec (Feq x y)) (at level 70, no associativity) : type_scope. Local Notation "x =? y" := (Sumbool.bool_of_sumbool (Decidable.dec (Feq x y))) : bool_scope. diff --git a/src/Specific/NewBaseSystemTest.v b/src/Specific/ArithmeticSynthesisTest.v index f0d0d763b..369f242c8 100644 --- a/src/Specific/NewBaseSystemTest.v +++ b/src/Specific/ArithmeticSynthesisTest.v @@ -1,7 +1,7 @@ Require Import Coq.ZArith.ZArith Coq.ZArith.BinIntDef. Require Import Coq.Lists.List. Import ListNotations. -Require Import Crypto.NewBaseSystem. Import B. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. +Require Import Crypto.Arithmetic.Core. Import B. +Require Import Crypto.Arithmetic.PrimeFieldTheorems. Require Import (*Crypto.Util.Tactics*) Crypto.Util.Decidable. Require Import Crypto.Util.LetIn Crypto.Util.ZUtil Crypto.Util.Tactics. Require Crypto.Util.Tuple. diff --git a/src/Specific/FancyMachine256/Barrett.v b/src/Specific/FancyMachine256/Barrett.v index b87a9a0bc..263bc82ba 100644 --- a/src/Specific/FancyMachine256/Barrett.v +++ b/src/Specific/FancyMachine256/Barrett.v @@ -1,6 +1,6 @@ Require Import Crypto.Specific.FancyMachine256.Core. -Require Import Crypto.ModularArithmetic.BarrettReduction.ZBounded. -Require Import Crypto.ModularArithmetic.BarrettReduction.ZHandbook. +Require Import LegacyArithmetic.BarretReduction. +Require Import Crypto.Arithmetic.BarrettReduction.HAC. (** Useful for arithmetic in the field of integers modulo the order of the curve25519 base point *) Section expression. diff --git a/src/Specific/FancyMachine256/Core.v b/src/Specific/FancyMachine256/Core.v index 6ea614936..900ac92a9 100644 --- a/src/Specific/FancyMachine256/Core.v +++ b/src/Specific/FancyMachine256/Core.v @@ -3,22 +3,22 @@ Require Import Coq.Classes.RelationClasses Coq.Classes.Morphisms. Require Import Coq.PArith.BinPos Coq.micromega.Psatz. Require Export Coq.ZArith.ZArith Coq.Lists.List. Require Import Crypto.Util.Decidable. -Require Export Crypto.BoundedArithmetic.Interface. -Require Export Crypto.BoundedArithmetic.ArchitectureToZLike. -Require Export Crypto.BoundedArithmetic.ArchitectureToZLikeProofs. +Require Export Crypto.LegacyArithmetic.Interface. +Require Export Crypto.LegacyArithmetic.ArchitectureToZLike. +Require Export Crypto.LegacyArithmetic.ArchitectureToZLikeProofs. Require Export Crypto.Util.Tuple. Require Import Crypto.Util.Option Crypto.Util.Sigma Crypto.Util.Prod. -Require Export Crypto.Reflection.Named.Syntax. -Require Export Crypto.Reflection.Named.PositiveContext. -Require Import Crypto.Reflection.Named.DeadCodeElimination. -Require Import Crypto.Reflection.CountLets. -Require Import Crypto.Reflection.Named.ContextOn. -Require Import Crypto.Reflection.Named.Wf. -Require Export Crypto.Reflection.Syntax. -Require Import Crypto.Reflection.Linearize. -Require Import Crypto.Reflection.Inline. -Require Import Crypto.Reflection.CommonSubexpressionElimination. -Require Export Crypto.Reflection.Reify. +Require Export Crypto.Compilers.Named.Syntax. +Require Export Crypto.Compilers.Named.PositiveContext. +Require Import Crypto.Compilers.Named.DeadCodeElimination. +Require Import Crypto.Compilers.CountLets. +Require Import Crypto.Compilers.Named.ContextOn. +Require Import Crypto.Compilers.Named.Wf. +Require Export Crypto.Compilers.Syntax. +Require Import Crypto.Compilers.Linearize. +Require Import Crypto.Compilers.Inline. +Require Import Crypto.Compilers.CommonSubexpressionElimination. +Require Export Crypto.Compilers.Reify. Require Export Crypto.Util.ZUtil. Require Export Crypto.Util.Option. Require Export Crypto.Util.Notations. @@ -245,7 +245,7 @@ Section assemble. := invert_Some (@Named.interp base_type interp_base_type op Register RegisterContext interp_op empty t e v). End assemble. -Export Reflection.Named.Syntax. +Export Compilers.Named.Syntax. Open Scope nexpr_scope. Open Scope ctype_scope. Open Scope type_scope. diff --git a/src/Specific/FancyMachine256/Montgomery.v b/src/Specific/FancyMachine256/Montgomery.v index f052cd548..e6af32aab 100644 --- a/src/Specific/FancyMachine256/Montgomery.v +++ b/src/Specific/FancyMachine256/Montgomery.v @@ -1,6 +1,6 @@ Require Import Crypto.Specific.FancyMachine256.Core. -Require Import Crypto.ModularArithmetic.Montgomery.ZBounded. -Require Import Crypto.ModularArithmetic.Montgomery.ZProofs. +Require Import Crypto.LegacyArithmetic.MontgomeryReduction. +Require Import Crypto.Arithmetic.MontgomeryReduction.Proofs. Section expression. Context (ops : fancy_machine.instructions (2 * 128)) (props : fancy_machine.arithmetic ops) (modulus : Z) (m' : Z) (Hm : modulus <> 0) (H : 0 <= modulus < 2^256) (Hm' : 0 <= m' < 2^256). @@ -48,7 +48,7 @@ Section expression. v Hv : fancy_machine.decode (expression v) = _ - := @ZBounded.reduce_via_partial_correct (2^256) modulus _ (props' _ _ eq_refl eq_refl) (ldi' m') I Hm R' HR0 HR1 (fst v, snd v) I Hv. + := @Crypto.LegacyArithmetic.MontgomeryReduction.reduce_via_partial_correct (2^256) modulus _ (props' _ _ eq_refl eq_refl) (ldi' m') I Hm R' HR0 HR1 (fst v, snd v) I Hv. End expression. Section reflected. diff --git a/src/Specific/GF1305.v b/src/Specific/GF1305.v deleted file mode 100644 index 6ddc12ee5..000000000 --- a/src/Specific/GF1305.v +++ /dev/null @@ -1,404 +0,0 @@ -Require Import Crypto.BaseSystem. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystem. -Require Import Crypto.ModularArithmetic.ModularBaseSystemProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystemOpt. -Require Import Crypto.Util.Tuple. -Require Import Coq.Lists.List Crypto.Util.ListUtil. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.LetIn. -Require Import Crypto.Util.Notations. -Require Import Crypto.Util.Decidable. -Require Import Crypto.Algebra. -Import ListNotations. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.ZArith.Znumtheory. -Local Open Scope Z. - -(* BEGIN precomputation. *) - -Definition modulus : positive := (2^130 - 5)%positive. -Lemma prime_modulus : prime modulus. Admitted. -Definition int_width := 32%Z. - -Instance params1305 : PseudoMersenneBaseParams modulus. - construct_params prime_modulus 5%nat 130. -Defined. - -Definition fe1305 := Eval compute in (tuple Z (length limb_widths)). - -Definition mul2modulus : fe1305 := - Eval compute in (from_list_default 0%Z (length limb_widths) (construct_mul2modulus params1305)). - -Instance subCoeff : @SubtractionCoefficient modulus params1305. - apply Build_SubtractionCoefficient with (coeff := mul2modulus). - vm_decide. -Defined. - -Instance carryChain : CarryChain limb_widths. - apply Build_CarryChain with (carry_chain := ([0;1;2;3;4;0])%nat). - intros; - repeat (destruct H as [|H]; [subst; vm_compute; repeat constructor | ]). - contradiction H. -Defined. - -Definition freezePreconditions1305 : FreezePreconditions int_width int_width. -Proof. - constructor; compute_preconditions. -Defined. -(* Wire format for [pack] and [unpack] *) -Definition wire_widths := Eval compute in (repeat 32 4 ++ 2 :: nil). - -Definition wire_digits := Eval compute in (tuple Z (length wire_widths)). - -Lemma wire_widths_nonneg : forall w, In w wire_widths -> 0 <= w. -Proof. - intros. - repeat (destruct H as [|H]; [subst; vm_compute; congruence | ]). - contradiction H. -Qed. - -Lemma bits_eq : sum_firstn limb_widths (length limb_widths) = sum_firstn wire_widths (length wire_widths). -Proof. reflexivity. Qed. - -Lemma modulus_gt_2 : 2 < modulus. Proof. cbv; congruence. Qed. - -(* Temporarily, we'll use addition chains equivalent to double-and-add. This is pending - finding the real, more optimal chains from previous work. *) -Fixpoint pow2Chain'' p (pow2_index acc_index : nat) chain_acc : list (nat * nat) := - match p with - | xI p' => pow2Chain'' p' 1 0 - (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - | xO p' => pow2Chain'' p' 0 (S acc_index) - (chain_acc ++ (pow2_index, pow2_index)::nil) - | xH => (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - end. - -Fixpoint pow2Chain' p index := - match p with - | xI p' => pow2Chain'' p' 0 0 (repeat (0,0)%nat index) - | xO p' => pow2Chain' p' (S index) - | xH => repeat (0,0)%nat index - end. - -Definition pow2_chain p := - match p with - | xH => nil - | _ => pow2Chain' p 0 - end. - -Definition invChain := Eval compute in pow2_chain (Z.to_pos (modulus - 2)). - -Instance inv_ec : ExponentiationChain (modulus - 2). - apply Build_ExponentiationChain with (chain := invChain). - reflexivity. -Defined. - -(* Note : use caution copying square root code to other primes. The (modulus / 4 + 1) chains are - for primes that are 3 mod 4; if the prime is 5 mod 8 then use (modulus / 8 + 1). *) -Definition sqrtChain := Eval compute in pow2_chain (Z.to_pos (modulus / 4 + 1)). - -Instance sqrt_ec : ExponentiationChain (modulus / 4 + 1). - apply Build_ExponentiationChain with (chain := sqrtChain). - reflexivity. -Defined. - -Arguments chain {_ _ _} _. - -(* END precomputation *) - -(* Precompute k, c, zero, and one *) -Definition k_ := Eval compute in k. -Definition c_ := Eval compute in c. -Definition one_ := Eval compute in one. -Definition zero_ := Eval compute in zero. -Definition k_subst : k = k_ := eq_refl k_. -Definition c_subst : c = c_ := eq_refl c_. -Definition one_subst : one = one_ := eq_refl one_. -Definition zero_subst : zero = zero_ := eq_refl zero_. - -Local Opaque Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In. - -Definition app_5 {T} (f : fe1305) (P : fe1305 -> T) : T. -Proof. - cbv [fe1305] in *. - set (f0 := f). - repeat (let g := fresh "g" in destruct f as [f g]). - apply P. - apply f0. -Defined. - -Definition app_5_correct {T} f (P : fe1305 -> T) : app_5 f P = P f. -Proof. - intros. - cbv [fe1305] in *. - repeat match goal with [p : (_*Z)%type |- _ ] => destruct p end. - reflexivity. -Qed. - -Definition appify2 {T} (op : fe1305 -> fe1305 -> T) (f g : fe1305) := - app_5 f (fun f0 => (app_5 g (fun g0 => op f0 g0))). - -Lemma appify2_correct : forall {T} op f g, @appify2 T op f g = op f g. -Proof. - intros. cbv [appify2]. - etransitivity; apply app_5_correct. -Qed. - -Definition add_sig (f g : fe1305) : - { fg : fe1305 | fg = add_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe1305). - cbv. - reflexivity. -Defined. - -Definition add (f g : fe1305) : fe1305 := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj1_sig (add_sig f g). - -Definition add_correct (f g : fe1305) - : add f g = add_opt f g := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj2_sig (add_sig f g). - -Definition sub_sig (f g : fe1305) : - { fg : fe1305 | fg = sub_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe1305). - cbv. - reflexivity. -Defined. - -Definition sub (f g : fe1305) : fe1305 := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj1_sig (sub_sig f g). - -Definition sub_correct (f g : fe1305) - : sub f g = sub_opt f g := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj2_sig (sub_sig f g). - -(* For multiplication, we add another layer of definition so that we can - rewrite under the [let] binders. *) -Definition mul_simpl_sig (f g : fe1305) : - { fg : fe1305 | fg = carry_mul_opt k_ c_ f g}. -Proof. - cbv [fe1305] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv. - autorewrite with zsimplify. - reflexivity. -Defined. - -Definition mul_simpl (f g : fe1305) : fe1305 := - Eval cbv beta iota delta [proj1_sig mul_simpl_sig] in - proj1_sig (mul_simpl_sig f g). - -Definition mul_simpl_correct (f g : fe1305) - : mul_simpl f g = carry_mul_opt k_ c_ f g := - Eval cbv beta iota delta [proj1_sig mul_simpl_sig] in - proj2_sig (mul_simpl_sig f g). - -Definition mul_sig (f g : fe1305) : - { fg : fe1305 | fg = carry_mul_opt k_ c_ f g}. -Proof. - eexists. - rewrite <-mul_simpl_correct. - rewrite <-(@appify2_correct fe1305). - cbv. - reflexivity. -Defined. - -Definition mul (f g : fe1305) : fe1305 := - Eval cbv beta iota delta [proj1_sig mul_sig] in - proj1_sig (mul_sig f g). - -Definition mul_correct (f g : fe1305) - : mul f g = carry_mul_opt k_ c_ f g := - Eval cbv beta iota delta [proj2_sig add_sig] in - proj2_sig (mul_sig f g). - -Definition opp_sig (f : fe1305) : - { g : fe1305 | g = opp_opt f }. -Proof. - eexists. - cbv [opp_opt]. - rewrite <-sub_correct. - rewrite zero_subst. - cbv [sub]. - reflexivity. -Defined. - -Definition opp (f : fe1305) : fe1305 - := Eval cbv beta iota delta [proj1_sig opp_sig] in proj1_sig (opp_sig f). - -Definition opp_correct (f : fe1305) - : opp f = opp_opt f - := Eval cbv beta iota delta [proj2_sig add_sig] in proj2_sig (opp_sig f). - -Definition pow (f : fe1305) chain := fold_chain_opt one_ mul chain [f]. - -Lemma pow_correct (f : fe1305) : forall chain, pow f chain = pow_opt k_ c_ one_ f chain. -Proof. - cbv [pow pow_opt]; intros. - rewrite !fold_chain_opt_correct. - apply Proper_fold_chain; try reflexivity. - intros; subst; apply mul_correct. -Qed. - -Definition inv_sig (f : fe1305) : - { g : fe1305 | g = inv_opt k_ c_ one_ f }. -Proof. - eexists; cbv [inv_opt]. - rewrite <-pow_correct. - cbv - [mul]. - reflexivity. -Defined. - -Definition inv (f : fe1305) : fe1305 - := Eval cbv beta iota delta [proj1_sig inv_sig] in proj1_sig (inv_sig f). - -Definition inv_correct (f : fe1305) - : inv f = inv_opt k_ c_ one_ f - := Eval cbv beta iota delta [proj2_sig inv_sig] in proj2_sig (inv_sig f). - -Definition mbs_field := modular_base_system_field modulus_gt_2. - -Import Morphisms. - -Lemma field1305 : @field fe1305 eq zero one opp add sub mul inv div. -Proof. - pose proof (Equivalence_Reflexive : Reflexive eq). - eapply (Field.equivalent_operations_field (fieldR := mbs_field)). - Grab Existential Variables. - + reflexivity. - + reflexivity. - + reflexivity. - + intros; rewrite mul_correct. - rewrite carry_mul_opt_correct by auto using k_subst, c_subst. - cbv [eq]. - rewrite carry_mul_rep by reflexivity. - rewrite mul_rep; reflexivity. - + intros; rewrite sub_correct, sub_opt_correct; reflexivity. - + intros; rewrite add_correct, add_opt_correct; reflexivity. - + intros; rewrite inv_correct, inv_opt_correct; reflexivity. - + intros; rewrite opp_correct, opp_opt_correct; reflexivity. -Qed. - -Lemma homomorphism_F1305 : - @Ring.is_homomorphism - (F modulus) Logic.eq F.one F.add F.mul - fe1305 eq one add mul encode. -Proof. - econstructor. - + econstructor; [ | apply encode_Proper]. - intros; cbv [eq]. - rewrite add_correct, add_opt_correct, add_rep; apply encode_rep. - + intros; cbv [eq]. - rewrite mul_correct, carry_mul_opt_correct, carry_mul_rep - by auto using k_subst, c_subst, encode_rep. - apply encode_rep. - + reflexivity. -Qed. - -Definition pack_simpl_sig (f : fe1305) : - { f' | f' = pack_opt params1305 wire_widths_nonneg bits_eq f }. -Proof. - cbv [fe1305] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [pack_opt]. - repeat ( - rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']; - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r). - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition pack_simpl (f : fe1305) := - Eval cbv beta iota delta [proj1_sig pack_simpl_sig] in - proj1_sig (pack_simpl_sig f). - -Definition pack_simpl_correct (f : fe1305) - : pack_simpl f = pack_opt params1305 wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_simpl_sig] in proj2_sig (pack_simpl_sig f). - -Definition pack_sig (f : fe1305) : - { f' | f' = pack_opt params1305 wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-pack_simpl_correct. - rewrite <-(@app_5_correct wire_digits). - cbv. - reflexivity. -Defined. - -Definition pack (f : fe1305) : wire_digits := - Eval cbv beta iota delta [proj1_sig pack_sig] in proj1_sig (pack_sig f). - -Definition pack_correct (f : fe1305) - : pack f = pack_opt params1305 wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (pack_sig f). - -Definition unpack_simpl_sig (f : wire_digits) : - { f' | f' = unpack_opt params1305 wire_widths_nonneg bits_eq f }. -Proof. - cbv [wire_digits] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [unpack_opt]. - repeat ( - rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']; - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r). - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition unpack_simpl (f : wire_digits) : fe1305 := - Eval cbv beta iota delta [proj1_sig unpack_simpl_sig] in - proj1_sig (unpack_simpl_sig f). - -Definition unpack_simpl_correct (f : wire_digits) - : unpack_simpl f = unpack_opt params1305 wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig unpack_simpl_sig] in proj2_sig (unpack_simpl_sig f). - -Definition unpack_sig (f : wire_digits) : - { f' | f' = unpack_opt params1305 wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-unpack_simpl_correct. - rewrite <-(@app_5_correct fe1305). - cbv. - reflexivity. -Defined. - -Definition unpack (f : wire_digits) : fe1305 := - Eval cbv beta iota delta [proj1_sig unpack_sig] in proj1_sig (unpack_sig f). - -Definition unpack_correct (f : wire_digits) - : unpack f = unpack_opt params1305 wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (unpack_sig f). - -Definition sqrt_sig (f : fe1305) : - { g | g = sqrt_3mod4_opt k_ c_ one_ f}. -Proof. - eexists; cbv [sqrt_3mod4_opt]. - rewrite <-pow_correct. - cbv - [mul]. - reflexivity. -Defined. - -Definition sqrt (f : fe1305) : fe1305 := - Eval cbv beta iota delta [proj1_sig sqrt_sig] in proj1_sig (sqrt_sig f). - -Definition sqrt_correct (f : fe1305) - : sqrt f = sqrt_3mod4_opt k_ c_ one_ f - := Eval cbv beta iota delta [proj2_sig sqrt_sig] in proj2_sig (sqrt_sig f). diff --git a/src/Specific/GF25519.v b/src/Specific/GF25519.v deleted file mode 100644 index 1a74de889..000000000 --- a/src/Specific/GF25519.v +++ /dev/null @@ -1,785 +0,0 @@ -Require Import Crypto.BaseSystem. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystem. -Require Import Crypto.ModularArithmetic.ModularBaseSystemProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystemOpt. -Require Import Crypto.Util.Tuple. -Require Import Coq.Lists.List Crypto.Util.ListUtil. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.Tactics.SetEvars. -Require Import Crypto.Util.Tactics.SubstEvars. -Require Import Crypto.Util.Tactics.DestructHead. -Require Import Crypto.Util.LetIn. -Require Import Crypto.Util.Tower. -Require Import Crypto.Util.Notations. -Require Import Crypto.Util.Decidable. -Require Import Crypto.Algebra. -Require Crypto.Spec.Ed25519. -Import ListNotations. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.ZArith.Znumtheory. -Local Open Scope Z. - -(* BEGIN precomputation. *) - -Definition modulus : positive := Eval compute in (2^255 - 19)%positive. -Definition prime_modulus : prime modulus := Crypto.Spec.Ed25519.prime_q. -Definition int_width := 64%Z. -Definition freeze_input_bound := 32%Z. - -Instance params25519 : PseudoMersenneBaseParams modulus. - construct_params prime_modulus 10%nat 255. -Defined. - -Definition length_fe25519 := Eval compute in length limb_widths. -Definition fe25519 := Eval compute in (tuple Z length_fe25519). - -Definition mul2modulus : fe25519 := - Eval compute in (from_list_default 0%Z (length limb_widths) (construct_mul2modulus params25519)). - -Instance subCoeff : SubtractionCoefficient. - apply Build_SubtractionCoefficient with (coeff := mul2modulus). - vm_decide. -Defined. - -Instance carryChain : CarryChain limb_widths. - apply Build_CarryChain with (carry_chain := (rev [0;1;2;3;4;5;6;7;8;9;0;1])%nat). - intros. - repeat (destruct H as [|H]; [subst; vm_compute; repeat constructor | ]). - contradiction H. -Defined. - -Definition freezePreconditions25519 : FreezePreconditions freeze_input_bound int_width. -Proof. - constructor; compute_preconditions. -Defined. - -(* Wire format for [pack] and [unpack] *) -Definition wire_widths := Eval compute in (repeat 32 7 ++ 31 :: nil). - -Definition wire_digits := Eval compute in (tuple Z (length wire_widths)). - -Lemma wire_widths_nonneg : forall w, In w wire_widths -> 0 <= w. -Proof. - intros. - repeat (destruct H as [|H]; [subst; vm_compute; congruence | ]). - contradiction H. -Qed. - -Lemma bits_eq : sum_firstn limb_widths (length limb_widths) = sum_firstn wire_widths (length wire_widths). -Proof. - reflexivity. -Qed. - -Lemma modulus_gt_2 : 2 < modulus. Proof. cbv; congruence. Qed. - -(* Temporarily, we'll use addition chains equivalent to double-and-add. This is pending - finding the real, more optimal chains from previous work. *) -Fixpoint pow2Chain'' p (pow2_index acc_index : nat) chain_acc : list (nat * nat) := - match p with - | xI p' => pow2Chain'' p' 1 0 - (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - | xO p' => pow2Chain'' p' 0 (S acc_index) - (chain_acc ++ (pow2_index, pow2_index)::nil) - | xH => (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - end. - -Fixpoint pow2Chain' p index := - match p with - | xI p' => pow2Chain'' p' 0 0 (repeat (0,0)%nat index) - | xO p' => pow2Chain' p' (S index) - | xH => repeat (0,0)%nat index - end. - -Definition pow2_chain p := - match p with - | xH => nil - | _ => pow2Chain' p 0 - end. - -(* From Daniel Bernstein's "ref" implementation (Public Domain) *) -Definition invChain := [(0, 0); (0, 0); (0, 0); (0, 3); (0, 3); (0, 0); (0, 2); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 5); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 10); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 20); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 42); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 50); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 100); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 202); (0, 0); (0, 0); (0, 0); (0, 0); (0, 0); (0, 259)]%nat. - -Instance inv_ec : ExponentiationChain (modulus - 2). - apply Build_ExponentiationChain with (chain := invChain); vm_decide_no_check. -Defined. - -(* Note : use caution copying square root code to other primes. The (modulus / 8 + 1) chains are - for primes that are 5 mod 8; if the prime is 3 mod 4 then use (modulus / 4 + 1). *) -Definition sqrtChain := Eval compute in pow2_chain (Z.to_pos (modulus / 8 + 1)). - -Instance sqrt_ec : ExponentiationChain (modulus / 8 + 1). - apply Build_ExponentiationChain with (chain := sqrtChain). - reflexivity. -Defined. - -Arguments chain {_ _ _} _. - -(* END precomputation *) - -(* Precompute constants *) -Definition k_ := Eval compute in k. -Definition k_subst : k = k_ := eq_refl k_. - -Definition c_ := Eval compute in c. -Definition c_subst : c = c_ := eq_refl c_. - -Definition one_ := Eval compute in one. -Definition one_subst : one = one_ := eq_refl one_. - -Definition zero_ := Eval compute in zero. -Definition zero_subst : zero = zero_ := eq_refl zero_. - -Definition modulus_digits_ := Eval compute in ModularBaseSystemList.modulus_digits. -Definition modulus_digits_subst : ModularBaseSystemList.modulus_digits = modulus_digits_ := eq_refl modulus_digits_. - -Local Opaque Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb Z.leb ModularBaseSystemListZOperations.neg ModularBaseSystemListZOperations.cmovl ModularBaseSystemListZOperations.cmovne. - -Definition app_7 {T} (f : wire_digits) (P : wire_digits -> T) : T. -Proof. - cbv [wire_digits] in *. - set (f0 := f). - repeat (let g := fresh "g" in destruct f as [f g]). - apply P. - apply f0. -Defined. - -Definition app_7_correct {T} f (P : wire_digits -> T) : app_7 f P = P f. -Proof. - intros. - cbv [wire_digits] in *. - repeat match goal with [p : (_*Z)%type |- _ ] => destruct p end. - reflexivity. -Qed. - -Definition app_10 {T} (f : fe25519) (P : fe25519 -> T) : T. -Proof. - cbv [fe25519] in *. - set (f0 := f). - repeat (let g := fresh "g" in destruct f as [f g]). - apply P. - apply f0. -Defined. - -Definition app_10_correct {T} f (P : fe25519 -> T) : app_10 f P = P f. -Proof. - intros. - cbv [fe25519] in *. - repeat match goal with [p : (_*Z)%type |- _ ] => destruct p end. - reflexivity. -Qed. - -Definition appify2 {T} (op : fe25519 -> fe25519 -> T) (f g : fe25519) := - app_10 f (fun f0 => (app_10 g (fun g0 => op f0 g0))). - -Lemma appify2_correct : forall {T} op f g, @appify2 T op f g = op f g. -Proof. - intros. cbv [appify2]. - etransitivity; apply app_10_correct. -Qed. - -Definition appify9 {T} (op : fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> T) (x0 x1 x2 x3 x4 x5 x6 x7 x8 : fe25519) := - app_10 x0 (fun x0' => - app_10 x1 (fun x1' => - app_10 x2 (fun x2' => - app_10 x3 (fun x3' => - app_10 x4 (fun x4' => - app_10 x5 (fun x5' => - app_10 x6 (fun x6' => - app_10 x7 (fun x7' => - app_10 x8 (fun x8' => - op x0' x1' x2' x3' x4' x5' x6' x7' x8'))))))))). - -Lemma appify9_correct : forall {T} op x0 x1 x2 x3 x4 x5 x6 x7 x8, - @appify9 T op x0 x1 x2 x3 x4 x5 x6 x7 x8 = op x0 x1 x2 x3 x4 x5 x6 x7 x8. -Proof. - intros. cbv [appify9]. - repeat (etransitivity; [ apply app_10_correct | ]); reflexivity. -Qed. - -Definition uncurry_unop_fe25519 {T} (op : fe25519 -> T) - := Eval compute in Tuple.uncurry (n:=length_fe25519) op. -Definition curry_unop_fe25519 {T} op : fe25519 -> T - := Eval compute in fun f => app_10 f (Tuple.curry (n:=length_fe25519) op). - -Fixpoint uncurry_n_op_fe25519 {T} n - : forall (op : Tower.tower_nd fe25519 T n), - Tower.tower_nd Z T (n * length_fe25519) - := match n - return (forall (op : Tower.tower_nd fe25519 T n), - Tower.tower_nd Z T (n * length_fe25519)) - with - | O => fun x => x - | S n' => fun f => uncurry_unop_fe25519 (fun x => @uncurry_n_op_fe25519 _ n' (f x)) - end. - -Definition uncurry_binop_fe25519 {T} (op : fe25519 -> fe25519 -> T) - := Eval compute in uncurry_n_op_fe25519 2 op. -Definition curry_binop_fe25519 {T} op : fe25519 -> fe25519 -> T - := Eval compute in appify2 (fun f => curry_unop_fe25519 (curry_unop_fe25519 op f)). - -Definition uncurry_unop_wire_digits {T} (op : wire_digits -> T) - := Eval compute in Tuple.uncurry (n:=length wire_widths) op. -Definition curry_unop_wire_digits {T} op : wire_digits -> T - := Eval compute in fun f => app_7 f (Tuple.curry (n:=length wire_widths) op). - -Definition uncurry_9op_fe25519 {T} (op : fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> T) - := Eval compute in uncurry_n_op_fe25519 9 op. -Definition curry_9op_fe25519 {T} op : fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> fe25519 -> T - := Eval compute in - appify9 (fun x0 x1 x2 x3 x4 x5 x6 x7 x8 - => curry_unop_fe25519 (curry_unop_fe25519 (curry_unop_fe25519 (curry_unop_fe25519 (curry_unop_fe25519 (curry_unop_fe25519 (curry_unop_fe25519 (curry_unop_fe25519 (curry_unop_fe25519 op x0) x1) x2) x3) x4) x5) x6) x7) x8). - -Definition add_sig (f g : fe25519) : - { fg : fe25519 | fg = add_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe25519). - cbv. - reflexivity. -Defined. - -Definition add (f g : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj1_sig (add_sig f g). - -Definition add_correct (f g : fe25519) - : add f g = add_opt f g := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj2_sig (add_sig f g). - -Definition carry_add_sig (f g : fe25519) : - { fg : fe25519 | fg = carry_add_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe25519). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. (* FIXME: The speed of this rewrite depends on the fact that we have 10 limbs; there are some lemmas in [zsimplify_Z_to_pos] which are specific to 10. *) - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition carry_add (f g : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig carry_add_sig] in - proj1_sig (carry_add_sig f g). - -Definition carry_add_correct (f g : fe25519) - : carry_add f g = carry_add_opt f g := - Eval cbv beta iota delta [proj1_sig carry_add_sig] in - proj2_sig (carry_add_sig f g). - -Definition sub_sig (f g : fe25519) : - { fg : fe25519 | fg = sub_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe25519). - cbv. - reflexivity. -Defined. - -Definition sub (f g : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj1_sig (sub_sig f g). - -Definition sub_correct (f g : fe25519) - : sub f g = sub_opt f g := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj2_sig (sub_sig f g). - -Definition carry_sub_sig (f g : fe25519) : - { fg : fe25519 | fg = carry_sub_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe25519). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. (* FIXME: The speed of this rewrite depends on the fact that we have 10 limbs; there are some lemmas in [zsimplify_Z_to_pos] which are specific to 10. *) - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition carry_sub (f g : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig carry_sub_sig] in - proj1_sig (carry_sub_sig f g). - -Definition carry_sub_correct (f g : fe25519) - : carry_sub f g = carry_sub_opt f g := - Eval cbv beta iota delta [proj1_sig carry_sub_sig] in - proj2_sig (carry_sub_sig f g). - -(* For multiplication, we add another layer of definition so that we can - rewrite under the [let] binders. *) -Definition mul_simpl_sig (f g : fe25519) : - { fg : fe25519 | fg = carry_mul_opt k_ c_ f g}. -Proof. - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv. (* N.B. The slow part of this is computing with [Z_div_opt]. - It would be much faster if we could take advantage of - the form of [base_from_limb_widths] when doing - division, so we could do subtraction instead. *) - autorewrite with zsimplify_fast. - reflexivity. -Defined. - -Definition mul_simpl (f g : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig mul_simpl_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) := f in - let '(g0, g1, g2, g3, g4, g5, g6, g7, g8, g9) := g in - proj1_sig (mul_simpl_sig (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) - (g0, g1, g2, g3, g4, g5, g6, g7, g8, g9)). - -Definition mul_simpl_correct (f g : fe25519) - : mul_simpl f g = carry_mul_opt k_ c_ f g. -Proof. - pose proof (proj2_sig (mul_simpl_sig f g)). - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition mul_sig (f g : fe25519) : - { fg : fe25519 | fg = carry_mul_opt k_ c_ f g}. -Proof. - eexists. - rewrite <-mul_simpl_correct. - rewrite <-(@appify2_correct fe25519). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. (* FIXME: The speed of this rewrite depends on the fact that we have 10 limbs; there are some lemmas in [zsimplify_Z_to_pos] which are specific to 10. *) - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition mul (f g : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig mul_sig] in - proj1_sig (mul_sig f g). - -Definition mul_correct (f g : fe25519) - : mul f g = carry_mul_opt k_ c_ f g := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj2_sig (mul_sig f g). - -Definition opp_sig (f : fe25519) : - { g : fe25519 | g = opp_opt f }. -Proof. - eexists. - cbv [opp_opt]. - rewrite <-sub_correct. - rewrite zero_subst. - cbv [sub]. - reflexivity. -Defined. - -Definition opp (f : fe25519) : fe25519 - := Eval cbv beta iota delta [proj1_sig opp_sig] in proj1_sig (opp_sig f). - -Definition opp_correct (f : fe25519) - : opp f = opp_opt f - := Eval cbv beta iota delta [proj2_sig add_sig] in proj2_sig (opp_sig f). - -Definition carry_opp_sig (f : fe25519) : - { g : fe25519 | g = carry_opp_opt f }. -Proof. - eexists. - cbv [carry_opp_opt]. - rewrite <-carry_sub_correct. - rewrite zero_subst. - cbv [carry_sub]. - reflexivity. -Defined. - -Definition carry_opp (f : fe25519) : fe25519 - := Eval cbv beta iota delta [proj1_sig carry_opp_sig] in proj1_sig (carry_opp_sig f). - -Definition carry_opp_correct (f : fe25519) - : carry_opp f = carry_opp_opt f - := Eval cbv beta iota delta [proj2_sig add_sig] in proj2_sig (carry_opp_sig f). - -Definition pow (f : fe25519) chain := fold_chain_opt one_ mul chain [f]. - -Lemma pow_correct (f : fe25519) : forall chain, pow f chain = pow_opt k_ c_ one_ f chain. -Proof. - cbv [pow pow_opt]; intros. - rewrite !fold_chain_opt_correct. - apply Proper_fold_chain; try reflexivity. - intros; subst; apply mul_correct. -Qed. - -(* Now that we have [pow], we can compute sqrt of -1 for use - in sqrt function (this is not needed unless the prime is - 5 mod 8) *) -Local Transparent Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb andb. - -Definition sqrt_m1 := Eval vm_compute in (pow (encode (F.of_Z _ 2)) (pow2_chain (Z.to_pos ((modulus - 1) / 4)))). - -Lemma sqrt_m1_correct : rep (mul sqrt_m1 sqrt_m1) (F.opp 1%F). -Proof. - cbv [rep]. - apply F.eq_to_Z_iff. - vm_compute. - reflexivity. -Qed. - -Local Opaque Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb andb. - -Definition inv_sig (f : fe25519) : - { g : fe25519 | g = inv_opt k_ c_ one_ f }. -Proof. - eexists; cbv [inv_opt]. - rewrite <-pow_correct. - cbv - [mul]. - reflexivity. -Defined. - -Definition inv (f : fe25519) : fe25519 - := Eval cbv beta iota delta [proj1_sig inv_sig] in proj1_sig (inv_sig f). - -Definition inv_correct (f : fe25519) - : inv f = inv_opt k_ c_ one_ f - := Eval cbv beta iota delta [proj2_sig inv_sig] in proj2_sig (inv_sig f). - -Definition mbs_field := modular_base_system_field modulus_gt_2. - -Import Morphisms. - -Local Existing Instance prime_modulus. - -Lemma field25519_and_homomorphisms - : @field fe25519 eq zero_ one_ opp add sub mul inv div - /\ @Ring.is_homomorphism - (F modulus) Logic.eq F.one F.add F.mul - fe25519 eq one_ add mul encode - /\ @Ring.is_homomorphism - fe25519 eq one_ add mul - (F modulus) Logic.eq F.one F.add F.mul - decode. -Proof. - eapply @Field.field_and_homomorphism_from_redundant_representation. - { exact (F.field_modulo _). } - { apply encode_rep. } - { reflexivity. } - { reflexivity. } - { reflexivity. } - { intros; rewrite opp_correct, opp_opt_correct; apply opp_rep; reflexivity. } - { intros; rewrite add_correct, add_opt_correct; apply add_rep; reflexivity. } - { intros; rewrite sub_correct, sub_opt_correct; apply sub_rep; reflexivity. } - { intros; rewrite mul_correct, carry_mul_opt_correct by reflexivity; apply carry_mul_rep; reflexivity. } - { intros; rewrite inv_correct, inv_opt_correct by reflexivity; apply inv_rep; reflexivity. } - { intros; apply encode_rep. } -Qed. - -Definition field25519 : @field fe25519 eq zero_ one_ opp add sub mul inv div := proj1 field25519_and_homomorphisms. - -Lemma carry_field25519_and_homomorphisms - : @field fe25519 eq zero_ one_ carry_opp carry_add carry_sub mul inv div - /\ @Ring.is_homomorphism - (F modulus) Logic.eq F.one F.add F.mul - fe25519 eq one_ carry_add mul encode - /\ @Ring.is_homomorphism - fe25519 eq one_ carry_add mul - (F modulus) Logic.eq F.one F.add F.mul - decode. -Proof. - eapply @Field.field_and_homomorphism_from_redundant_representation. - { exact (F.field_modulo _). } - { apply encode_rep. } - { reflexivity. } - { reflexivity. } - { reflexivity. } - { intros; rewrite carry_opp_correct, carry_opp_opt_correct, carry_opp_rep; apply opp_rep; reflexivity. } - { intros; rewrite carry_add_correct, carry_add_opt_correct, carry_add_rep; apply add_rep; reflexivity. } - { intros; rewrite carry_sub_correct, carry_sub_opt_correct, carry_sub_rep; apply sub_rep; reflexivity. } - { intros; rewrite mul_correct, carry_mul_opt_correct by reflexivity; apply carry_mul_rep; reflexivity. } - { intros; rewrite inv_correct, inv_opt_correct by reflexivity; apply inv_rep; reflexivity. } - { intros; apply encode_rep. } -Qed. - -Definition carry_field25519 : @field fe25519 eq zero_ one_ carry_opp carry_add carry_sub mul inv div := proj1 carry_field25519_and_homomorphisms. - -Lemma homomorphism_F25519_encode - : @Ring.is_homomorphism (F modulus) Logic.eq F.one F.add F.mul fe25519 eq one add mul encode. -Proof. apply field25519_and_homomorphisms. Qed. - -Lemma homomorphism_F25519_decode - : @Ring.is_homomorphism fe25519 eq one add mul (F modulus) Logic.eq F.one F.add F.mul decode. -Proof. apply field25519_and_homomorphisms. Qed. - - -Lemma homomorphism_carry_F25519_encode - : @Ring.is_homomorphism (F modulus) Logic.eq F.one F.add F.mul fe25519 eq one carry_add mul encode. -Proof. apply carry_field25519_and_homomorphisms. Qed. - -Lemma homomorphism_carry_F25519_decode - : @Ring.is_homomorphism fe25519 eq one carry_add mul (F modulus) Logic.eq F.one F.add F.mul decode. -Proof. apply carry_field25519_and_homomorphisms. Qed. - -Definition ge_modulus_sig (f : fe25519) : - { b : Z | b = ge_modulus_opt (to_list 10 f) }. -Proof. - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists; cbv [ge_modulus_opt]. - rewrite !modulus_digits_subst. - cbv. - reflexivity. -Defined. - -Definition ge_modulus (f : fe25519) : Z := - Eval cbv beta iota delta [proj1_sig ge_modulus_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) := f in - proj1_sig (ge_modulus_sig (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9)). - -Definition ge_modulus_correct (f : fe25519) : - ge_modulus f = ge_modulus_opt (to_list 10 f). -Proof. - pose proof (proj2_sig (ge_modulus_sig f)). - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition prefreeze_sig (f : fe25519) : - { f' : fe25519 | f' = from_list_default 0 10 (carry_full_3_opt c_ (to_list 10 f)) }. -Proof. - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv - [from_list_default]. - (* TODO(jgross,jadep): use Reflective linearization here? *) - repeat ( - set_evars; rewrite app_Let_In_nd; subst_evars; - eapply Proper_Let_In_nd_changebody; [reflexivity|intro]). - cbv [from_list_default from_list_default']. - reflexivity. -Defined. - -Definition prefreeze (f : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig prefreeze_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) := f in - proj1_sig (prefreeze_sig (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9)). - -Definition prefreeze_correct (f : fe25519) - : prefreeze f = from_list_default 0 10 (carry_full_3_opt c_ (to_list 10 f)). -Proof. - pose proof (proj2_sig (prefreeze_sig f)). - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition postfreeze_sig (f : fe25519) : - { f' : fe25519 | f' = from_list_default 0 10 (conditional_subtract_modulus_opt (int_width := int_width) (to_list 10 f)) }. -Proof. - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists; cbv [freeze_opt int_width]. - cbv [to_list to_list']. - cbv [conditional_subtract_modulus_opt]. - rewrite !modulus_digits_subst. - cbv - [from_list_default]. - (* TODO(jgross,jadep): use Reflective linearization here? *) - repeat ( - set_evars; rewrite app_Let_In_nd; subst_evars; - eapply Proper_Let_In_nd_changebody; [reflexivity|intro]). - cbv [from_list_default from_list_default']. - reflexivity. -Defined. - -Definition postfreeze (f : fe25519) : fe25519 := - Eval cbv beta iota delta [proj1_sig postfreeze_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) := f in - proj1_sig (postfreeze_sig (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9)). - -Definition postfreeze_correct (f : fe25519) - : postfreeze f = from_list_default 0 10 (conditional_subtract_modulus_opt (int_width := int_width) (to_list 10 f)). -Proof. - pose proof (proj2_sig (postfreeze_sig f)). - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition freeze (f : fe25519) : fe25519 := - dlet x := prefreeze f in - postfreeze x. - -Local Transparent Let_In. -Definition freeze_correct (f : fe25519) - : freeze f = from_list_default 0 10 (freeze_opt (int_width := int_width) c_ (to_list 10 f)). -Proof. - cbv [freeze_opt freeze Let_In]. - rewrite prefreeze_correct. - rewrite postfreeze_correct. - match goal with - |- appcontext [to_list _ (from_list_default _ ?n ?xs)] => - assert (length xs = n) as pf; [ | rewrite from_list_default_eq with (pf0 := pf) ] end. - { rewrite carry_full_3_opt_correct; repeat rewrite ModularBaseSystemListProofs.length_carry_full; auto using length_to_list. } - rewrite to_list_from_list. - reflexivity. -Qed. -Local Opaque Let_In. - -Definition fieldwiseb_sig (f g : fe25519) : - { b | b = @fieldwiseb Z Z 10 Z.eqb f g }. -Proof. - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv. - reflexivity. -Defined. - -Definition fieldwiseb (f g : fe25519) : bool - := Eval cbv beta iota delta [proj1_sig fieldwiseb_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) := f in - let '(g0, g1, g2, g3, g4, g5, g6, g7, g8, g9) := g in - proj1_sig (fieldwiseb_sig (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) - (g0, g1, g2, g3, g4, g5, g6, g7, g8, g9)). - -Lemma fieldwiseb_correct (f g : fe25519) - : fieldwiseb f g = @Tuple.fieldwiseb Z Z 10 Z.eqb f g. -Proof. - set (f' := f); set (g' := g). - hnf in f, g; destruct_head' prod. - exact (proj2_sig (fieldwiseb_sig f' g')). -Qed. - -Definition eqb_sig (f g : fe25519) : - { b | b = eqb int_width f g }. -Proof. - cbv [eqb]. - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [ModularBaseSystem.freeze int_width]. - rewrite <-!from_list_default_eq with (d := 0). - rewrite <-!(freeze_opt_correct c_) by auto using length_to_list. - rewrite <-!freeze_correct. - rewrite <-fieldwiseb_correct. - reflexivity. -Defined. - -Definition eqb (f g : fe25519) : bool - := Eval cbv beta iota delta [proj1_sig eqb_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) := f in - let '(g0, g1, g2, g3, g4, g5, g6, g7, g8, g9) := g in - proj1_sig (eqb_sig (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) - (g0, g1, g2, g3, g4, g5, g6, g7, g8, g9)). - -Lemma eqb_correct (f g : fe25519) - : eqb f g = ModularBaseSystem.eqb int_width f g. -Proof. - set (f' := f); set (g' := g). - hnf in f, g; destruct_head' prod. - exact (proj2_sig (eqb_sig f' g')). -Qed. - -Definition sqrt_sig (powf powf_squared f : fe25519) : - { f' : fe25519 | f' = sqrt_5mod8_opt (int_width := int_width) k_ c_ sqrt_m1 powf powf_squared f}. -Proof. - eexists. - cbv [sqrt_5mod8_opt int_width]. - apply Proper_Let_In_nd_changebody; [reflexivity|intro]. - set_evars. rewrite <-!mul_correct, <-eqb_correct. subst_evars. - reflexivity. -Defined. - -Definition sqrt (powf powf_squared f : fe25519) : fe25519 - := Eval cbv beta iota delta [proj1_sig sqrt_sig] in proj1_sig (sqrt_sig powf powf_squared f). - -Definition sqrt_correct (powf powf_squared f : fe25519) - : sqrt powf powf_squared f = sqrt_5mod8_opt k_ c_ sqrt_m1 powf powf_squared f - := Eval cbv beta iota delta [proj2_sig sqrt_sig] in proj2_sig (sqrt_sig powf powf_squared f). - -Definition pack_simpl_sig (f : fe25519) : - { f' | f' = pack_opt params25519 wire_widths_nonneg bits_eq f }. -Proof. - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [pack_opt]. - repeat (rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']). - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r. - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition pack_simpl (f : fe25519) := - Eval cbv beta iota delta [proj1_sig pack_simpl_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9) := f in - proj1_sig (pack_simpl_sig (f0, f1, f2, f3, f4, f5, f6, f7, f8, f9)). - -Definition pack_simpl_correct (f : fe25519) - : pack_simpl f = pack_opt params25519 wire_widths_nonneg bits_eq f. -Proof. - pose proof (proj2_sig (pack_simpl_sig f)). - cbv [fe25519] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition pack_sig (f : fe25519) : - { f' | f' = pack_opt params25519 wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-pack_simpl_correct. - rewrite <-(@app_10_correct wire_digits). - cbv. - reflexivity. -Defined. - -Definition pack (f : fe25519) : wire_digits := - Eval cbv beta iota delta [proj1_sig pack_sig] in proj1_sig (pack_sig f). - -Definition pack_correct (f : fe25519) - : pack f = pack_opt params25519 wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (pack_sig f). - -Definition unpack_simpl_sig (f : wire_digits) : - { f' | f' = unpack_opt params25519 wire_widths_nonneg bits_eq f }. -Proof. - cbv [wire_digits] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [unpack_opt]. - repeat ( - rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']). - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r. - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition unpack_simpl (f : wire_digits) : fe25519 := - Eval cbv beta iota delta [proj1_sig unpack_simpl_sig] in - let '(f0, f1, f2, f3, f4, f5, f6, f7) := f in - proj1_sig (unpack_simpl_sig (f0, f1, f2, f3, f4, f5, f6, f7)). - -Definition unpack_simpl_correct (f : wire_digits) - : unpack_simpl f = unpack_opt params25519 wire_widths_nonneg bits_eq f. -Proof. - pose proof (proj2_sig (unpack_simpl_sig f)). - cbv [wire_digits] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition unpack_sig (f : wire_digits) : - { f' | f' = unpack_opt params25519 wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-unpack_simpl_correct. - rewrite <-(@app_7_correct fe25519). - cbv. - reflexivity. -Defined. - -Definition unpack (f : wire_digits) : fe25519 := - Eval cbv beta iota delta [proj1_sig unpack_sig] in proj1_sig (unpack_sig f). - -Definition unpack_correct (f : wire_digits) - : unpack f = unpack_opt params25519 wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (unpack_sig f). diff --git a/src/Specific/IntegrationTestMul.v b/src/Specific/IntegrationTestMul.v index ccdbc7166..ec9120246 100644 --- a/src/Specific/IntegrationTestMul.v +++ b/src/Specific/IntegrationTestMul.v @@ -2,17 +2,16 @@ Require Import Coq.ZArith.ZArith. Require Import Coq.Lists.List. Local Open Scope Z_scope. -Require Import Crypto.Algebra. -Require Import Crypto.NewBaseSystem. +Require Import Crypto.Arithmetic.Core. Require Import Crypto.Util.FixedWordSizes. -Require Import Crypto.Specific.NewBaseSystemTest. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. +Require Import Crypto.Specific.ArithmeticSynthesisTest. +Require Import Crypto.Arithmetic.PrimeFieldTheorems. Require Import Crypto.Util.Tuple Crypto.Util.Sigma Crypto.Util.Sigma.MapProjections Crypto.Util.Sigma.Lift Crypto.Util.Notations Crypto.Util.ZRange Crypto.Util.BoundedWord. Require Import Crypto.Util.Tactics.Head. Require Import Crypto.Util.Tactics.MoveLetIn. Import ListNotations. -Require Import Crypto.Reflection.Z.Bounds.Pipeline. +Require Import Crypto.Compilers.Z.Bounds.Pipeline. Section BoundedField25p5. Local Coercion Z.of_nat : nat >-> Z. diff --git a/src/Specific/IntegrationTestSub.v b/src/Specific/IntegrationTestSub.v index aab923179..a3a1e8613 100644 --- a/src/Specific/IntegrationTestSub.v +++ b/src/Specific/IntegrationTestSub.v @@ -2,17 +2,16 @@ Require Import Coq.ZArith.ZArith. Require Import Coq.Lists.List. Local Open Scope Z_scope. -Require Import Crypto.Algebra. -Require Import Crypto.NewBaseSystem. +Require Import Crypto.Arithmetic.Core. Require Import Crypto.Util.FixedWordSizes. -Require Import Crypto.Specific.NewBaseSystemTest. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. +Require Import Crypto.Specific.ArithmeticSynthesisTest. +Require Import Crypto.Arithmetic.PrimeFieldTheorems. Require Import Crypto.Util.Tuple Crypto.Util.Sigma Crypto.Util.Sigma.MapProjections Crypto.Util.Sigma.Lift Crypto.Util.Notations Crypto.Util.ZRange Crypto.Util.BoundedWord. Require Import Crypto.Util.Tactics.Head. Require Import Crypto.Util.Tactics.MoveLetIn. Import ListNotations. -Require Import Crypto.Reflection.Z.Bounds.Pipeline. +Require Import Crypto.Compilers.Z.Bounds.Pipeline. Section BoundedField25p5. Local Coercion Z.of_nat : nat >-> Z. diff --git a/src/Specific/SC25519.v b/src/Specific/SC25519.v deleted file mode 100644 index eaf1f564a..000000000 --- a/src/Specific/SC25519.v +++ /dev/null @@ -1,171 +0,0 @@ -Require Import Coq.ZArith.ZArith Coq.micromega.Psatz Coq.Classes.Morphisms Coq.Classes.RelationClasses. -Require Import Crypto.Spec.Ed25519. -Require Import Crypto.EdDSARepChange. -Require Import Crypto.ModularArithmetic.BarrettReduction.ZBounded. -Require Import Crypto.ModularArithmetic.ZBoundedZ. -Require Import Crypto.Spec.ModularArithmetic. -Require Import Crypto.Util.Tuple. -Require Import Crypto.Util.LetIn. -Require Import Crypto.Util.Tactics.SpecializeBy. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.WordUtil. -Import NPeano. - -Local Notation modulusv := (2^252 + 27742317777372353535851937790883648493)%positive. -Local Coercion Z.of_nat : nat >-> Z. -Local Notation eta x := (fst x, snd x). -Local Notation eta3 x := (eta (fst x), snd x). -Local Notation eta4 x := (eta3 (fst x), snd x). -Local Notation eta4' x := (eta (fst x), eta (snd x)). -Local Open Scope Z_scope. - -Section Z. - Definition SRep := Z. (*tuple x86.W (256/n).*) - Definition SRepEq : Relation_Definitions.relation SRep := Logic.eq. - Local Instance SRepEquiv : RelationClasses.Equivalence SRepEq := _. - Local Notation base := 2%Z. - Local Notation kv := 256%Z. - Local Notation offsetv := 8%Z. - Lemma smaller_bound_smaller : (0 <= kv - offsetv <= 256)%Z. Proof. vm_compute; intuition congruence. Qed. - Lemma modulusv_in_range : 0 <= modulusv < 2 ^ 256. Proof. vm_compute; intuition congruence. Qed. - Lemma modulusv_pos : 0 < modulusv. Proof. vm_compute; reflexivity. Qed. - Section params_gen. - Import BarrettBundled. - Local Instance x86_25519_Barrett : BarrettParameters - := { m := modulusv; - b := base; - k := kv; - offset := offsetv; - ops := _; - μ' := base ^ (2 * kv) / modulusv }. - Local Instance x86_25519_BarrettProofs - : BarrettParametersCorrect x86_25519_Barrett - := { props := _ }. - Proof. - vm_compute; reflexivity. - vm_compute; reflexivity. - vm_compute; clear; abstract intuition congruence. - vm_compute; clear; abstract intuition congruence. - vm_compute; clear; abstract intuition congruence. - vm_compute; clear; abstract intuition congruence. - vm_compute; clear; abstract intuition congruence. - vm_compute; reflexivity. - Defined. - End params_gen. - Local Existing Instance x86_25519_Barrett. - Local Existing Instance x86_25519_BarrettProofs. - Declare Reduction srep := cbv [barrett_reduce_function_bundled barrett_reduce_function BarrettBundled.m BarrettBundled.b BarrettBundled.k BarrettBundled.offset BarrettBundled.μ' ZBounded.ConditionalSubtractModulus ZBounded.CarrySubSmall ZBounded.Mod_SmallBound ZBounded.Mod_SmallBound ZBounded.Mul ZBounded.DivBy_SmallBound ZBounded.DivBy_SmallerBound ZBounded.modulus_digits x86_25519_Barrett BarrettBundled.ops ZZLikeOps ZBounded.CarryAdd Z.pow2_mod]. - Definition SRepDecModL : Word.word (256 + 256) -> SRep - := Eval srep in - fun w => dlet w := (Z.of_N (Word.wordToN w)) in barrett_reduce_function_bundled w. - Definition S2Rep : ModularArithmetic.F.F l -> SRep := F.to_Z. - Local Ltac transitivity_refl x := transitivity x; [ | reflexivity ]. - Local Ltac pose_barrett_bounds H x := - pose proof (fun pf => proj1 (barrett_reduce_correct_bundled x pf)) as H; - unfold ZBounded.medium_valid, BarrettBundled.props, x86_25519_BarrettProofs, ZZLikeProperties, BarrettBundled.k in H; - simpl in H. - Local Ltac fold_modulusv := - let m := (eval vm_compute in modulusv) in - change m with modulusv in *. - Local Ltac fold_Z_pow_pos := - repeat match goal with - | [ |- context[Z.pow_pos ?b ?e] ] - => let e2 := (eval compute in (Z.pos e / 2)%Z) in - change (Z.pow_pos b e) with (b^(e2 + e2)) - end; - repeat simpl (Z.pos _ + Z.pos _) in *. - Local Ltac transitivity_barrett_bounds := - let LHS := match goal with |- ?R ?LHS ?RHS => LHS end in - let RHS := match goal with |- ?R ?LHS ?RHS => RHS end in - let H := fresh in - first [ match LHS with - | context[barrett_reduce_function_bundled ?x] - => etransitivity; [ pose_barrett_bounds H x | ] - end - | match RHS with - | context[barrett_reduce_function_bundled ?x] - => symmetry; etransitivity; [ pose_barrett_bounds H x | ] - end ]; - [ apply H; clear H | ]; - instantiate; - rewrite ?Z.pow2_mod_spec in * by omega; - fold_modulusv; fold_Z_pow_pos. - Lemma Z_of_nat_lt_helper x b e : (x < b^e)%nat <-> x < b^e. - Proof. rewrite Nat2Z.inj_lt, Z.pow_Zpow; reflexivity. Qed. - Lemma SRepDecModL_Correct : forall w : Word.word (b + b), SRepEq (S2Rep (ModularArithmetic.F.of_nat l (Word.wordToNat w))) (SRepDecModL w). - Proof. - intro w; unfold SRepEq, S2Rep, b in *. - pose proof (Word.wordToNat_bound w) as H'. - transitivity_refl (barrett_reduce_function_bundled (Z.of_N (Word.wordToN w))). - transitivity_barrett_bounds; - rewrite ?Word.wordToN_nat, ?nat_N_Z, ?WordUtil.pow2_id in *. - { apply Z_of_nat_lt_helper in H'. - rewrite Nat2Z.inj_add in H'. - auto with zarith. } - { reflexivity. } - Qed. - Definition SRepAdd : SRep -> SRep -> SRep - := Eval srep in - let work_around_bug_5198 - := fun x y => barrett_reduce_function_bundled (snd (ZBounded.CarryAdd x y)) - in work_around_bug_5198. - Lemma SRepAdd_Correct : forall x y : ModularArithmetic.F.F l, SRepEq (S2Rep (ModularArithmetic.F.add x y)) (SRepAdd (S2Rep x) (S2Rep y)). - Proof. - intros x y; unfold SRepEq, S2Rep, b in *; simpl. - transitivity_refl (let work_around_bug_5198 - := fun x y => barrett_reduce_function_bundled (snd (ZBounded.CarryAdd x y)) - in work_around_bug_5198 (F.to_Z x) (F.to_Z y)). - pose proof (ModularArithmeticTheorems.F.to_Z_range x). - pose proof (ModularArithmeticTheorems.F.to_Z_range y). - unfold l in *; specialize_by auto using modulusv_pos. - assert (F.to_Z x + F.to_Z y < 2 * modulusv - 1) by omega. - assert (2 * modulusv - 1 <= 2 ^ (kv + kv)) by (vm_compute; clear; intuition congruence). - assert (2 * modulusv - 1 < 2^((kv + offsetv) + (kv + offsetv))) by (vm_compute; clear; intuition congruence). - transitivity_barrett_bounds. - { Z.rewrite_mod_small; omega. } - { rewrite (Z.mod_small _ (base^_)) by zutil_arith. - reflexivity. } - Qed. - Global Instance SRepAdd_Proper : Proper (SRepEq ==> SRepEq ==> SRepEq) SRepAdd. - Proof. unfold SRepEq; repeat intro; subst; reflexivity. Qed. - Definition SRepMul : SRep -> SRep -> SRep - := Eval srep in - let work_around_bug_5198 - := fun x y => barrett_reduce_function_bundled (ZBounded.Mul x y) - in work_around_bug_5198. - Lemma SRepMul_Correct : forall x y : ModularArithmetic.F.F l, SRepEq (S2Rep (ModularArithmetic.F.mul x y)) (SRepMul (S2Rep x) (S2Rep y)). - Proof. - intros x y; unfold SRepEq, S2Rep, b in *; simpl. - transitivity_refl (let work_around_bug_5198 - := fun x y => barrett_reduce_function_bundled (ZBounded.Mul x y) - in work_around_bug_5198 (F.to_Z x) (F.to_Z y)). - pose proof (ModularArithmeticTheorems.F.to_Z_range x). - pose proof (ModularArithmeticTheorems.F.to_Z_range y). - unfold l in *; specialize_by auto using modulusv_pos. - assert (0 <= F.to_Z x * F.to_Z y < modulusv * modulusv) by nia. - assert (modulusv * modulusv <= 2 ^ (kv + kv)) by (vm_compute; clear; intuition congruence). - assert (2^(kv + kv) < 2^((kv + offsetv) + (kv + offsetv))) by (vm_compute; clear; intuition congruence). - transitivity_barrett_bounds. - { Z.rewrite_mod_small; omega. } - { reflexivity. } - Qed. - Global Instance SRepMul_Proper : Proper (SRepEq ==> SRepEq ==> SRepEq) SRepMul. - Proof. unfold SRepEq; repeat intro; subst; reflexivity. Qed. - Definition SRepDecModLShort : Word.word (n + 1) -> SRep - := Eval srep in - fun w => dlet w := (Z.of_N (Word.wordToN w)) in barrett_reduce_function_bundled w. - Lemma SRepDecModLShort_Correct : forall w : Word.word (n + 1), SRepEq (S2Rep (ModularArithmetic.F.of_nat l (Word.wordToNat w))) (SRepDecModLShort w). - Proof. - intros w; unfold SRepEq, S2Rep, n, b in *; simpl. - transitivity_refl (barrett_reduce_function_bundled (Z.of_N (Word.wordToN w))). - transitivity_barrett_bounds. - { pose proof (Word.wordToNat_bound w) as H. - rewrite Word.wordToN_nat, nat_N_Z. - rewrite WordUtil.pow2_id in H. - apply Z_of_nat_lt_helper in H. - rewrite Nat2Z.inj_add in H; simpl @Z.of_nat in *. - split; auto with zarith. - etransitivity; [ eassumption | instantiate; vm_compute; reflexivity ]. } - { rewrite Word.wordToN_nat, nat_N_Z; reflexivity. } - Qed. -End Z. diff --git a/src/SpecificGen/2213_32.json b/src/SpecificGen/2213_32.json deleted file mode 100644 index fe000da25..000000000 --- a/src/SpecificGen/2213_32.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "k" : 221, - "c" : 3, - "n" : 8, - "w" : 32, - "ch" : "[0;1;2;3;4;5;6;7;0;1]" -} diff --git a/src/SpecificGen/2519_32.json b/src/SpecificGen/2519_32.json deleted file mode 100644 index f2aabdb70..000000000 --- a/src/SpecificGen/2519_32.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "k" : 251, - "c" : 9, - "n" : 10, - "w" : 32, - "ch" : "[0;1;2;3;4;5;6;7;8;9;0;1]" -} diff --git a/src/SpecificGen/25519_32.json b/src/SpecificGen/25519_32.json deleted file mode 100644 index 383c03531..000000000 --- a/src/SpecificGen/25519_32.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "k" : 255, - "c" : 19, - "n" : 10, - "w" : 32, - "ch" : "[0;1;2;3;4;5;6;7;8;9;0;1]" -} diff --git a/src/SpecificGen/25519_64.json b/src/SpecificGen/25519_64.json deleted file mode 100644 index b4acfda31..000000000 --- a/src/SpecificGen/25519_64.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "k" : 255, - "c" : 19, - "n" : 5, - "w" : 64, - "ch" : "[0;1;2;3;4;0;1]" -} diff --git a/src/SpecificGen/41417_32.json b/src/SpecificGen/41417_32.json deleted file mode 100644 index 0a55e4c0b..000000000 --- a/src/SpecificGen/41417_32.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "k" : 414, - "c" : 17, - "n" : 18, - "w" : 32, - "ch" : "[0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;0;1]" -} diff --git a/src/SpecificGen/5211_32.json b/src/SpecificGen/5211_32.json deleted file mode 100644 index dc43b67b7..000000000 --- a/src/SpecificGen/5211_32.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "k" : 521, - "c" : 1, - "n" : 20, - "w" : 32, - "ch" : "[0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;0;1]" -} diff --git a/src/SpecificGen/GFtemplate3mod4 b/src/SpecificGen/GFtemplate3mod4 deleted file mode 100644 index b98067a9a..000000000 --- a/src/SpecificGen/GFtemplate3mod4 +++ /dev/null @@ -1,773 +0,0 @@ -Require Import Crypto.BaseSystem. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystem. -Require Import Crypto.ModularArithmetic.ModularBaseSystemProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystemOpt. -Require Import Coq.Lists.List Crypto.Util.ListUtil. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.Tuple. -(*Require Import Crypto.Util.Tactics.*) -Require Import Crypto.Util.LetIn. -Require Import Crypto.Util.Tower. -Require Import Crypto.Util.Notations. -Require Import Crypto.Util.Decidable. -Require Import Crypto.Algebra. -Import ListNotations. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.ZArith.Znumtheory. -Local Open Scope Z. - -(* BEGIN precomputation. *) - -Definition modulus : Z := Eval compute in 2^{{{k}}} - {{{c}}}. -Lemma prime_modulus : prime modulus. Admitted. -Definition int_width := Eval compute in (2 * {{{w}}})%Z. -Definition freeze_input_bound := {{{w}}}%Z. - -Instance params{{{k}}}{{{c}}}_{{{w}}} : PseudoMersenneBaseParams modulus. - construct_params prime_modulus {{{n}}}%nat {{{k}}}. -Defined. - -Definition length_fe{{{k}}}{{{c}}}_{{{w}}} := Eval compute in length limb_widths. -Definition fe{{{k}}}{{{c}}}_{{{w}}} := Eval compute in (tuple Z length_fe{{{k}}}{{{c}}}_{{{w}}}). - -Definition mul2modulus : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval compute in (from_list_default 0%Z (length limb_widths) (construct_mul2modulus params{{{k}}}{{{c}}}_{{{w}}})). - -Instance subCoeff : SubtractionCoefficient. - apply Build_SubtractionCoefficient with (coeff := mul2modulus). - vm_decide. -Defined. - -Instance carryChain : CarryChain limb_widths. - apply Build_CarryChain with (carry_chain := (rev {{{ch}}})%nat). - intros. - repeat (destruct H as [|H]; [subst; vm_compute; repeat constructor | ]). - contradiction H. -Defined. - -Definition freezePreconditions : FreezePreconditions freeze_input_bound int_width. -Proof. - constructor; compute_preconditions. -Defined. - -(* Wire format for [pack] and [unpack] *) -Definition wire_widths := Eval compute in (repeat {{{w}}} {{{kdivw}}} ++ {{{kmodw}}} :: nil). - -Definition wire_digits := Eval compute in (tuple Z (length wire_widths)). - -Lemma wire_widths_nonneg : forall w, In w wire_widths -> 0 <= w. -Proof. - intros. - repeat (destruct H as [|H]; [subst; vm_compute; congruence | ]). - contradiction H. -Qed. - -Lemma bits_eq : sum_firstn limb_widths (length limb_widths) = sum_firstn wire_widths (length wire_widths). -Proof. - reflexivity. -Qed. - -Lemma modulus_gt_2 : 2 < modulus. Proof. cbv; congruence. Qed. - -(* Temporarily, we'll use addition chains equivalent to double-and-add. This is pending - finding the real, more optimal chains from previous work. *) -Fixpoint pow2Chain'' p (pow2_index acc_index : nat) chain_acc : list (nat * nat) := - match p with - | xI p' => pow2Chain'' p' 1 0 - (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - | xO p' => pow2Chain'' p' 0 (S acc_index) - (chain_acc ++ (pow2_index, pow2_index)::nil) - | xH => (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - end. - -Fixpoint pow2Chain' p index := - match p with - | xI p' => pow2Chain'' p' 0 0 (repeat (0,0)%nat index) - | xO p' => pow2Chain' p' (S index) - | xH => repeat (0,0)%nat index - end. - -Definition pow2_chain p := - match p with - | xH => nil - | _ => pow2Chain' p 0 - end. - -Definition invChain := Eval compute in pow2_chain (Z.to_pos (modulus - 2)). - -Instance inv_ec : ExponentiationChain (modulus - 2). - apply Build_ExponentiationChain with (chain := invChain). - reflexivity. -Defined. - -(* Note : use caution copying square root code to other primes. The (modulus / 8 + 1) chains are - for primes that are 5 mod 8; if the prime is 3 mod 4 then use (modulus / 4 + 1). *) -Definition sqrtChain := Eval compute in pow2_chain (Z.to_pos (modulus / 4 + 1)). - -Instance sqrt_ec : ExponentiationChain (modulus / 4 + 1). - apply Build_ExponentiationChain with (chain := sqrtChain). - reflexivity. -Defined. - -Arguments chain {_ _ _} _. - -(* END precomputation *) - -(* Precompute constants *) -Definition k_ := Eval compute in k. -Definition k_subst : k = k_ := eq_refl k_. - -Definition c_ := Eval compute in c. -Definition c_subst : c = c_ := eq_refl c_. - -Definition one_ := Eval compute in one. -Definition one_subst : one = one_ := eq_refl one_. - -Definition zero_ := Eval compute in zero. -Definition zero_subst : zero = zero_ := eq_refl zero_. - -Definition modulus_digits_ := Eval compute in ModularBaseSystemList.modulus_digits. -Definition modulus_digits_subst : ModularBaseSystemList.modulus_digits = modulus_digits_ := eq_refl modulus_digits_. - -Local Opaque Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb Z.leb ModularBaseSystemListZOperations.neg ModularBaseSystemListZOperations.cmovl ModularBaseSystemListZOperations.cmovne. - -Definition app_n2 {T} (f : wire_digits) (P : wire_digits -> T) : T. -Proof. - cbv [wire_digits] in *. - set (f0 := f). - repeat (let g := fresh "g" in destruct f as [f g]). - apply P. - apply f0. -Defined. - -Definition app_n2_correct {T} f (P : wire_digits -> T) : app_n2 f P = P f. -Proof. - intros. - cbv [wire_digits] in *. - repeat match goal with [p : (_*Z)%type |- _ ] => destruct p end. - reflexivity. -Qed. - -Definition app_n {T} (f : fe{{{k}}}{{{c}}}_{{{w}}}) (P : fe{{{k}}}{{{c}}}_{{{w}}} -> T) : T. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - set (f0 := f). - repeat (let g := fresh "g" in destruct f as [f g]). - apply P. - apply f0. -Defined. - -Definition app_n_correct {T} f (P : fe{{{k}}}{{{c}}}_{{{w}}} -> T) : app_n f P = P f. -Proof. - intros. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with [p : (_*Z)%type |- _ ] => destruct p end. - reflexivity. -Qed. - -Definition appify2 {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) (f g : fe{{{k}}}{{{c}}}_{{{w}}}) := - app_n f (fun f0 => (app_n g (fun g0 => op f0 g0))). - -Lemma appify2_correct : forall {T} op f g, @appify2 T op f g = op f g. -Proof. - intros. cbv [appify2]. - etransitivity; apply app_n_correct. -Qed. - -Definition appify9 {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) (x0 x1 x2 x3 x4 x5 x6 x7 x8 : fe{{{k}}}{{{c}}}_{{{w}}}) := - app_n x0 (fun x0' => - app_n x1 (fun x1' => - app_n x2 (fun x2' => - app_n x3 (fun x3' => - app_n x4 (fun x4' => - app_n x5 (fun x5' => - app_n x6 (fun x6' => - app_n x7 (fun x7' => - app_n x8 (fun x8' => - op x0' x1' x2' x3' x4' x5' x6' x7' x8'))))))))). - -Lemma appify9_correct : forall {T} op x0 x1 x2 x3 x4 x5 x6 x7 x8, - @appify9 T op x0 x1 x2 x3 x4 x5 x6 x7 x8 = op x0 x1 x2 x3 x4 x5 x6 x7 x8. -Proof. - intros. cbv [appify9]. - repeat (etransitivity; [ apply app_n_correct | ]); reflexivity. -Qed. - -Definition uncurry_unop_fe{{{k}}}{{{c}}}_{{{w}}} {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> T) - := Eval compute in Tuple.uncurry (n:=length_fe{{{k}}}{{{c}}}_{{{w}}}) op. -Definition curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} {T} op : fe{{{k}}}{{{c}}}_{{{w}}} -> T - := Eval compute in fun f => app_n f (Tuple.curry (n:=length_fe{{{k}}}{{{c}}}_{{{w}}}) op). - -Fixpoint uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} {T} n - : forall (op : Tower.tower_nd fe{{{k}}}{{{c}}}_{{{w}}} T n), - Tower.tower_nd Z T (n * length_fe{{{k}}}{{{c}}}_{{{w}}}) - := match n - return (forall (op : Tower.tower_nd fe{{{k}}}{{{c}}}_{{{w}}} T n), - Tower.tower_nd Z T (n * length_fe{{{k}}}{{{c}}}_{{{w}}})) - with - | O => fun x => x - | S n' => fun f => uncurry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (fun x => @uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} _ n' (f x)) - end. - -Definition uncurry_binop_fe{{{k}}}{{{c}}}_{{{w}}} {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) - := Eval compute in uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} 2 op. -Definition curry_binop_fe{{{k}}}{{{c}}}_{{{w}}} {T} op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T - := Eval compute in appify2 (fun f => curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} op f)). - -Definition uncurry_unop_wire_digits {T} (op : wire_digits -> T) - := Eval compute in Tuple.uncurry (n:=length wire_widths) op. -Definition curry_unop_wire_digits {T} op : wire_digits -> T - := Eval compute in fun f => app_n2 f (Tuple.curry (n:=length wire_widths) op). - -Definition uncurry_9op_fe{{{k}}}{{{c}}}_{{{w}}} {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) - := Eval compute in uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} 9 op. -Definition curry_9op_fe{{{k}}}{{{c}}}_{{{w}}} {T} op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T - := Eval compute in - appify9 (fun x0 x1 x2 x3 x4 x5 x6 x7 x8 - => curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} op x0) x1) x2) x3) x4) x5) x6) x7) x8). - -Definition add_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = add_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - reflexivity. -Defined. - -Definition add (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj1_sig (add_sig f g). - -Definition add_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : add f g = add_opt f g := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj2_sig (add_sig f g). - -Definition carry_add_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_add_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition carry_add (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig carry_add_sig] in - proj1_sig (carry_add_sig f g). - -Definition carry_add_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : carry_add f g = carry_add_opt f g := - Eval cbv beta iota delta [proj1_sig carry_add_sig] in - proj2_sig (carry_add_sig f g). - -Definition sub_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = sub_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - reflexivity. -Defined. - -Definition sub (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj1_sig (sub_sig f g). - -Definition sub_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : sub f g = sub_opt f g := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj2_sig (sub_sig f g). - -Definition carry_sub_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_sub_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition carry_sub (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig carry_sub_sig] in - proj1_sig (carry_sub_sig f g). - -Definition carry_sub_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : carry_sub f g = carry_sub_opt f g := - Eval cbv beta iota delta [proj1_sig carry_sub_sig] in - proj2_sig (carry_sub_sig f g). - -(* For multiplication, we add another layer of definition so that we can - rewrite under the [let] binders. *) -Definition mul_simpl_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_mul_opt k_ c_ f g}. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv. (* N.B. The slow part of this is computing with [Z_div_opt]. - It would be much faster if we could take advantage of - the form of [base_from_limb_widths] when doing - division, so we could do subtraction instead. *) - autorewrite with zsimplify_fast. - reflexivity. -Defined. - -Definition mul_simpl (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig mul_simpl_sig] in - let '{{{enum f}}} := f in - let '{{{enum g}}} := g in - proj1_sig (mul_simpl_sig {{{enum f}}} - {{{enum g}}}). - -Definition mul_simpl_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : mul_simpl f g = carry_mul_opt k_ c_ f g. -Proof. - pose proof (proj2_sig (mul_simpl_sig f g)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition mul_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_mul_opt k_ c_ f g}. -Proof. - eexists. - rewrite <-mul_simpl_correct. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition mul (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig mul_sig] in - proj1_sig (mul_sig f g). - -Definition mul_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : mul f g = carry_mul_opt k_ c_ f g := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj2_sig (mul_sig f g). - -Definition opp_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { g : fe{{{k}}}{{{c}}}_{{{w}}} | g = opp_opt f }. -Proof. - eexists. - cbv [opp_opt]. - rewrite <-sub_correct. - rewrite zero_subst. - cbv [sub]. - reflexivity. -Defined. - -Definition opp (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig opp_sig] in proj1_sig (opp_sig f). - -Definition opp_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : opp f = opp_opt f - := Eval cbv beta iota delta [proj2_sig add_sig] in proj2_sig (opp_sig f). - -Definition carry_opp_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { g : fe{{{k}}}{{{c}}}_{{{w}}} | g = carry_opp_opt f }. -Proof. - eexists. - cbv [carry_opp_opt]. - rewrite <-carry_sub_correct. - rewrite zero_subst. - cbv [carry_sub]. - reflexivity. -Defined. - -Definition carry_opp (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig carry_opp_sig] in proj1_sig (carry_opp_sig f). - -Definition carry_opp_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : carry_opp f = carry_opp_opt f - := Eval cbv beta iota delta [proj2_sig add_sig] in proj2_sig (carry_opp_sig f). - -Definition pow (f : fe{{{k}}}{{{c}}}_{{{w}}}) chain := fold_chain_opt one_ mul chain [f]. - -Lemma pow_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) : forall chain, pow f chain = pow_opt k_ c_ one_ f chain. -Proof. - cbv [pow pow_opt]; intros. - rewrite !fold_chain_opt_correct. - apply Proper_fold_chain; try reflexivity. - intros; subst; apply mul_correct. -Qed. - -(* Now that we have [pow], we can compute sqrt of -1 for use - in sqrt function (this is not needed unless the prime is - 5 mod 8) *) -Local Transparent Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb andb. - -Definition sqrt_m1 := Eval vm_compute in (pow (encode (F.of_Z _ 2)) (pow2_chain (Z.to_pos ((modulus - 1) / 4)))). - -Local Opaque Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb andb. - -Definition inv_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { g : fe{{{k}}}{{{c}}}_{{{w}}} | g = inv_opt k_ c_ one_ f }. -Proof. - eexists; cbv [inv_opt]. - rewrite <-pow_correct. - cbv - [mul]. - reflexivity. -Defined. - -Definition inv (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig inv_sig] in proj1_sig (inv_sig f). - -Definition inv_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : inv f = inv_opt k_ c_ one_ f - := Eval cbv beta iota delta [proj2_sig inv_sig] in proj2_sig (inv_sig f). - -Definition mbs_field := modular_base_system_field modulus_gt_2. - -Import Morphisms. - -Local Existing Instance prime_modulus. - -Lemma field_and_homomorphisms - : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ opp add sub mul inv div - /\ @Ring.is_homomorphism - (F modulus) Logic.eq F.one F.add F.mul - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ add mul encode - /\ @Ring.is_homomorphism - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ add mul - (F modulus) Logic.eq F.one F.add F.mul - decode. -Proof. - eapply @Field.field_and_homomorphism_from_redundant_representation. - { exact (F.field_modulo _). } - { apply encode_rep. } - { reflexivity. } - { reflexivity. } - { reflexivity. } - { intros; rewrite opp_correct, opp_opt_correct; apply opp_rep; reflexivity. } - { intros; rewrite add_correct, add_opt_correct; apply add_rep; reflexivity. } - { intros; rewrite sub_correct, sub_opt_correct; apply sub_rep; reflexivity. } - { intros; rewrite mul_correct, carry_mul_opt_correct by reflexivity; apply carry_mul_rep; reflexivity. } - { intros; rewrite inv_correct, inv_opt_correct by reflexivity; apply inv_rep; reflexivity. } - { intros; apply encode_rep. } -Qed. - -Definition field{{{k}}}{{{c}}}_{{{w}}} : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ opp add sub mul inv div := proj1 field_and_homomorphisms. - -Lemma carry_field_and_homomorphisms - : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ carry_opp carry_add carry_sub mul inv div - /\ @Ring.is_homomorphism - (F modulus) Logic.eq F.one F.add F.mul - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ carry_add mul encode - /\ @Ring.is_homomorphism - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ carry_add mul - (F modulus) Logic.eq F.one F.add F.mul - decode. -Proof. - eapply @Field.field_and_homomorphism_from_redundant_representation. - { exact (F.field_modulo _). } - { apply encode_rep. } - { reflexivity. } - { reflexivity. } - { reflexivity. } - { intros; rewrite carry_opp_correct, carry_opp_opt_correct, carry_opp_rep; apply opp_rep; reflexivity. } - { intros; rewrite carry_add_correct, carry_add_opt_correct, carry_add_rep; apply add_rep; reflexivity. } - { intros; rewrite carry_sub_correct, carry_sub_opt_correct, carry_sub_rep; apply sub_rep; reflexivity. } - { intros; rewrite mul_correct, carry_mul_opt_correct by reflexivity; apply carry_mul_rep; reflexivity. } - { intros; rewrite inv_correct, inv_opt_correct by reflexivity; apply inv_rep; reflexivity. } - { intros; apply encode_rep. } -Qed. - -Definition carry_field{{{k}}}{{{c}}}_{{{w}}} : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ carry_opp carry_add carry_sub mul inv div := proj1 carry_field_and_homomorphisms. - -Lemma homomorphism_F{{{k}}}{{{c}}}_{{{w}}}_encode - : @Ring.is_homomorphism (F modulus) Logic.eq F.one F.add F.mul fe{{{k}}}{{{c}}}_{{{w}}} eq one add mul encode. -Proof. apply field_and_homomorphisms. Qed. - -Lemma homomorphism_F{{{k}}}{{{c}}}_{{{w}}}_decode - : @Ring.is_homomorphism fe{{{k}}}{{{c}}}_{{{w}}} eq one add mul (F modulus) Logic.eq F.one F.add F.mul decode. -Proof. apply field_and_homomorphisms. Qed. - - -Lemma homomorphism_carry_F{{{k}}}{{{c}}}_{{{w}}}_encode - : @Ring.is_homomorphism (F modulus) Logic.eq F.one F.add F.mul fe{{{k}}}{{{c}}}_{{{w}}} eq one carry_add mul encode. -Proof. apply carry_field_and_homomorphisms. Qed. - -Lemma homomorphism_carry_F{{{k}}}{{{c}}}_{{{w}}}_decode - : @Ring.is_homomorphism fe{{{k}}}{{{c}}}_{{{w}}} eq one carry_add mul (F modulus) Logic.eq F.one F.add F.mul decode. -Proof. apply carry_field_and_homomorphisms. Qed. - -Definition ge_modulus_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { b : Z | b = ge_modulus_opt (to_list {{{n}}} f) }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists; cbv [ge_modulus_opt]. - rewrite !modulus_digits_subst. - cbv. - reflexivity. -Defined. - -Definition ge_modulus (f : fe{{{k}}}{{{c}}}_{{{w}}}) : Z := - Eval cbv beta iota delta [proj1_sig ge_modulus_sig] in - let '{{{enum f}}} := f in - proj1_sig (ge_modulus_sig {{{enum f}}}). - -Definition ge_modulus_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - ge_modulus f = ge_modulus_opt (to_list {{{n}}} f). -Proof. - pose proof (proj2_sig (ge_modulus_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition prefreeze_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' : fe{{{k}}}{{{c}}}_{{{w}}} | f' = from_list_default 0 {{{n}}} (carry_full_3_opt c_ (to_list {{{n}}} f)) }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv - [from_list_default]. - (* TODO(jgross,jadep): use Reflective linearization here? *) - repeat ( - set_evars; rewrite app_Let_In_nd; subst_evars; - eapply Proper_Let_In_nd_changebody; [reflexivity|intro]). - cbv [from_list_default from_list_default']. - reflexivity. -Defined. - -Definition prefreeze (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig prefreeze_sig] in - let '{{{enum f}}} := f in - proj1_sig (prefreeze_sig {{{enum f}}}). - -Definition prefreeze_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : prefreeze f = from_list_default 0 {{{n}}} (carry_full_3_opt c_ (to_list {{{n}}} f)). -Proof. - pose proof (proj2_sig (prefreeze_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition postfreeze_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' : fe{{{k}}}{{{c}}}_{{{w}}} | f' = from_list_default 0 {{{n}}} (conditional_subtract_modulus_opt (int_width := int_width) (to_list {{{n}}} f)) }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists; cbv [freeze_opt int_width]. - cbv [to_list to_list']. - cbv [conditional_subtract_modulus_opt]. - rewrite !modulus_digits_subst. - cbv - [from_list_default]. - (* TODO(jgross,jadep): use Reflective linearization here? *) - repeat ( - set_evars; rewrite app_Let_In_nd; subst_evars; - eapply Proper_Let_In_nd_changebody; [reflexivity|intro]). - cbv [from_list_default from_list_default']. - reflexivity. -Defined. - -Definition postfreeze (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig postfreeze_sig] in - let '{{{enum f}}} := f in - proj1_sig (postfreeze_sig {{{enum f}}}). - -Definition postfreeze_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : postfreeze f = from_list_default 0 {{{n}}} (conditional_subtract_modulus_opt (int_width := int_width) (to_list {{{n}}} f)). -Proof. - pose proof (proj2_sig (postfreeze_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition freeze (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - dlet x := prefreeze f in - postfreeze x. - -Local Transparent Let_In. -Definition freeze_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : freeze f = from_list_default 0 {{{n}}} (freeze_opt (int_width := int_width) c_ (to_list {{{n}}} f)). -Proof. - cbv [freeze_opt freeze Let_In]. - rewrite prefreeze_correct. - rewrite postfreeze_correct. - match goal with - |- appcontext [to_list _ (from_list_default _ ?n ?xs)] => - assert (length xs = n) as pf; [ | rewrite from_list_default_eq with (pf0 := pf) ] end. - { rewrite carry_full_3_opt_correct; repeat rewrite ModularBaseSystemListProofs.length_carry_full; auto using length_to_list. } - rewrite to_list_from_list. - reflexivity. -Qed. -Local Opaque Let_In. - -Definition fieldwiseb_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { b | b = @fieldwiseb Z Z {{{n}}} Z.eqb f g }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv. - reflexivity. -Defined. - -Definition fieldwiseb (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : bool - := Eval cbv beta iota delta [proj1_sig fieldwiseb_sig] in - let '{{{enum f}}} := f in - let '{{{enum g}}} := g in - proj1_sig (fieldwiseb_sig {{{enum f}}} - {{{enum g}}}). - -Lemma fieldwiseb_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : fieldwiseb f g = @Tuple.fieldwiseb Z Z {{{n}}} Z.eqb f g. -Proof. - set (f' := f); set (g' := g). - hnf in f, g; destruct_head' prod. - exact (proj2_sig (fieldwiseb_sig f' g')). -Qed. - -Definition eqb_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { b | b = eqb int_width f g }. -Proof. - cbv [eqb]. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [ModularBaseSystem.freeze int_width]. - rewrite <-!from_list_default_eq with (d := 0). - rewrite <-!(freeze_opt_correct c_) by auto using length_to_list. - rewrite <-!freeze_correct. - rewrite <-fieldwiseb_correct. - reflexivity. -Defined. - -Definition eqb (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : bool - := Eval cbv beta iota delta [proj1_sig eqb_sig] in - let '{{{enum f}}} := f in - let '{{{enum g}}} := g in - proj1_sig (eqb_sig {{{enum f}}} - {{{enum g}}}). - -Lemma eqb_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : eqb f g = ModularBaseSystem.eqb int_width f g. -Proof. - set (f' := f); set (g' := g). - hnf in f, g; destruct_head' prod. - exact (proj2_sig (eqb_sig f' g')). -Qed. - -Definition sqrt_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' : fe{{{k}}}{{{c}}}_{{{w}}} | f' = sqrt_3mod4_opt k_ c_ one_ f}. -Proof. - eexists. - cbv [sqrt_3mod4_opt int_width]. - rewrite <- pow_correct. - reflexivity. -Defined. - -Definition sqrt (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig sqrt_sig] in proj1_sig (sqrt_sig f). - -Definition sqrt_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : sqrt f = sqrt_3mod4_opt k_ c_ one_ f - := Eval cbv beta iota delta [proj2_sig sqrt_sig] in proj2_sig (sqrt_sig f). - -Definition pack_simpl_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' | f' = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [pack_opt]. - repeat (rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']). - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r. - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition pack_simpl (f : fe{{{k}}}{{{c}}}_{{{w}}}) := - Eval cbv beta iota delta [proj1_sig pack_simpl_sig] in - let '{{{enum f}}} := f in - proj1_sig (pack_simpl_sig {{{enum f}}}). - -Definition pack_simpl_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : pack_simpl f = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f. -Proof. - pose proof (proj2_sig (pack_simpl_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition pack_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' | f' = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-pack_simpl_correct. - rewrite <-(@app_n_correct wire_digits). - cbv. - reflexivity. -Defined. - -Definition pack (f : fe{{{k}}}{{{c}}}_{{{w}}}) : wire_digits := - Eval cbv beta iota delta [proj1_sig pack_sig] in proj1_sig (pack_sig f). - -Definition pack_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : pack f = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (pack_sig f). - -Definition unpack_simpl_sig (f : wire_digits) : - { f' | f' = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - cbv [wire_digits] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [unpack_opt]. - repeat ( - rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']). - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r. - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition unpack_simpl (f : wire_digits) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig unpack_simpl_sig] in - let '{{{enumw f}}} := f in - proj1_sig (unpack_simpl_sig {{{enumw f}}}). - -Definition unpack_simpl_correct (f : wire_digits) - : unpack_simpl f = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f. -Proof. - pose proof (proj2_sig (unpack_simpl_sig f)). - cbv [wire_digits] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition unpack_sig (f : wire_digits) : - { f' | f' = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-unpack_simpl_correct. - rewrite <-(@app_n2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - reflexivity. -Defined. - -Definition unpack (f : wire_digits) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig unpack_sig] in proj1_sig (unpack_sig f). - -Definition unpack_correct (f : wire_digits) - : unpack f = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (unpack_sig f). diff --git a/src/SpecificGen/GFtemplate5mod8 b/src/SpecificGen/GFtemplate5mod8 deleted file mode 100644 index d6e8f32ad..000000000 --- a/src/SpecificGen/GFtemplate5mod8 +++ /dev/null @@ -1,782 +0,0 @@ -Require Import Crypto.BaseSystem. -Require Import Crypto.ModularArithmetic.PrimeFieldTheorems. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParams. -Require Import Crypto.ModularArithmetic.PseudoMersenneBaseParamProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystem. -Require Import Crypto.ModularArithmetic.ModularBaseSystemProofs. -Require Import Crypto.ModularArithmetic.ModularBaseSystemOpt. -Require Import Coq.Lists.List Crypto.Util.ListUtil. -Require Import Crypto.Tactics.VerdiTactics. -Require Import Crypto.Util.ZUtil. -Require Import Crypto.Util.Tuple. -(*Require Import Crypto.Util.Tactics.*) -Require Import Crypto.Util.LetIn. -Require Import Crypto.Util.Tower. -Require Import Crypto.Util.Notations. -Require Import Crypto.Util.Decidable. -Require Import Crypto.Algebra. -Import ListNotations. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zpower Coq.ZArith.ZArith Coq.ZArith.Znumtheory. -Local Open Scope Z. - -(* BEGIN precomputation. *) - -Definition modulus : Z := Eval compute in 2^{{{k}}} - {{{c}}}. -Lemma prime_modulus : prime modulus. Admitted. -Definition int_width := Eval compute in (2 * {{{w}}})%Z. -Definition freeze_input_bound := {{{w}}}%Z. - -Instance params{{{k}}}{{{c}}}_{{{w}}} : PseudoMersenneBaseParams modulus. - construct_params prime_modulus {{{n}}}%nat {{{k}}}. -Defined. - -Definition length_fe{{{k}}}{{{c}}}_{{{w}}} := Eval compute in length limb_widths. -Definition fe{{{k}}}{{{c}}}_{{{w}}} := Eval compute in (tuple Z length_fe{{{k}}}{{{c}}}_{{{w}}}). - -Definition mul2modulus : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval compute in (from_list_default 0%Z (length limb_widths) (construct_mul2modulus params{{{k}}}{{{c}}}_{{{w}}})). - -Instance subCoeff : SubtractionCoefficient. - apply Build_SubtractionCoefficient with (coeff := mul2modulus). - vm_decide. -Defined. - -Instance carryChain : CarryChain limb_widths. - apply Build_CarryChain with (carry_chain := (rev {{{ch}}})%nat). - intros. - repeat (destruct H as [|H]; [subst; vm_compute; repeat constructor | ]). - contradiction H. -Defined. - -Definition freezePreconditions : FreezePreconditions freeze_input_bound int_width. -Proof. - constructor; compute_preconditions. -Defined. - -(* Wire format for [pack] and [unpack] *) -Definition wire_widths := Eval compute in (repeat {{{w}}} {{{kdivw}}} ++ {{{kmodw}}} :: nil). - -Definition wire_digits := Eval compute in (tuple Z (length wire_widths)). - -Lemma wire_widths_nonneg : forall w, In w wire_widths -> 0 <= w. -Proof. - intros. - repeat (destruct H as [|H]; [subst; vm_compute; congruence | ]). - contradiction H. -Qed. - -Lemma bits_eq : sum_firstn limb_widths (length limb_widths) = sum_firstn wire_widths (length wire_widths). -Proof. - reflexivity. -Qed. - -Lemma modulus_gt_2 : 2 < modulus. Proof. cbv; congruence. Qed. - -(* Temporarily, we'll use addition chains equivalent to double-and-add. This is pending - finding the real, more optimal chains from previous work. *) -Fixpoint pow2Chain'' p (pow2_index acc_index : nat) chain_acc : list (nat * nat) := - match p with - | xI p' => pow2Chain'' p' 1 0 - (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - | xO p' => pow2Chain'' p' 0 (S acc_index) - (chain_acc ++ (pow2_index, pow2_index)::nil) - | xH => (chain_acc ++ (pow2_index, pow2_index) :: (0%nat, S acc_index) :: nil) - end. - -Fixpoint pow2Chain' p index := - match p with - | xI p' => pow2Chain'' p' 0 0 (repeat (0,0)%nat index) - | xO p' => pow2Chain' p' (S index) - | xH => repeat (0,0)%nat index - end. - -Definition pow2_chain p := - match p with - | xH => nil - | _ => pow2Chain' p 0 - end. - -Definition invChain := Eval compute in pow2_chain (Z.to_pos (modulus - 2)). - -Instance inv_ec : ExponentiationChain (modulus - 2). - apply Build_ExponentiationChain with (chain := invChain). - reflexivity. -Defined. - -(* Note : use caution copying square root code to other primes. The (modulus / 8 + 1) chains are - for primes that are 5 mod 8; if the prime is 3 mod 4 then use (modulus / 4 + 1). *) -Definition sqrtChain := Eval compute in pow2_chain (Z.to_pos (modulus / 8 + 1)). - -Instance sqrt_ec : ExponentiationChain (modulus / 8 + 1). - apply Build_ExponentiationChain with (chain := sqrtChain). - reflexivity. -Defined. - -Arguments chain {_ _ _} _. - -(* END precomputation *) - -(* Precompute constants *) -Definition k_ := Eval compute in k. -Definition k_subst : k = k_ := eq_refl k_. - -Definition c_ := Eval compute in c. -Definition c_subst : c = c_ := eq_refl c_. - -Definition one_ := Eval compute in one. -Definition one_subst : one = one_ := eq_refl one_. - -Definition zero_ := Eval compute in zero. -Definition zero_subst : zero = zero_ := eq_refl zero_. - -Definition modulus_digits_ := Eval compute in ModularBaseSystemList.modulus_digits. -Definition modulus_digits_subst : ModularBaseSystemList.modulus_digits = modulus_digits_ := eq_refl modulus_digits_. - -Local Opaque Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb Z.leb ModularBaseSystemListZOperations.neg ModularBaseSystemListZOperations.cmovl ModularBaseSystemListZOperations.cmovne. - -Definition app_n2 {T} (f : wire_digits) (P : wire_digits -> T) : T. -Proof. - cbv [wire_digits] in *. - set (f0 := f). - repeat (let g := fresh "g" in destruct f as [f g]). - apply P. - apply f0. -Defined. - -Definition app_n2_correct {T} f (P : wire_digits -> T) : app_n2 f P = P f. -Proof. - intros. - cbv [wire_digits] in *. - repeat match goal with [p : (_*Z)%type |- _ ] => destruct p end. - reflexivity. -Qed. - -Definition app_n {T} (f : fe{{{k}}}{{{c}}}_{{{w}}}) (P : fe{{{k}}}{{{c}}}_{{{w}}} -> T) : T. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - set (f0 := f). - repeat (let g := fresh "g" in destruct f as [f g]). - apply P. - apply f0. -Defined. - -Definition app_n_correct {T} f (P : fe{{{k}}}{{{c}}}_{{{w}}} -> T) : app_n f P = P f. -Proof. - intros. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with [p : (_*Z)%type |- _ ] => destruct p end. - reflexivity. -Qed. - -Definition appify2 {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) (f g : fe{{{k}}}{{{c}}}_{{{w}}}) := - app_n f (fun f0 => (app_n g (fun g0 => op f0 g0))). - -Lemma appify2_correct : forall {T} op f g, @appify2 T op f g = op f g. -Proof. - intros. cbv [appify2]. - etransitivity; apply app_n_correct. -Qed. - -Definition appify9 {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) (x0 x1 x2 x3 x4 x5 x6 x7 x8 : fe{{{k}}}{{{c}}}_{{{w}}}) := - app_n x0 (fun x0' => - app_n x1 (fun x1' => - app_n x2 (fun x2' => - app_n x3 (fun x3' => - app_n x4 (fun x4' => - app_n x5 (fun x5' => - app_n x6 (fun x6' => - app_n x7 (fun x7' => - app_n x8 (fun x8' => - op x0' x1' x2' x3' x4' x5' x6' x7' x8'))))))))). - -Lemma appify9_correct : forall {T} op x0 x1 x2 x3 x4 x5 x6 x7 x8, - @appify9 T op x0 x1 x2 x3 x4 x5 x6 x7 x8 = op x0 x1 x2 x3 x4 x5 x6 x7 x8. -Proof. - intros. cbv [appify9]. - repeat (etransitivity; [ apply app_n_correct | ]); reflexivity. -Qed. - -Definition uncurry_unop_fe{{{k}}}{{{c}}}_{{{w}}} {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> T) - := Eval compute in Tuple.uncurry (n:=length_fe{{{k}}}{{{c}}}_{{{w}}}) op. -Definition curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} {T} op : fe{{{k}}}{{{c}}}_{{{w}}} -> T - := Eval compute in fun f => app_n f (Tuple.curry (n:=length_fe{{{k}}}{{{c}}}_{{{w}}}) op). - -Fixpoint uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} {T} n - : forall (op : Tower.tower_nd fe{{{k}}}{{{c}}}_{{{w}}} T n), - Tower.tower_nd Z T (n * length_fe{{{k}}}{{{c}}}_{{{w}}}) - := match n - return (forall (op : Tower.tower_nd fe{{{k}}}{{{c}}}_{{{w}}} T n), - Tower.tower_nd Z T (n * length_fe{{{k}}}{{{c}}}_{{{w}}})) - with - | O => fun x => x - | S n' => fun f => uncurry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (fun x => @uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} _ n' (f x)) - end. - -Definition uncurry_binop_fe{{{k}}}{{{c}}}_{{{w}}} {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) - := Eval compute in uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} 2 op. -Definition curry_binop_fe{{{k}}}{{{c}}}_{{{w}}} {T} op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T - := Eval compute in appify2 (fun f => curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} op f)). - -Definition uncurry_unop_wire_digits {T} (op : wire_digits -> T) - := Eval compute in Tuple.uncurry (n:=length wire_widths) op. -Definition curry_unop_wire_digits {T} op : wire_digits -> T - := Eval compute in fun f => app_n2 f (Tuple.curry (n:=length wire_widths) op). - -Definition uncurry_9op_fe{{{k}}}{{{c}}}_{{{w}}} {T} (op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T) - := Eval compute in uncurry_n_op_fe{{{k}}}{{{c}}}_{{{w}}} 9 op. -Definition curry_9op_fe{{{k}}}{{{c}}}_{{{w}}} {T} op : fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> fe{{{k}}}{{{c}}}_{{{w}}} -> T - := Eval compute in - appify9 (fun x0 x1 x2 x3 x4 x5 x6 x7 x8 - => curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} (curry_unop_fe{{{k}}}{{{c}}}_{{{w}}} op x0) x1) x2) x3) x4) x5) x6) x7) x8). - -Definition add_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = add_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - reflexivity. -Defined. - -Definition add (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj1_sig (add_sig f g). - -Definition add_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : add f g = add_opt f g := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj2_sig (add_sig f g). - -Definition carry_add_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_add_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition carry_add (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig carry_add_sig] in - proj1_sig (carry_add_sig f g). - -Definition carry_add_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : carry_add f g = carry_add_opt f g := - Eval cbv beta iota delta [proj1_sig carry_add_sig] in - proj2_sig (carry_add_sig f g). - -Definition sub_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = sub_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - reflexivity. -Defined. - -Definition sub (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj1_sig (sub_sig f g). - -Definition sub_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : sub f g = sub_opt f g := - Eval cbv beta iota delta [proj1_sig sub_sig] in - proj2_sig (sub_sig f g). - -Definition carry_sub_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_sub_opt f g}. -Proof. - eexists. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition carry_sub (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig carry_sub_sig] in - proj1_sig (carry_sub_sig f g). - -Definition carry_sub_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : carry_sub f g = carry_sub_opt f g := - Eval cbv beta iota delta [proj1_sig carry_sub_sig] in - proj2_sig (carry_sub_sig f g). - -(* For multiplication, we add another layer of definition so that we can - rewrite under the [let] binders. *) -Definition mul_simpl_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_mul_opt k_ c_ f g}. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv. (* N.B. The slow part of this is computing with [Z_div_opt]. - It would be much faster if we could take advantage of - the form of [base_from_limb_widths] when doing - division, so we could do subtraction instead. *) - autorewrite with zsimplify_fast. - reflexivity. -Defined. - -Definition mul_simpl (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig mul_simpl_sig] in - let '{{{enum f}}} := f in - let '{{{enum g}}} := g in - proj1_sig (mul_simpl_sig {{{enum f}}} - {{{enum g}}}). - -Definition mul_simpl_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : mul_simpl f g = carry_mul_opt k_ c_ f g. -Proof. - pose proof (proj2_sig (mul_simpl_sig f g)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition mul_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { fg : fe{{{k}}}{{{c}}}_{{{w}}} | fg = carry_mul_opt k_ c_ f g}. -Proof. - eexists. - rewrite <-mul_simpl_correct. - rewrite <-(@appify2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - autorewrite with zsimplify_fast zsimplify_Z_to_pos; cbv. - autorewrite with zsimplify_Z_to_pos; cbv. - reflexivity. -Defined. - -Definition mul (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig mul_sig] in - proj1_sig (mul_sig f g). - -Definition mul_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : mul f g = carry_mul_opt k_ c_ f g := - Eval cbv beta iota delta [proj1_sig add_sig] in - proj2_sig (mul_sig f g). - -Definition opp_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { g : fe{{{k}}}{{{c}}}_{{{w}}} | g = opp_opt f }. -Proof. - eexists. - cbv [opp_opt]. - rewrite <-sub_correct. - rewrite zero_subst. - cbv [sub]. - reflexivity. -Defined. - -Definition opp (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig opp_sig] in proj1_sig (opp_sig f). - -Definition opp_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : opp f = opp_opt f - := Eval cbv beta iota delta [proj2_sig add_sig] in proj2_sig (opp_sig f). - -Definition carry_opp_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { g : fe{{{k}}}{{{c}}}_{{{w}}} | g = carry_opp_opt f }. -Proof. - eexists. - cbv [carry_opp_opt]. - rewrite <-carry_sub_correct. - rewrite zero_subst. - cbv [carry_sub]. - reflexivity. -Defined. - -Definition carry_opp (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig carry_opp_sig] in proj1_sig (carry_opp_sig f). - -Definition carry_opp_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : carry_opp f = carry_opp_opt f - := Eval cbv beta iota delta [proj2_sig add_sig] in proj2_sig (carry_opp_sig f). - -Definition pow (f : fe{{{k}}}{{{c}}}_{{{w}}}) chain := fold_chain_opt one_ mul chain [f]. - -Lemma pow_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) : forall chain, pow f chain = pow_opt k_ c_ one_ f chain. -Proof. - cbv [pow pow_opt]; intros. - rewrite !fold_chain_opt_correct. - apply Proper_fold_chain; try reflexivity. - intros; subst; apply mul_correct. -Qed. - -(* Now that we have [pow], we can compute sqrt of -1 for use - in sqrt function (this is not needed unless the prime is - 5 mod 8) *) -Local Transparent Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb andb. - -Definition sqrt_m1 := Eval vm_compute in (pow (encode (F.of_Z _ 2)) (pow2_chain (Z.to_pos ((modulus - 1) / 4)))). - -Lemma sqrt_m1_correct : rep (mul sqrt_m1 sqrt_m1) (F.opp 1%F). -Proof. - cbv [rep]. - apply F.eq_to_Z_iff. - vm_compute. - reflexivity. -Qed. - -Local Opaque Z.shiftr Z.shiftl Z.land Z.mul Z.add Z.sub Z.lor Let_In Z.eqb Z.ltb andb. - -Definition inv_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { g : fe{{{k}}}{{{c}}}_{{{w}}} | g = inv_opt k_ c_ one_ f }. -Proof. - eexists; cbv [inv_opt]. - rewrite <-pow_correct. - cbv - [mul]. - reflexivity. -Defined. - -Definition inv (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig inv_sig] in proj1_sig (inv_sig f). - -Definition inv_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : inv f = inv_opt k_ c_ one_ f - := Eval cbv beta iota delta [proj2_sig inv_sig] in proj2_sig (inv_sig f). - -Definition mbs_field := modular_base_system_field modulus_gt_2. - -Import Morphisms. - -Local Existing Instance prime_modulus. - -Lemma field_and_homomorphisms - : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ opp add sub mul inv div - /\ @Ring.is_homomorphism - (F modulus) Logic.eq F.one F.add F.mul - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ add mul encode - /\ @Ring.is_homomorphism - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ add mul - (F modulus) Logic.eq F.one F.add F.mul - decode. -Proof. - eapply @Field.field_and_homomorphism_from_redundant_representation. - { exact (F.field_modulo _). } - { apply encode_rep. } - { reflexivity. } - { reflexivity. } - { reflexivity. } - { intros; rewrite opp_correct, opp_opt_correct; apply opp_rep; reflexivity. } - { intros; rewrite add_correct, add_opt_correct; apply add_rep; reflexivity. } - { intros; rewrite sub_correct, sub_opt_correct; apply sub_rep; reflexivity. } - { intros; rewrite mul_correct, carry_mul_opt_correct by reflexivity; apply carry_mul_rep; reflexivity. } - { intros; rewrite inv_correct, inv_opt_correct by reflexivity; apply inv_rep; reflexivity. } - { intros; apply encode_rep. } -Qed. - -Definition field{{{k}}}{{{c}}}_{{{w}}} : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ opp add sub mul inv div := proj1 field_and_homomorphisms. - -Lemma carry_field_and_homomorphisms - : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ carry_opp carry_add carry_sub mul inv div - /\ @Ring.is_homomorphism - (F modulus) Logic.eq F.one F.add F.mul - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ carry_add mul encode - /\ @Ring.is_homomorphism - fe{{{k}}}{{{c}}}_{{{w}}} eq one_ carry_add mul - (F modulus) Logic.eq F.one F.add F.mul - decode. -Proof. - eapply @Field.field_and_homomorphism_from_redundant_representation. - { exact (F.field_modulo _). } - { apply encode_rep. } - { reflexivity. } - { reflexivity. } - { reflexivity. } - { intros; rewrite carry_opp_correct, carry_opp_opt_correct, carry_opp_rep; apply opp_rep; reflexivity. } - { intros; rewrite carry_add_correct, carry_add_opt_correct, carry_add_rep; apply add_rep; reflexivity. } - { intros; rewrite carry_sub_correct, carry_sub_opt_correct, carry_sub_rep; apply sub_rep; reflexivity. } - { intros; rewrite mul_correct, carry_mul_opt_correct by reflexivity; apply carry_mul_rep; reflexivity. } - { intros; rewrite inv_correct, inv_opt_correct by reflexivity; apply inv_rep; reflexivity. } - { intros; apply encode_rep. } -Qed. - -Definition carry_field{{{k}}}{{{c}}}_{{{w}}} : @field fe{{{k}}}{{{c}}}_{{{w}}} eq zero_ one_ carry_opp carry_add carry_sub mul inv div := proj1 carry_field_and_homomorphisms. - -Lemma homomorphism_F{{{k}}}{{{c}}}_{{{w}}}_encode - : @Ring.is_homomorphism (F modulus) Logic.eq F.one F.add F.mul fe{{{k}}}{{{c}}}_{{{w}}} eq one add mul encode. -Proof. apply field_and_homomorphisms. Qed. - -Lemma homomorphism_F{{{k}}}{{{c}}}_{{{w}}}_decode - : @Ring.is_homomorphism fe{{{k}}}{{{c}}}_{{{w}}} eq one add mul (F modulus) Logic.eq F.one F.add F.mul decode. -Proof. apply field_and_homomorphisms. Qed. - - -Lemma homomorphism_carry_F{{{k}}}{{{c}}}_{{{w}}}_encode - : @Ring.is_homomorphism (F modulus) Logic.eq F.one F.add F.mul fe{{{k}}}{{{c}}}_{{{w}}} eq one carry_add mul encode. -Proof. apply carry_field_and_homomorphisms. Qed. - -Lemma homomorphism_carry_F{{{k}}}{{{c}}}_{{{w}}}_decode - : @Ring.is_homomorphism fe{{{k}}}{{{c}}}_{{{w}}} eq one carry_add mul (F modulus) Logic.eq F.one F.add F.mul decode. -Proof. apply carry_field_and_homomorphisms. Qed. - -Definition ge_modulus_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { b : Z | b = ge_modulus_opt (to_list {{{n}}} f) }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists; cbv [ge_modulus_opt]. - rewrite !modulus_digits_subst. - cbv. - reflexivity. -Defined. - -Definition ge_modulus (f : fe{{{k}}}{{{c}}}_{{{w}}}) : Z := - Eval cbv beta iota delta [proj1_sig ge_modulus_sig] in - let '{{{enum f}}} := f in - proj1_sig (ge_modulus_sig {{{enum f}}}). - -Definition ge_modulus_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - ge_modulus f = ge_modulus_opt (to_list {{{n}}} f). -Proof. - pose proof (proj2_sig (ge_modulus_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition prefreeze_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' : fe{{{k}}}{{{c}}}_{{{w}}} | f' = from_list_default 0 {{{n}}} (carry_full_3_opt c_ (to_list {{{n}}} f)) }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv - [from_list_default]. - (* TODO(jgross,jadep): use Reflective linearization here? *) - repeat ( - set_evars; rewrite app_Let_In_nd; subst_evars; - eapply Proper_Let_In_nd_changebody; [reflexivity|intro]). - cbv [from_list_default from_list_default']. - reflexivity. -Defined. - -Definition prefreeze (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig prefreeze_sig] in - let '{{{enum f}}} := f in - proj1_sig (prefreeze_sig {{{enum f}}}). - -Definition prefreeze_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : prefreeze f = from_list_default 0 {{{n}}} (carry_full_3_opt c_ (to_list {{{n}}} f)). -Proof. - pose proof (proj2_sig (prefreeze_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition postfreeze_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' : fe{{{k}}}{{{c}}}_{{{w}}} | f' = from_list_default 0 {{{n}}} (conditional_subtract_modulus_opt (int_width := int_width) (to_list {{{n}}} f)) }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists; cbv [freeze_opt int_width]. - cbv [to_list to_list']. - cbv [conditional_subtract_modulus_opt]. - rewrite !modulus_digits_subst. - cbv - [from_list_default]. - (* TODO(jgross,jadep): use Reflective linearization here? *) - repeat ( - set_evars; rewrite app_Let_In_nd; subst_evars; - eapply Proper_Let_In_nd_changebody; [reflexivity|intro]). - cbv [from_list_default from_list_default']. - reflexivity. -Defined. - -Definition postfreeze (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig postfreeze_sig] in - let '{{{enum f}}} := f in - proj1_sig (postfreeze_sig {{{enum f}}}). - -Definition postfreeze_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : postfreeze f = from_list_default 0 {{{n}}} (conditional_subtract_modulus_opt (int_width := int_width) (to_list {{{n}}} f)). -Proof. - pose proof (proj2_sig (postfreeze_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Defined. - -Definition freeze (f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} := - dlet x := prefreeze f in - postfreeze x. - -Local Transparent Let_In. -Definition freeze_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : freeze f = from_list_default 0 {{{n}}} (freeze_opt (int_width := int_width) c_ (to_list {{{n}}} f)). -Proof. - cbv [freeze_opt freeze Let_In]. - rewrite prefreeze_correct. - rewrite postfreeze_correct. - match goal with - |- appcontext [to_list _ (from_list_default _ ?n ?xs)] => - assert (length xs = n) as pf; [ | rewrite from_list_default_eq with (pf0 := pf) ] end. - { rewrite carry_full_3_opt_correct; repeat rewrite ModularBaseSystemListProofs.length_carry_full; auto using length_to_list. } - rewrite to_list_from_list. - reflexivity. -Qed. -Local Opaque Let_In. - -Definition fieldwiseb_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { b | b = @fieldwiseb Z Z {{{n}}} Z.eqb f g }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv. - reflexivity. -Defined. - -Definition fieldwiseb (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : bool - := Eval cbv beta iota delta [proj1_sig fieldwiseb_sig] in - let '{{{enum f}}} := f in - let '{{{enum g}}} := g in - proj1_sig (fieldwiseb_sig {{{enum f}}} - {{{enum g}}}). - -Lemma fieldwiseb_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : fieldwiseb f g = @Tuple.fieldwiseb Z Z {{{n}}} Z.eqb f g. -Proof. - set (f' := f); set (g' := g). - hnf in f, g; destruct_head' prod. - exact (proj2_sig (fieldwiseb_sig f' g')). -Qed. - -Definition eqb_sig (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : - { b | b = eqb int_width f g }. -Proof. - cbv [eqb]. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [ModularBaseSystem.freeze int_width]. - rewrite <-!from_list_default_eq with (d := 0). - rewrite <-!(freeze_opt_correct c_) by auto using length_to_list. - rewrite <-!freeze_correct. - rewrite <-fieldwiseb_correct. - reflexivity. -Defined. - -Definition eqb (f g : fe{{{k}}}{{{c}}}_{{{w}}}) : bool - := Eval cbv beta iota delta [proj1_sig eqb_sig] in - let '{{{enum f}}} := f in - let '{{{enum g}}} := g in - proj1_sig (eqb_sig {{{enum f}}} - {{{enum g}}}). - -Lemma eqb_correct (f g : fe{{{k}}}{{{c}}}_{{{w}}}) - : eqb f g = ModularBaseSystem.eqb int_width f g. -Proof. - set (f' := f); set (g' := g). - hnf in f, g; destruct_head' prod. - exact (proj2_sig (eqb_sig f' g')). -Qed. - -Definition sqrt_sig (powx powx_squared f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' : fe{{{k}}}{{{c}}}_{{{w}}} | f' = sqrt_5mod8_opt (int_width := int_width) k_ c_ sqrt_m1 powx powx_squared f}. -Proof. - eexists. - cbv [sqrt_5mod8_opt int_width]. - apply Proper_Let_In_nd_changebody; [reflexivity|intro]. - set_evars. rewrite <-!mul_correct, <-eqb_correct. subst_evars. - reflexivity. -Defined. - -Definition sqrt (powx powx_squared f : fe{{{k}}}{{{c}}}_{{{w}}}) : fe{{{k}}}{{{c}}}_{{{w}}} - := Eval cbv beta iota delta [proj1_sig sqrt_sig] in proj1_sig (sqrt_sig powx powx_squared f). - -Definition sqrt_correct (powx powx_squared f : fe{{{k}}}{{{c}}}_{{{w}}}) - : sqrt powx powx_squared f = sqrt_5mod8_opt k_ c_ sqrt_m1 powx powx_squared f - := Eval cbv beta iota delta [proj2_sig sqrt_sig] in proj2_sig (sqrt_sig powx powx_squared f). - -Definition pack_simpl_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' | f' = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [pack_opt]. - repeat (rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']). - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r. - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition pack_simpl (f : fe{{{k}}}{{{c}}}_{{{w}}}) := - Eval cbv beta iota delta [proj1_sig pack_simpl_sig] in - let '{{{enum f}}} := f in - proj1_sig (pack_simpl_sig {{{enum f}}}). - -Definition pack_simpl_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : pack_simpl f = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f. -Proof. - pose proof (proj2_sig (pack_simpl_sig f)). - cbv [fe{{{k}}}{{{c}}}_{{{w}}}] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition pack_sig (f : fe{{{k}}}{{{c}}}_{{{w}}}) : - { f' | f' = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-pack_simpl_correct. - rewrite <-(@app_n_correct wire_digits). - cbv. - reflexivity. -Defined. - -Definition pack (f : fe{{{k}}}{{{c}}}_{{{w}}}) : wire_digits := - Eval cbv beta iota delta [proj1_sig pack_sig] in proj1_sig (pack_sig f). - -Definition pack_correct (f : fe{{{k}}}{{{c}}}_{{{w}}}) - : pack f = pack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (pack_sig f). - -Definition unpack_simpl_sig (f : wire_digits) : - { f' | f' = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - cbv [wire_digits] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - eexists. - cbv [unpack_opt]. - repeat ( - rewrite <-convert'_opt_correct; - cbv - [from_list_default_opt Conversion.convert']). - repeat progress rewrite ?Z.shiftl_0_r, ?Z.shiftr_0_r, ?Z.land_0_l, ?Z.lor_0_l, ?Z.land_same_r. - cbv [from_list_default_opt]. - reflexivity. -Defined. - -Definition unpack_simpl (f : wire_digits) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig unpack_simpl_sig] in - let '{{{enumw f}}} := f in - proj1_sig (unpack_simpl_sig {{{enumw f}}}). - -Definition unpack_simpl_correct (f : wire_digits) - : unpack_simpl f = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f. -Proof. - pose proof (proj2_sig (unpack_simpl_sig f)). - cbv [wire_digits] in *. - repeat match goal with p : (_ * Z)%type |- _ => destruct p end. - assumption. -Qed. - -Definition unpack_sig (f : wire_digits) : - { f' | f' = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f }. -Proof. - eexists. - rewrite <-unpack_simpl_correct. - rewrite <-(@app_n2_correct fe{{{k}}}{{{c}}}_{{{w}}}). - cbv. - reflexivity. -Defined. - -Definition unpack (f : wire_digits) : fe{{{k}}}{{{c}}}_{{{w}}} := - Eval cbv beta iota delta [proj1_sig unpack_sig] in proj1_sig (unpack_sig f). - -Definition unpack_correct (f : wire_digits) - : unpack f = unpack_opt params{{{k}}}{{{c}}}_{{{w}}} wire_widths_nonneg bits_eq f - := Eval cbv beta iota delta [proj2_sig pack_sig] in proj2_sig (unpack_sig f). diff --git a/src/SpecificGen/README.md b/src/SpecificGen/README.md deleted file mode 100644 index 165e755d5..000000000 --- a/src/SpecificGen/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Usage: - -python fill_template.py 41417_32.json - -(overwrites GF41417_32.v) diff --git a/src/SpecificGen/copy_bounds.sh b/src/SpecificGen/copy_bounds.sh deleted file mode 100755 index bb43e1aaa..000000000 --- a/src/SpecificGen/copy_bounds.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -cd "$DIR" - -FILENAME="$1" -V_FILE_STEM="${FILENAME%.*}" -BIT_WIDTH=64 -case "$V_FILE_STEM" in - *_64) BIT_WIDTH=128;; -esac - -if [ -z "$V_FILE_STEM" ]; then - echo "USAGE: $0 JSON_FILE" - exit 1 -fi - -for ORIG in $(git ls-files "../Specific/**GF25519*.v" | grep -v "../Specific/GF25519.v"); do - NEW="$(echo "$ORIG" | sed s'|^../Specific|.|g' | sed s"|25519|${V_FILE_STEM}|g")" - echo "$NEW" - NEW_DIR="$(dirname "$NEW")" - mkdir -p "$NEW_DIR" || exit $? - cat "$ORIG" | sed s"/64/${BIT_WIDTH}/g" | sed s'/Specific/SpecificGen/g' | sed s"/25519/${V_FILE_STEM}/g" > "$NEW" || exit $? - if [ -z "$(git ls-files "$NEW")" ]; then - echo "git add '$NEW'" - git add "$NEW" || exit $? - fi -done diff --git a/src/SpecificGen/fill_template.py b/src/SpecificGen/fill_template.py deleted file mode 100644 index 172ec1079..000000000 --- a/src/SpecificGen/fill_template.py +++ /dev/null @@ -1,39 +0,0 @@ -import os, sys, json - -enum = lambda n, s : "(" + ", ".join([s + str(x) for x in range(n)]) + ")" - -params = open(sys.argv[1]) -replacements = json.load(params) -params.close() -replacements["kmodw"] = replacements["k"] % replacements["w"] -replacements["kdivw"] = int(replacements["k"] / replacements["w"]) -replacements["enum f"] = enum(replacements["n"], "f") -replacements["enum g"] = enum(replacements["n"], "g") -replacements["enumw f"] = enum(replacements["kdivw"] + 1, "f") -replacements = {k : str(v) for k,v in replacements.items()} - -OUT = "GF" + replacements["k"] + replacements["c"] + "_" + replacements["w"] + ".v" - -if len(sys.argv) > 2: - OUT = sys.argv[2] - -if int(replacements["c"]) % 8 == 1: - TEMPLATE = "GFtemplate3mod4" -else: - TEMPLATE = "GFtemplate5mod8" - -BEGIN_FIELD = "{{{" -END_FIELD = "}}}" -field = lambda s : BEGIN_FIELD + s + END_FIELD - -inp = open(TEMPLATE) -out = open(OUT, "w+") - -for line in inp: - new_line = line - for w in replacements: - new_line = new_line.replace(field(w), replacements[w]) - out.write(new_line) - -inp.close() -out.close() diff --git a/src/Testbit.v b/src/Testbit.v deleted file mode 100644 index 1da2c33e0..000000000 --- a/src/Testbit.v +++ /dev/null @@ -1,81 +0,0 @@ -Require Import Coq.Lists.List. -Require Import Crypto.Util.ListUtil Crypto.Util.ZUtil Crypto.Util.NatUtil. -Require Import Crypto.BaseSystem Crypto.BaseSystemProofs. -Require Import Crypto.ModularArithmetic.Pow2Base Crypto.ModularArithmetic.Pow2BaseProofs. -Require Import Coq.ZArith.ZArith Coq.ZArith.Zdiv. -Require Import Coq.omega.Omega Coq.Numbers.Natural.Peano.NPeano. -Require Import Coq.micromega.Psatz. -Require Import Crypto.Util.Tactics.UniquePose. -Require Coq.Arith.Arith. -Import Nat. -Local Open Scope Z. - -Section Testbit. - Context {width : Z} (limb_width_pos : 0 < width). - Context (limb_widths : list Z) (limb_widths_nonnil : limb_widths <> nil) - (limb_widths_uniform : forall w, In w limb_widths -> w = width). - Local Notation base := (base_from_limb_widths limb_widths). - - Definition testbit (us : list Z) (n : nat) := - Z.testbit (nth_default 0 us (n / (Z.to_nat width))) (Z.of_nat (n mod Z.to_nat width)%nat). - - Ltac zify_nat_hyp := - repeat match goal with - | H : ~ (_ < _)%nat |- _ => rewrite nlt_ge in H - | H : ~ (_ <= _)%nat |- _ => rewrite nle_gt in H - | H : ~ (_ > _)%nat |- _ => apply not_gt in H - | H : ~ (_ >= _)%nat |- _ => apply not_ge in H - | H : (_ < _)%nat |- _ => unique pose proof (proj1 (Nat2Z.inj_lt _ _) H) - | H : (_ <= _)%nat |- _ => unique pose proof (proj1 (Nat2Z.inj_le _ _) H) - | H : (_ > _)%nat |- _ => unique pose proof (proj1 (Nat2Z.inj_gt _ _) H) - | H : (_ >= _)%nat |- _ => unique pose proof (proj1 (Nat2Z.inj_ge _ _) H) - | H : ~ (_ = _ :> nat) |- _ => unique pose proof (fun x => H (Nat2Z.inj _ _ x)) - | H : (_ = _ :> nat) |- _ => unique pose proof (proj2 (Nat2Z.inj_iff _ _) H) - end. - - Lemma testbit_spec' : forall a b us, (0 <= b < width) -> - bounded limb_widths us -> (length us = length limb_widths)%nat -> - Z.testbit (nth_default 0 us a) b = Z.testbit (decode base us) (Z.of_nat a * width + b). - Proof using limb_width_pos limb_widths_uniform. - repeat match goal with - | |- _ => progress intros - | |- _ => progress autorewrite with push_nth_default Ztestbit zsimplify in * - | |- _ => progress change (Z.of_nat 0) with 0 in * - | [ H : In ?x ?ls, H' : forall x', In x' ?ls -> x' = _ |- _ ] - => is_var x; apply H' in H - | |- _ => rewrite Nat2Z.inj_succ, Z.mul_succ_l - | |- _ => rewrite nth_default_out_of_bounds by omega - | |- _ => rewrite nth_default_uniform_base by omega - | |- false = Z.testbit (decode _ _) _ => rewrite testbit_decode_high - | |- _ => rewrite (@sum_firstn_uniform_base width) by (eassumption || omega) - | |- _ => rewrite sum_firstn_succ_default - | |- Z.testbit (nth_default _ _ ?x) _ = Z.testbit (decode _ _) _ => - destruct (lt_dec x (length limb_widths)); - [ erewrite testbit_decode_digit_select with (i := x); eauto | ] - | |- _ => reflexivity - | |- _ => assumption - | |- _ => zify_nat_hyp; omega - | |- ?a * ?b <= ?c * ?b + ?d => transitivity (c * b); [ | omega ] - | |- ?a * ?b <= ?c * ?b => apply Z.mul_le_mono_pos_r - | |- _ => solve [auto] - | |- _ => solve [eapply uniform_limb_widths_nonneg; eauto] - end. - Qed. - - Hint Rewrite div_add_l' mod_add_l mod_add_l' mod_div_eq0 add_0_r mod_mod : nat_mod_div. - - Lemma testbit_spec : forall n us, (length us = length limb_widths)%nat -> - bounded limb_widths us -> - testbit us n = Z.testbit (BaseSystem.decode base us) (Z.of_nat n). - Proof using limb_width_pos limb_widths_uniform. - cbv [testbit]; intros. - pose proof limb_width_pos as limb_width_pos_nat. - rewrite Z2Nat.inj_lt in limb_width_pos_nat by omega. - rewrite (Nat.div_mod n (Z.to_nat width)) by omega. - autorewrite with nat_mod_div; try omega. - rewrite testbit_spec' by (rewrite ?mod_Zmod, ?Z2Nat.id; try apply Z.mod_pos_bound; omega || auto). - f_equal. - rewrite Nat2Z.inj_add, Nat2Z.inj_mul, Z2Nat.id; ring || omega. - Qed. - -End Testbit. diff --git a/src/Util/AdditionChainExponentiation.v b/src/Util/AdditionChainExponentiation.v index fc082a54a..e03b2e36f 100644 --- a/src/Util/AdditionChainExponentiation.v +++ b/src/Util/AdditionChainExponentiation.v @@ -1,9 +1,9 @@ Require Import Coq.Lists.List Coq.Lists.SetoidList. Import ListNotations. Require Import Coq.Numbers.BinNums Coq.NArith.BinNat. Require Import Crypto.Util.ListUtil. -Require Import Crypto.Algebra Crypto.Algebra.Monoid Crypto.Algebra.ScalarMult. -Require Import Crypto.Tactics.VerdiTactics. +Require Import Crypto.Algebra.Monoid Crypto.Algebra.ScalarMult. Require Import Crypto.Util.Option. +Require Import Crypto.Util.Tactics.BreakMatch. Section AddChainExp. Function fold_chain {T} (id:T) (op:T->T->T) (is:list (nat*nat)) (acc:list T) {struct is} : T := @@ -28,7 +28,7 @@ Section AddChainExp. (0, 6)] (* 31 = 30 + 1 *) [1] = 31. reflexivity. Qed. - Context {G eq op id} {monoid:@Algebra.monoid G eq op id}. + Context {G eq op id} {monoid:@Algebra.Hierarchy.monoid G eq op id}. Context {scalarmult} {is_scalarmult:@ScalarMult.is_scalarmult G eq op id scalarmult}. Local Infix "=" := eq : type_scope. Local Open Scope N_scope. diff --git a/src/Util/CaseUtil.v b/src/Util/CaseUtil.v deleted file mode 100644 index 2d1ab6c58..000000000 --- a/src/Util/CaseUtil.v +++ /dev/null @@ -1,18 +0,0 @@ -Require Import Coq.Arith.Arith Coq.Arith.Max. - -Ltac case_max := - match goal with [ |- context[max ?x ?y] ] => - destruct (le_dec x y); - match goal with - | [ H : (?x <= ?y)%nat |- context[max ?x ?y] ] => rewrite max_r by - (exact H) - | [ H : ~ (?x <= ?y)%nat |- context[max ?x ?y] ] => rewrite max_l by - (exact (le_Sn_le _ _ (not_le _ _ H))) - end - end. - -Lemma pull_app_if_sumbool {A B X Y} (b : sumbool X Y) (f g : A -> B) (x : A) - : (if b then f x else g x) = (if b then f else g) x. -Proof. - destruct b; reflexivity. -Qed. diff --git a/src/Util/IterAssocOp.v b/src/Util/IterAssocOp.v index 2fd7f8adc..e4f9dde08 100644 --- a/src/Util/IterAssocOp.v +++ b/src/Util/IterAssocOp.v @@ -1,7 +1,7 @@ Require Import Coq.Setoids.Setoid Coq.Classes.Morphisms Coq.Classes.Equivalence. Require Import Coq.NArith.NArith Coq.PArith.BinPosDef. Require Import Coq.Numbers.Natural.Peano.NPeano. -Require Import Crypto.Algebra Crypto.Algebra.Monoid Crypto.Algebra.ScalarMult. +Require Import Crypto.Algebra.Monoid Crypto.Algebra.ScalarMult. Require Import Crypto.Util.NUtil. Require Import Crypto.Util.Tactics.BreakMatch. @@ -9,7 +9,7 @@ Local Open Scope equiv_scope. Generalizable All Variables. Section IterAssocOp. - Context {T eq op id} {moinoid : @monoid T eq op id} (testbit : nat -> bool). + Context {T eq op id} {moinoid : @Algebra.Hierarchy.monoid T eq op id} (testbit : nat -> bool). Local Infix "===" := eq. Local Infix "===" := eq : type_scope. Local Notation nat_iter_op := (ScalarMult.scalarmult_ref (add:=op) (zero:=id)). @@ -26,12 +26,12 @@ Section IterAssocOp. Lemma Pos_iter_op_succ : forall p a, Pos.iter_op op (Pos.succ p) a === op a (Pos.iter_op op p a). Proof using Type*. - induction p; intros; simpl; rewrite ?associative, ?IHp; reflexivity. + induction p; intros; simpl; rewrite ?Algebra.Hierarchy.associative, ?IHp; reflexivity. Qed. Lemma N_iter_op_succ : forall n a, N_iter_op (N.succ n) a === op a (N_iter_op n a). Proof using Type*. - destruct n; simpl; intros; rewrite ?Pos_iter_op_succ, ?right_identity; reflexivity. + destruct n; simpl; intros; rewrite ?Pos_iter_op_succ, ?Algebra.Hierarchy.right_identity; reflexivity. Qed. Lemma N_iter_op_is_nat_iter_op : forall n a, N_iter_op n a === nat_iter_op (N.to_nat n) a. diff --git a/src/Util/ListUtil.v b/src/Util/ListUtil.v index 32c6dbdf7..a9987ffde 100644 --- a/src/Util/ListUtil.v +++ b/src/Util/ListUtil.v @@ -1,11 +1,12 @@ Require Import Coq.Lists.List. -Require Import Coq.omega.Omega. +Require Import Coq.omega.Omega Lia. Require Import Coq.Arith.Peano_dec. Require Import Coq.Classes.Morphisms. -Require Import Crypto.Tactics.VerdiTactics. Require Import Coq.Numbers.Natural.Peano.NPeano. Require Import Crypto.Util.NatUtil. Require Export Crypto.Util.FixCoqMistakes. +Require Export Crypto.Util.Tactics.BreakMatch. +Require Export Crypto.Util.Tactics.DestructHead. Create HintDb distr_length discriminated. Create HintDb simpl_set_nth discriminated. @@ -552,8 +553,7 @@ Lemma splice_nth_equiv_update_nth : forall {T} n f d (xs:list T), then update_nth n f xs else xs ++ (f d)::nil. Proof. - induction n, xs; boring_list. - do 2 break_if; auto; omega. + induction n, xs; boring_list; break_match; auto; omega. Qed. Lemma splice_nth_equiv_update_nth_update : forall {T} n f d (xs:list T), @@ -561,8 +561,7 @@ Lemma splice_nth_equiv_update_nth_update : forall {T} n f d (xs:list T), splice_nth n (f (nth_default d xs n)) xs = update_nth n f xs. Proof. intros. - rewrite splice_nth_equiv_update_nth. - break_if; auto; omega. + rewrite splice_nth_equiv_update_nth; break_match; auto; omega. Qed. Lemma splice_nth_equiv_update_nth_snoc : forall {T} n f d (xs:list T), @@ -570,8 +569,7 @@ Lemma splice_nth_equiv_update_nth_snoc : forall {T} n f d (xs:list T), splice_nth n (f (nth_default d xs n)) xs = xs ++ (f d)::nil. Proof. intros. - rewrite splice_nth_equiv_update_nth. - break_if; auto; omega. + rewrite splice_nth_equiv_update_nth; break_match; auto; omega. Qed. Definition IMPOSSIBLE {T} : list T. exact nil. Qed. @@ -688,7 +686,7 @@ Qed. Lemma In_nth_error_value : forall {T} xs (x:T), In x xs -> exists n, nth_error xs n = Some x. Proof. - induction xs; nth_tac; break_or_hyp. + induction xs; nth_tac; destruct_head or; subst. - exists 0; reflexivity. - edestruct IHxs; eauto. exists (S x0). eauto. Qed. @@ -1115,11 +1113,11 @@ Hint Resolve @nth_default_in_bounds : simpl_nth_default. Lemma cons_eq_head : forall {T} (x y:T) xs ys, x::xs = y::ys -> x=y. Proof. - intros; solve_by_inversion. + intros; congruence. Qed. Lemma cons_eq_tail : forall {T} (x y:T) xs ys, x::xs = y::ys -> xs=ys. Proof. - intros; solve_by_inversion. + intros; congruence. Qed. Lemma map_nth_default_always {A B} (f : A -> B) (n : nat) (x : A) (l : list A) @@ -1238,8 +1236,8 @@ Lemma update_nth_nth_default_full : forall {A} (d:A) n f l i, else d. Proof. induction n; (destruct l; simpl in *; [ intros; destruct i; simpl; try reflexivity; omega | ]); - intros; repeat break_if; subst; try destruct i; - repeat first [ progress break_if + intros; repeat break_match; subst; try destruct i; + repeat first [ progress break_match | progress subst | progress boring | progress autorewrite with simpl_nth_default @@ -1251,7 +1249,7 @@ Hint Rewrite @update_nth_nth_default_full : push_nth_default. Lemma update_nth_nth_default : forall {A} (d:A) n f l i, (0 <= i < length l)%nat -> nth_default d (update_nth n f l) i = if (eq_nat_dec i n) then f (nth_default d l i) else nth_default d l i. -Proof. intros; rewrite update_nth_nth_default_full; repeat break_if; boring. Qed. +Proof. intros; rewrite update_nth_nth_default_full; repeat break_match; boring. Qed. Hint Rewrite @update_nth_nth_default using (omega || distr_length; omega) : push_nth_default. @@ -1527,23 +1525,23 @@ Proof. induction ls1, ls2. + cbv [map2 length min]. intros. - break_if; try omega. + break_match; try omega. apply nth_default_nil. + cbv [map2 length min]. intros. - break_if; try omega. + break_match; try omega. apply nth_default_nil. + cbv [map2 length min]. intros. - break_if; try omega. + break_match; try omega. apply nth_default_nil. + simpl. destruct i. - intros. rewrite !nth_default_cons. - break_if; auto; omega. + break_match; auto; omega. - intros. rewrite !nth_default_cons_S. rewrite IHls1 with (d1 := d1) (d2 := d2). - repeat break_if; auto; omega. + repeat break_match; auto; omega. Qed. Lemma map2_cons : forall A B C (f : A -> B -> C) ls1 ls2 a b, @@ -1655,15 +1653,15 @@ Lemma nth_default_firstn : forall {A} (d : A) l i n, then if lt_dec i n then nth_default d l i else d else nth_default d l i. Proof. - induction n; intros; break_if; autorewrite with push_nth_default; auto; try omega. + induction n; intros; break_match; autorewrite with push_nth_default; auto; try omega. + rewrite (firstn_succ d) by omega. - autorewrite with push_nth_default; repeat (break_if; distr_length); + autorewrite with push_nth_default; repeat (break_match_hyps; break_match; distr_length); rewrite Min.min_l in * by omega; try omega. - apply IHn; omega. - replace i with n in * by omega. rewrite Nat.sub_diag. autorewrite with push_nth_default; auto. - - rewrite nth_default_out_of_bounds; distr_length; auto. + + rewrite nth_default_out_of_bounds; break_match_hyps; distr_length; auto; lia. + rewrite firstn_all2 by omega. auto. Qed. diff --git a/src/Util/NumTheoryUtil.v b/src/Util/NumTheoryUtil.v index 05ce4a0de..2ccb0455f 100644 --- a/src/Util/NumTheoryUtil.v +++ b/src/Util/NumTheoryUtil.v @@ -2,8 +2,8 @@ Require Import Coq.ZArith.Zpower Coq.ZArith.Znumtheory Coq.ZArith.ZArith Coq.ZAr Require Import Coq.omega.Omega Coq.Numbers.Natural.Peano.NPeano Coq.Arith.Arith. Require Import Crypto.Util.NatUtil Crypto.Util.ZUtil. Require Import Coqprime.Zp. -Require Import Crypto.Tactics.VerdiTactics. Require Export Crypto.Util.FixCoqMistakes. +Require Export Crypto.Util.Tactics. Local Open Scope Z. (* TODO: move somewhere else for lemmas about Coqprime? *) @@ -284,7 +284,7 @@ Proof. intros. destruct (Z.prime_odd_or_2 p prime_p); intuition. rewrite <- Zdiv2_div. - pose proof (Zdiv2_odd_eqn p); break_if; congruence || omega. + pose proof (Zdiv2_odd_eqn p); break_match; break_match_hyps; congruence || omega. Qed. Lemma minus1_square_1mod4 : forall (p : Z) (prime_p : prime p), diff --git a/src/Util/ZUtil.v b/src/Util/ZUtil.v index 5e59daab9..91c350d9f 100644 --- a/src/Util/ZUtil.v +++ b/src/Util/ZUtil.v @@ -11,7 +11,6 @@ Require Import Crypto.Util.Bool. Require Import Crypto.Util.Notations. Require Import Coq.Lists.List. Require Export Crypto.Util.FixCoqMistakes. -(*Require Export Crypto.Tactics.VerdiTactics.*) Import Nat. Local Open Scope Z. diff --git a/synthesis-parameters.txt b/synthesis-parameters.txt new file mode 100644 index 000000000..2140cebf0 --- /dev/null +++ b/synthesis-parameters.txt @@ -0,0 +1,53 @@ +==> src/SpecificGen/2213_32.json <== +{ + "k" : 221, + "c" : 3, + "n" : 8, + "w" : 32, + "ch" : "[0;1;2;3;4;5;6;7;0;1]" +} + +==> src/SpecificGen/2519_32.json <== +{ + "k" : 251, + "c" : 9, + "n" : 10, + "w" : 32, + "ch" : "[0;1;2;3;4;5;6;7;8;9;0;1]" +} + +==> src/SpecificGen/25519_32.json <== +{ + "k" : 255, + "c" : 19, + "n" : 10, + "w" : 32, + "ch" : "[0;1;2;3;4;5;6;7;8;9;0;1]" +} + +==> src/SpecificGen/25519_64.json <== +{ + "k" : 255, + "c" : 19, + "n" : 5, + "w" : 64, + "ch" : "[0;1;2;3;4;0;1]" +} + +==> src/SpecificGen/41417_32.json <== +{ + "k" : 414, + "c" : 17, + "n" : 18, + "w" : 32, + "ch" : "[0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;0;1]" +} + +==> src/SpecificGen/5211_32.json <== +{ + "k" : 521, + "c" : 1, + "n" : 20, + "w" : 32, + "ch" : "[0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;0;1]" +} |