Class Optimizer

  • Direct Known Subclasses:
    OptimizerEE

    public class Optimizer
    extends java.lang.Object
    This class performs optimizations that vary between different versions of the Saxon product. The optimizer is obtained from the Saxon Configuration. This class is the version used in Saxon-HE, which in most cases does no optimization at all: the methods are provided so that they can be overridden in Saxon-EE.
    • Field Detail

      • tracing

        protected boolean tracing
    • Constructor Detail

      • Optimizer

        public Optimizer​(Configuration config)
        Create an Optimizer.
        Parameters:
        config - the Saxon configuration
    • Method Detail

      • getConfiguration

        public Configuration getConfiguration()
        Get the Saxon configuration object
        Returns:
        the configuration
      • setOptimizerOptions

        public void setOptimizerOptions​(OptimizerOptions options)
        Set the optimizer options
        Parameters:
        options - the optimizer options
      • getOptimizerOptions

        public OptimizerOptions getOptimizerOptions()
        Get the optimizer options
        Returns:
        the optimizer options
      • isOptionSet

        public boolean isOptionSet​(int option)
        Ask whether a particular optimizer option is set
        Parameters:
        option - the code identifying the option, e.g. OptimizerOptions.BYTE_CODE
        Returns:
        true if the option is set
      • optimizeGeneralComparison

        public Expression optimizeGeneralComparison​(ExpressionVisitor visitor,
                                                    GeneralComparison gc,
                                                    boolean backwardsCompatible,
                                                    ContextItemStaticInfo contextItemType)
        Simplify a GeneralComparison expression
        Parameters:
        visitor - the expression visitor
        gc - the GeneralComparison to be simplified
        backwardsCompatible - true if in 1.0 compatibility mode
        Returns:
        the simplified expression
      • optimizeSaxonStreamFunction

        public Expression optimizeSaxonStreamFunction​(ExpressionVisitor visitor,
                                                      ContextItemStaticInfo cisi,
                                                      Expression select)
                                               throws XPathException
        Attempt to optimize a call on saxon:stream(). Return null if no optimization is possible.
        Parameters:
        select - the expression that selects the items to be copied
        Returns:
        null if no optimization is possible, or an expression that does an optimized copy of these items otherwise
        Throws:
        XPathException
      • convertPathExpressionToKey

        public Expression convertPathExpressionToKey​(SlashExpression pathExp,
                                                     ExpressionVisitor visitor)
                                              throws XPathException
        Examine a path expression to see whether it can be replaced by a call on the key() function; if so, generate an appropriate key definition and return the call on key(). If not, return null.
        Parameters:
        pathExp - The path expression to be converted.
        visitor - The expression visitor
        Returns:
        the optimized expression, or null if no optimization is possible
        Throws:
        XPathException
      • tryIndexedFilter

        public Expression tryIndexedFilter​(FilterExpression f,
                                           ExpressionVisitor visitor,
                                           boolean indexFirstOperand,
                                           boolean contextIsDoc)
        Try converting a filter expression to a call on the key function. Return the supplied expression unchanged if not possible
        Parameters:
        f - the filter expression to be converted
        visitor - the expression visitor, which must be currently visiting the filter expression f
        indexFirstOperand - true if the first operand of the filter comparison is to be indexed; false if it is the second operand
        contextIsDoc - true if the context item is known to be a document node
        Returns:
        the optimized expression, or the unchanged expression f if no optimization is possible
      • reorderPredicates

        public FilterExpression reorderPredicates​(FilterExpression f,
                                                  ExpressionVisitor visitor,
                                                  ContextItemStaticInfo cisi)
                                           throws XPathException
        Consider reordering the predicates in a filter expression based on cost estimates and other criteria
        Parameters:
        f - the filter expression
        visitor - expression visitor
        cisi - information about the context item type
        Returns:
        either the original expression, or an optimized replacement
        Throws:
        XPathException - if things go wrong
      • convertToFilterExpression

        public FilterExpression convertToFilterExpression​(SlashExpression pathExp,
                                                          TypeHierarchy th)
                                                   throws XPathException
        Convert a path expression such as a/b/c[predicate] into a filter expression of the form (a/b/c)[predicate]. This is possible whenever the predicate is non-positional. The conversion is useful in the case where the path expression appears inside a loop, where the predicate depends on the loop variable but a/b/c does not.
        Parameters:
        pathExp - the path expression to be converted
        th - the type hierarchy cache
        Returns:
        the resulting filterexpression if conversion is possible, or null if not
        Throws:
        XPathException
      • isIndexableFilter

        public int isIndexableFilter​(Expression filter)
        Test whether a filter predicate is indexable.
        Parameters:
        filter - the predicate expression
        Returns:
        0 if not indexable; +1 if the predicate is in the form expression=value; -1 if it is in the form value=expression
      • makeIndexedValue

        public GroundedValue makeIndexedValue​(SequenceIterator iter)
                                       throws XPathException
        Create an indexed value
        Parameters:
        iter - the iterator that delivers the sequence of values to be indexed
        Returns:
        the indexed value
        Throws:
        java.lang.UnsupportedOperationException - this method should not be called in Saxon-HE
        XPathException
      • optimizeNodeSetPattern

        public void optimizeNodeSetPattern​(NodeSetPattern pattern)
      • prepareForStreaming

        public void prepareForStreaming​(Expression exp)
                                 throws XPathException
        Prepare an expression for streaming
        Parameters:
        exp - the expression to be prepared
        Throws:
        XPathException
      • evaluateStreamingArgument

        public Sequence evaluateStreamingArgument​(Expression expr,
                                                  XPathContext context)
                                           throws XPathException
        Evaluate the streaming (first) argument of a streamable stylesheet function
        Parameters:
        expr - the expression supplied for the value of the streaming argument
        context - the XPath evaluation context of the caller
        Returns:
        the (nominal) result of the evaluation
        Throws:
        XPathException
      • isVariableReplaceableByDot

        public boolean isVariableReplaceableByDot​(Expression exp,
                                                  Binding[] binding)
        Determine whether it is possible to rearrange an expression so that all references to a given variable are replaced by a reference to ".". This is true of there are no references to the variable within a filter predicate or on the rhs of a "/" operator.
        Parameters:
        exp - the expression in question
        binding - an array of bindings defining range variables; the method tests that there are no references to any of these variables within a predicate or on the rhs of "/"
        Returns:
        true if the variable reference can be replaced
      • makeConditionalDocumentSorter

        public Expression makeConditionalDocumentSorter​(DocumentSorter sorter,
                                                        SlashExpression path)
                                                 throws XPathException
        Make a conditional document sorter. This optimization is attempted when a DocumentSorter is wrapped around a path expression
        Parameters:
        sorter - the document sorter
        path - the path expression
        Returns:
        the original sorter unchanged when no optimization is possible, which is always the case in Saxon-HE
        Throws:
        XPathException
      • tryInlineFunctionCall

        public Expression tryInlineFunctionCall​(UserFunctionCall functionCall,
                                                ExpressionVisitor visitor,
                                                ContextItemStaticInfo contextItemType)
        Replace a function call by the body of the function, assuming all conditions for inlining the function are satisfied
        Parameters:
        functionCall - the functionCall expression
        visitor - the expression visitor
        contextItemType - the context item type
        Returns:
        either the original expression unchanged, or an expression that consists of the inlined function body, with all function parameters bound as required. In Saxon-HE, function inlining is not supported, so the original functionCall is always returned unchanged
      • promoteExpressionsToGlobal

        public Expression promoteExpressionsToGlobal​(Expression body,
                                                     GlobalVariableManager gvManager,
                                                     ExpressionVisitor visitor)
                                              throws XPathException
        Identify expressions within a function or template body that can be promoted to be evaluated as global variables.
        Parameters:
        body - the body of the template or function
        visitor - the expression visitor
        Returns:
        the expression after subexpressions have been promoted to global variables; or null if nothing has changed
        Throws:
        XPathException
      • eliminateCommonSubexpressions

        public Expression eliminateCommonSubexpressions​(Expression in)
        Eliminate common subexpressions. Rewrites (contains(X, 'x') and contains(X, 'y')) as (let $vv:C := X return (contains($vv:C, 'x') and contains($vv:C, 'y'))). Dummy method; the optimization happens only in Saxon-EE.
        Parameters:
        in - the expression to be optimized
        Returns:
        out the optimized expression (possibly the same as the input).
      • trySwitch

        public Expression trySwitch​(Choose choose,
                                    ExpressionVisitor visitor)
        Try to convert a Choose expression into a switch
        Parameters:
        choose - the Choose expression
        Returns:
        the result of optimizing this (the original expression if no optimization was possible)
      • tryGeneralComparison

        public Expression tryGeneralComparison​(ExpressionVisitor visitor,
                                               ContextItemStaticInfo contextItemType,
                                               OrExpression orExpr)
                                        throws XPathException
        Try to convert an Or expression into a comparison with Literal sequence
        Parameters:
        visitor - an expression visitor
        contextItemType - the static type of "." at the point where this expression is invoked. The parameter is set to null if it is known statically that the context item will be undefined. If the type of the context item is not known statically, the argument is set to Type.ITEM_TYPE
        orExpr - the expression to be converted
        Returns:
        the result of optimizing the Or expression (the original expression if no optimization was possible)
        Throws:
        XPathException
      • makeInversion

        public RuleTarget makeInversion​(Pattern pattern,
                                        NamedTemplate template)
                                 throws XPathException
        Generate the inversion of the expression comprising the body of a template rules. Supported in Saxon-EE only
        Parameters:
        pattern - the match pattern of this template rule
        template - the template to be inverted
        Throws:
        XPathException
      • makeCopyOperationsExplicit

        public void makeCopyOperationsExplicit​(Expression parent,
                                               Operand child)
                                        throws XPathException
        In streaming mode, make the copy operation applied to subexpressions of a complex-content sequence constructor into explicit copy-of operations.
        Throws:
        XPathException
      • checkStreamability

        public void checkStreamability​(XSLTemplate sourceTemplate,
                                       TemplateRule compiledTemplate)
                                throws XPathException
        Check the streamability of a template
        Parameters:
        sourceTemplate - the source of the template in the stylesheet tree
        compiledTemplate - the compiled template
        Throws:
        XPathException - if the template is declared streamable but does not satisfy the straming rules
      • optimizeForExpressionForStreaming

        public Expression optimizeForExpressionForStreaming​(ForExpression expr)
                                                     throws XPathException
        In streaming mode, optimizer a ForExpression for streaming
        Parameters:
        expr - the expression to be optimized
        Returns:
        the optimized expression
        Throws:
        XPathException
      • optimizeQuantifiedExpressionForStreaming

        public Expression optimizeQuantifiedExpressionForStreaming​(QuantifiedExpression expr)
                                                            throws XPathException
        In streaming mode, optimizer a QuantifiedExpression for streaming
        Parameters:
        expr - the expression to be optimized
        Returns:
        the optimized expression
        Throws:
        XPathException
      • generateMultithreadedInstruction

        public Expression generateMultithreadedInstruction​(Expression instruction)
        Generate a multi-threaded version of an instruction. Supported in Saxon-EE only; ignored with no action in Saxon-HE and Saxon-PE
        Parameters:
        instruction - the instruction to be multi-threaded
        Returns:
        the multi-threaded version of the instruction
      • compileToByteCode

        public Expression compileToByteCode​(ICompilerService compilerService,
                                            Expression expr,
                                            java.lang.String objectName,
                                            int evaluationMethods)
        Generate Java byte code for an expression
        Parameters:
        compilerService -
        expr - the expression to be compiled
        objectName - the name of the object (e.g. function) being compiled
        evaluationMethods - The evaluation modes for which code is generated. Currently a subset of Expression.PROCESS_METHOD, Expression.ITERATE_METHOD. If no code is generated for
      • makeByteCodeCandidate

        public Expression makeByteCodeCandidate​(ExpressionOwner owner,
                                                Expression expr,
                                                java.lang.String objectName,
                                                int requiredEvaluationModes)
        Insert a ByteCodeCandidate into the expression tree. A ByteCodeCandidate monitors how many times it is executed, and after reaching a certain threshold, generates bytecode for faster evaluation of its target expression
        Parameters:
        owner - the owning construct in the expression tree
        expr - the child (target) expression
        objectName - name to be used in forming the name of the bytecode class
        requiredEvaluationModes - the evaluation modes for which code should be generated
        Returns:
        a new ByteCodeCandidate if the expression is suitable for bytecode generation, or the supplied target expression otherwise.
      • trace

        public void trace​(java.lang.String message,
                          Expression exp)
        Trace optimization actions
        Parameters:
        message - the message to be displayed
        exp - the expression after being rewritten