Package net.sf.saxon.expr.parser
Class Optimizer
- java.lang.Object
-
- net.sf.saxon.expr.parser.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 Summary
Fields Modifier and Type Field Description protected Configuration
config
protected boolean
tracing
-
Constructor Summary
Constructors Constructor Description Optimizer(Configuration config)
Create an Optimizer.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description void
assessFunctionStreamability(XSLFunction reporter, UserFunction compiledFunction)
void
checkStreamability(XSLTemplate sourceTemplate, TemplateRule compiledTemplate)
Check the streamability of a templateExpression
compileToByteCode(ICompilerService compilerService, Expression expr, java.lang.String objectName, int evaluationMethods)
Generate Java byte code for an expressionExpression
convertPathExpressionToKey(SlashExpression pathExp, ExpressionVisitor visitor)
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().FilterExpression
convertToFilterExpression(SlashExpression pathExp, TypeHierarchy th)
Convert a path expression such as a/b/c[predicate] into a filter expression of the form (a/b/c)[predicate].Expression
eliminateCommonSubexpressions(Expression in)
Eliminate common subexpressions.Sequence
evaluateStreamingArgument(Expression expr, XPathContext context)
Evaluate the streaming (first) argument of a streamable stylesheet functionExpression
generateMultithreadedInstruction(Expression instruction)
Generate a multi-threaded version of an instruction.Configuration
getConfiguration()
Get the Saxon configuration objectOptimizerOptions
getOptimizerOptions()
Get the optimizer optionsvoid
injectByteCodeCandidates(Expression exp)
int
isIndexableFilter(Expression filter)
Test whether a filter predicate is indexable.boolean
isOptionSet(int option)
Ask whether a particular optimizer option is setboolean
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 ".".Expression
makeByteCodeCandidate(ExpressionOwner owner, Expression expr, java.lang.String objectName, int requiredEvaluationModes)
Insert a ByteCodeCandidate into the expression tree.Expression
makeConditionalDocumentSorter(DocumentSorter sorter, SlashExpression path)
Make a conditional document sorter.void
makeCopyOperationsExplicit(Expression parent, Operand child)
In streaming mode, make the copy operation applied to subexpressions of a complex-content sequence constructor into explicit copy-of operations.GroundedValue
makeIndexedValue(SequenceIterator iter)
Create an indexed valueRuleTarget
makeInversion(Pattern pattern, NamedTemplate template)
Generate the inversion of the expression comprising the body of a template rules.Expression
optimizeForExpressionForStreaming(ForExpression expr)
In streaming mode, optimizer a ForExpression for streamingExpression
optimizeGeneralComparison(ExpressionVisitor visitor, GeneralComparison gc, boolean backwardsCompatible, ContextItemStaticInfo contextItemType)
Simplify a GeneralComparison expressionvoid
optimizeNodeSetPattern(NodeSetPattern pattern)
Expression
optimizeNumberInstruction(NumberInstruction ni, ContextItemStaticInfo contextInfo)
Expression
optimizeQuantifiedExpressionForStreaming(QuantifiedExpression expr)
In streaming mode, optimizer a QuantifiedExpression for streamingExpression
optimizeSaxonStreamFunction(ExpressionVisitor visitor, ContextItemStaticInfo cisi, Expression select)
Attempt to optimize a call on saxon:stream().Expression
optimizeValueComparison(ValueComparison vc, ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)
Optimize a value comparisonvoid
prepareForStreaming(Expression exp)
Prepare an expression for streamingExpression
promoteExpressionsToGlobal(Expression body, GlobalVariableManager gvManager, ExpressionVisitor visitor)
Identify expressions within a function or template body that can be promoted to be evaluated as global variables.FilterExpression
reorderPredicates(FilterExpression f, ExpressionVisitor visitor, ContextItemStaticInfo cisi)
Consider reordering the predicates in a filter expression based on cost estimates and other criteriavoid
setOptimizerOptions(OptimizerOptions options)
Set the optimizer optionsvoid
trace(java.lang.String message, Expression exp)
Trace optimization actionsstatic void
trace(Configuration config, java.lang.String message, Expression exp)
Expression
tryGeneralComparison(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType, OrExpression orExpr)
Try to convert an Or expression into a comparison with Literal sequenceExpression
tryIndexedFilter(FilterExpression f, ExpressionVisitor visitor, boolean indexFirstOperand, boolean contextIsDoc)
Try converting a filter expression to a call on the key function.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 satisfiedExpression
trySwitch(Choose choose, ExpressionVisitor visitor)
Try to convert a Choose expression into a switch
-
-
-
Field Detail
-
config
protected Configuration config
-
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
-
optimizeValueComparison
public Expression optimizeValueComparison(ValueComparison vc, ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException
Optimize a value comparison- Parameters:
vc
- the value comparison expressionvisitor
- the expression visitorcontextInfo
- static context item information- Returns:
- either the original value comparison, or an optimized equivalent
- Throws:
XPathException
- if things go wrong
-
optimizeGeneralComparison
public Expression optimizeGeneralComparison(ExpressionVisitor visitor, GeneralComparison gc, boolean backwardsCompatible, ContextItemStaticInfo contextItemType)
Simplify a GeneralComparison expression- Parameters:
visitor
- the expression visitorgc
- the GeneralComparison to be simplifiedbackwardsCompatible
- true if in 1.0 compatibility modecontextItemType
- the static type of the context item- 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:
visitor
- the expression visitorcisi
- Static information about the context itemselect
- 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
- if any error occurs
-
convertPathExpressionToKey
public Expression convertPathExpressionToKey(SlashExpression pathExp, ExpressionVisitor visitor)
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
-
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 convertedvisitor
- the expression visitor, which must be currently visiting the filter expression findexFirstOperand
- true if the first operand of the filter comparison is to be indexed; false if it is the second operandcontextIsDoc
- 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 expressionvisitor
- expression visitorcisi
- 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)
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 convertedth
- the type hierarchy cache- Returns:
- the resulting filter expression if conversion is possible, or null if not
-
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 java.lang.UnsupportedOperationException, 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-HEXPathException
- if an error occurs
-
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
- if any error occurs
-
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 argumentcontext
- the XPath evaluation context of the caller- Returns:
- the (nominal) result of the evaluation
- Throws:
XPathException
- if any error occurs
-
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 questionbinding
- 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 sorterpath
- the path expression- Returns:
- the original sorter unchanged when no optimization is possible, which is always the case in Saxon-HE
- Throws:
XPathException
- if any error occurs
-
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 expressionvisitor
- the expression visitorcontextItemType
- 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 functiongvManager
- the global variable managervisitor
- the expression visitor- Returns:
- the expression after subexpressions have been promoted to global variables; or null if nothing has changed
- Throws:
XPathException
- if any error occurs
-
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 expressionvisitor
- the expression visitor- 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 visitorcontextItemType
- 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 toType.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
- if any error occurs
-
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 ruletemplate
- the template to be inverted- Returns:
- the inversion of the expression
- Throws:
XPathException
- if any error occurs
-
makeCopyOperationsExplicit
public void makeCopyOperationsExplicit(Expression parent, Operand child)
In streaming mode, make the copy operation applied to subexpressions of a complex-content sequence constructor into explicit copy-of operations.- Parameters:
parent
- the parent expressionchild
- the operand
-
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 treecompiledTemplate
- 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
- if any error occurs
-
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
- if any error occurs
-
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
- the compiler serviceexpr
- the expression to be compiledobjectName
- the name of the object (e.g. function) being compiledevaluationMethods
- The evaluation modes for which code is generated. Currently a subset ofExpression.PROCESS_METHOD
,Expression.ITERATE_METHOD
. If no code is generated for a given evaluation method, the fallback implementation from the superclass is used.- Returns:
- the compiled expression if possible, or null if compilation is not possible
-
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 treeexpr
- the child (target) expressionobjectName
- name to be used in forming the name of the bytecode classrequiredEvaluationModes
- 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.
-
injectByteCodeCandidates
public void injectByteCodeCandidates(Expression exp) throws XPathException
- Throws:
XPathException
-
optimizeNumberInstruction
public Expression optimizeNumberInstruction(NumberInstruction ni, ContextItemStaticInfo contextInfo)
-
assessFunctionStreamability
public void assessFunctionStreamability(XSLFunction reporter, UserFunction compiledFunction) throws XPathException
- Throws:
XPathException
-
trace
public void trace(java.lang.String message, Expression exp)
Trace optimization actions- Parameters:
message
- the message to be displayedexp
- the expression after being rewritten
-
trace
public static void trace(Configuration config, java.lang.String message, Expression exp)
-
-