| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.expr.parser; |
| 9 | |
| 10 | import net.sf.saxon.Configuration; |
| 11 | import net.sf.saxon.expr.*; |
| 12 | import net.sf.saxon.expr.instruct.*; |
| 13 | import net.sf.saxon.expr.sort.DocumentSorter; |
| 14 | import net.sf.saxon.lib.Feature; |
| 15 | import net.sf.saxon.lib.Logger; |
| 16 | import net.sf.saxon.om.GroundedValue; |
| 17 | import net.sf.saxon.om.Item; |
| 18 | import net.sf.saxon.om.Sequence; |
| 19 | import net.sf.saxon.om.SequenceIterator; |
| 20 | import net.sf.saxon.pattern.Pattern; |
| 21 | import net.sf.saxon.style.XSLFunction; |
| 22 | import net.sf.saxon.style.XSLTemplate; |
| 23 | import net.sf.saxon.trans.GlobalVariableManager; |
| 24 | import net.sf.saxon.trans.XPathException; |
| 25 | import net.sf.saxon.trans.rules.RuleTarget; |
| 26 | import net.sf.saxon.type.TypeHierarchy; |
| 27 | |
| 28 | /** |
| 29 | * This class performs optimizations that vary between different versions of the Saxon product. |
| 30 | * The optimizer is obtained from the Saxon Configuration. This class is the version used in Saxon-HE, |
| 31 | * which in most cases does no optimization at all: the methods are provided so that they can be |
| 32 | * overridden in Saxon-EE. |
| 33 | */ |
| 34 | public class Optimizer { |
| 35 | |
| 36 | public static final int NO_OPTIMIZATION = 0; |
| 37 | public static final int FULL_OPTIMIZATION = 10; |
| 38 | |
| 39 | /*@NotNull*/ protected Configuration config; |
| 40 | private OptimizerOptions optimizerOptions = OptimizerOptions.FULL_EE_OPTIMIZATION; |
| 41 | protected boolean tracing; |
| 42 | |
| 43 | /** |
| 44 | * Create an Optimizer. |
| 45 | * |
| 46 | * @param config the Saxon configuration |
| 47 | */ |
| 48 | |
| 49 | public Optimizer(Configuration config) { |
| 50 | this.config = config; |
| 51 | this.tracing = config.getBooleanProperty(Feature.TRACE_OPTIMIZER_DECISIONS); |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Get the Saxon configuration object |
| 56 | * |
| 57 | * @return the configuration |
| 58 | */ |
| 59 | |
| 60 | /*@NotNull*/ |
| 61 | public Configuration getConfiguration() { |
| 62 | return config; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Set the optimizer options |
| 67 | * |
| 68 | * @param options the optimizer options |
| 69 | */ |
| 70 | |
| 71 | public void setOptimizerOptions(OptimizerOptions options) { |
| 72 | optimizerOptions = options; |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Get the optimizer options |
| 77 | * |
| 78 | * @return the optimizer options |
| 79 | */ |
| 80 | |
| 81 | public OptimizerOptions getOptimizerOptions() { |
| 82 | return optimizerOptions; |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Ask whether a particular optimizer option is set |
| 87 | * @param option the code identifying the option, e.g. {@link OptimizerOptions#BYTE_CODE} |
| 88 | * @return true if the option is set |
| 89 | */ |
| 90 | |
| 91 | public boolean isOptionSet(int option) { |
| 92 | return optimizerOptions.isSet(option); |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * Simplify a GeneralComparison expression |
| 97 | * |
| 98 | * @param visitor the expression visitor |
| 99 | * @param gc the GeneralComparison to be simplified |
| 100 | * @param backwardsCompatible true if in 1.0 compatibility mode |
| 101 | * @return the simplified expression |
| 102 | */ |
| 103 | |
| 104 | public Expression optimizeGeneralComparison(ExpressionVisitor visitor, |
| 105 | GeneralComparison gc, boolean backwardsCompatible, ContextItemStaticInfo contextItemType) { |
| 106 | return gc; |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Attempt to optimize a call on saxon:stream(). Return null if no optimization is possible. |
| 111 | * |
| 112 | * @param select the expression that selects the items to be copied |
| 113 | * @return null if no optimization is possible, or an expression that does an optimized |
| 114 | * copy of these items otherwise |
| 115 | */ |
| 116 | |
| 117 | /*@Nullable*/ |
| 118 | public Expression optimizeSaxonStreamFunction(ExpressionVisitor visitor, ContextItemStaticInfo cisi, Expression select) throws XPathException { |
| 119 | if (select.getItemType().isPlainType()) { |
| 120 | return select; |
| 121 | } |
| 122 | return null; |
| 123 | } |
| 124 | |
| 125 | |
| 126 | /** |
| 127 | * Examine a path expression to see whether it can be replaced by a call on the key() function; |
| 128 | * if so, generate an appropriate key definition and return the call on key(). If not, return null. |
| 129 | * |
| 130 | * @param pathExp The path expression to be converted. |
| 131 | * @param visitor The expression visitor |
| 132 | * @return the optimized expression, or null if no optimization is possible |
| 133 | */ |
| 134 | |
| 135 | public Expression convertPathExpressionToKey(SlashExpression pathExp, ExpressionVisitor visitor) |
| 136 | throws XPathException { |
| 137 | return null; |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Try converting a filter expression to a call on the key function. Return the supplied |
| 142 | * expression unchanged if not possible |
| 143 | * |
| 144 | * @param f the filter expression to be converted |
| 145 | * @param visitor the expression visitor, which must be currently visiting the filter expression f |
| 146 | * @param indexFirstOperand true if the first operand of the filter comparison is to be indexed; |
| 147 | * false if it is the second operand |
| 148 | * @param contextIsDoc true if the context item is known to be a document node |
| 149 | * @return the optimized expression, or the unchanged expression f if no optimization is possible |
| 150 | */ |
| 151 | |
| 152 | public Expression tryIndexedFilter(FilterExpression f, ExpressionVisitor visitor, boolean indexFirstOperand, boolean contextIsDoc) { |
| 153 | return f; |
| 154 | } |
| 155 | |
| 156 | /** |
| 157 | * Consider reordering the predicates in a filter expression based on cost estimates |
| 158 | * |
| 159 | * @param f the filter expression (which is known to have more than one predicate) |
| 160 | * @param visitor expression visitor |
| 161 | * @param cisi information about the context item type |
| 162 | * @return either the original expression, or an optimized replacement |
| 163 | * @throws XPathException if things go wrong |
| 164 | */ |
| 165 | |
| 166 | public Expression reorderPredicates(FilterExpression f, ExpressionVisitor visitor, ContextItemStaticInfo cisi) |
| 167 | throws XPathException { |
| 168 | return f; |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Convert a path expression such as a/b/c[predicate] into a filter expression |
| 173 | * of the form (a/b/c)[predicate]. This is possible whenever the predicate is non-positional. |
| 174 | * The conversion is useful in the case where the path expression appears inside a loop, |
| 175 | * where the predicate depends on the loop variable but a/b/c does not. |
| 176 | * |
| 177 | * @param pathExp the path expression to be converted |
| 178 | * @param th the type hierarchy cache |
| 179 | * @return the resulting filterexpression if conversion is possible, or null if not |
| 180 | */ |
| 181 | |
| 182 | public FilterExpression convertToFilterExpression(SlashExpression pathExp, TypeHierarchy th) |
| 183 | throws XPathException { |
| 184 | return null; |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * Test whether a filter predicate is indexable. |
| 189 | * |
| 190 | * @param filter the predicate expression |
| 191 | * @return 0 if not indexable; +1 if the predicate is in the form expression=value; -1 if it is in |
| 192 | * the form value=expression |
| 193 | */ |
| 194 | |
| 195 | public int isIndexableFilter(Expression filter) { |
| 196 | return 0; |
| 197 | } |
| 198 | |
| 199 | /** |
| 200 | * Create an indexed value |
| 201 | * |
| 202 | * @param iter the iterator that delivers the sequence of values to be indexed |
| 203 | * @return the indexed value |
| 204 | * @throws UnsupportedOperationException: this method should not be called in Saxon-HE |
| 205 | */ |
| 206 | |
| 207 | public <T extends Item<?>> GroundedValue<T> makeIndexedValue(SequenceIterator<? extends T> iter) throws XPathException { |
| 208 | throw new UnsupportedOperationException("Indexing requires Saxon-EE"); |
| 209 | } |
| 210 | |
| 211 | /** |
| 212 | * Prepare an expression for streaming |
| 213 | * @param exp the expression to be prepared |
| 214 | */ |
| 215 | |
| 216 | public void prepareForStreaming(Expression exp) throws XPathException { |
| 217 | // No action except for Saxon-EE |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * Evaluate the streaming (first) argument of a streamable stylesheet function |
| 222 | * |
| 223 | * @param expr the expression supplied for the value of the streaming argument |
| 224 | * @param context the XPath evaluation context of the caller |
| 225 | * @return the (nominal) result of the evaluation |
| 226 | */ |
| 227 | |
| 228 | public Sequence<?> evaluateStreamingArgument(Expression expr, XPathContext context) throws XPathException { |
| 229 | // non-streaming fallback implementation |
| 230 | return ExpressionTool.eagerEvaluate(expr, context); |
| 231 | } |
| 232 | |
| 233 | /** |
| 234 | * Determine whether it is possible to rearrange an expression so that all references to a given |
| 235 | * variable are replaced by a reference to ".". This is true of there are no references to the variable |
| 236 | * within a filter predicate or on the rhs of a "/" operator. |
| 237 | * |
| 238 | * @param exp the expression in question |
| 239 | * @param binding an array of bindings defining range variables; the method tests that there are no |
| 240 | * references to any of these variables within a predicate or on the rhs of "/" |
| 241 | * @return true if the variable reference can be replaced |
| 242 | */ |
| 243 | |
| 244 | public boolean isVariableReplaceableByDot(Expression exp, Binding[] binding) { |
| 245 | // TODO: the fact that a variable reference appears inside a predicate (etc) shouldn't stop us |
| 246 | // rewriting a where clause as a predicate. We just have to bind a new variable: |
| 247 | // for $x in P where abc[n = $x/m] ==> for $x in P[let $z := . return abc[n = $z/m] |
| 248 | // We could probably do this in all cases and then let $z be optimized away where appropriate |
| 249 | if (exp instanceof ContextSwitchingExpression) { |
| 250 | Expression start = ((ContextSwitchingExpression) exp).getSelectExpression(); |
| 251 | Expression step = ((ContextSwitchingExpression) exp).getActionExpression(); |
| 252 | return isVariableReplaceableByDot(start, binding) && |
| 253 | !ExpressionTool.dependsOnVariable(step, binding); |
| 254 | } else { |
| 255 | for (Operand o : exp.operands()) { |
| 256 | if (!isVariableReplaceableByDot(o.getChildExpression(), binding)) { |
| 257 | return false; |
| 258 | } |
| 259 | } |
| 260 | return true; |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | |
| 265 | /** |
| 266 | * Make a conditional document sorter. This optimization is attempted |
| 267 | * when a DocumentSorter is wrapped around a path expression |
| 268 | * |
| 269 | * @param sorter the document sorter |
| 270 | * @param path the path expression |
| 271 | * @return the original sorter unchanged when no optimization is possible, which is always the |
| 272 | * case in Saxon-HE |
| 273 | */ |
| 274 | |
| 275 | public Expression makeConditionalDocumentSorter(DocumentSorter sorter, SlashExpression path) throws XPathException { |
| 276 | return sorter; |
| 277 | } |
| 278 | |
| 279 | /** |
| 280 | * Replace a function call by the body of the function, assuming all conditions for inlining |
| 281 | * the function are satisfied |
| 282 | * |
| 283 | * @param functionCall the functionCall expression |
| 284 | * @param visitor the expression visitor |
| 285 | * @param contextItemType the context item type |
| 286 | * @return either the original expression unchanged, or an expression that consists of the inlined |
| 287 | * function body, with all function parameters bound as required. In Saxon-HE, function inlining is |
| 288 | * not supported, so the original functionCall is always returned unchanged |
| 289 | */ |
| 290 | |
| 291 | public Expression tryInlineFunctionCall( |
| 292 | UserFunctionCall functionCall, ExpressionVisitor visitor, ContextItemStaticInfo contextItemType) { |
| 293 | return functionCall; |
| 294 | } |
| 295 | |
| 296 | /** |
| 297 | * Identify expressions within a function or template body that can be promoted to be |
| 298 | * evaluated as global variables. |
| 299 | * |
| 300 | * @param body the body of the template or function |
| 301 | * @param visitor the expression visitor |
| 302 | * @return the expression after subexpressions have been promoted to global variables; or null if |
| 303 | * nothing has changed |
| 304 | */ |
| 305 | |
| 306 | public Expression promoteExpressionsToGlobal(Expression body, GlobalVariableManager gvManager, ExpressionVisitor visitor) |
| 307 | throws XPathException { |
| 308 | return null; |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Eliminate common subexpressions. Rewrites (contains(X, 'x') and contains(X, 'y')) as |
| 313 | * (let $vv:C := X return (contains($vv:C, 'x') and contains($vv:C, 'y'))). |
| 314 | * Dummy method; the optimization happens only in Saxon-EE. |
| 315 | * @param in the expression to be optimized |
| 316 | * @return out the optimized expression (possibly the same as the input). |
| 317 | */ |
| 318 | |
| 319 | public Expression eliminateCommonSubexpressions(Expression in) { |
| 320 | return in; |
| 321 | } |
| 322 | |
| 323 | /** |
| 324 | * Try to convert a Choose expression into a switch |
| 325 | * |
| 326 | * @param choose the Choose expression |
| 327 | * @return the result of optimizing this (the original expression if no optimization was possible) |
| 328 | */ |
| 329 | |
| 330 | public Expression trySwitch(Choose choose, ExpressionVisitor visitor) { |
| 331 | return choose; |
| 332 | } |
| 333 | |
| 334 | |
| 335 | /** |
| 336 | * Try to convert an Or expression into a comparison with Literal sequence |
| 337 | * |
| 338 | * @param visitor an expression visitor |
| 339 | * @param contextItemType the static type of "." at the point where this expression is invoked. |
| 340 | * The parameter is set to null if it is known statically that the context item will be undefined. |
| 341 | * If the type of the context item is not known statically, the argument is set to |
| 342 | * {@link net.sf.saxon.type.Type#ITEM_TYPE} |
| 343 | * @param orExpr the expression to be converted |
| 344 | * @return the result of optimizing the Or expression (the original expression if no optimization was possible) |
| 345 | */ |
| 346 | |
| 347 | public Expression tryGeneralComparison(ExpressionVisitor visitor, ContextItemStaticInfo contextItemType, OrExpression orExpr) throws XPathException { |
| 348 | return orExpr; |
| 349 | } |
| 350 | |
| 351 | /** |
| 352 | * Extract subexpressions from the body of a function that can be evaluated |
| 353 | * as global variables |
| 354 | * |
| 355 | * @param body the body of the function |
| 356 | * @param offer The PromotionOffer. Will be marked to indicate whether any action was taken |
| 357 | * @return a reference to the new global variable if a variable has been created, or null if not |
| 358 | */ |
| 359 | |
| 360 | // public Expression extractGlobalVariables(Expression body, ExpressionVisitor visitor, PromotionOffer offer) |
| 361 | // throws XPathException { |
| 362 | // return null; |
| 363 | // } |
| 364 | |
| 365 | /** |
| 366 | * Generate the inversion of the expression comprising the body of a template rules. |
| 367 | * Supported in Saxon-EE only |
| 368 | * |
| 369 | * @param pattern the match pattern of this template rule |
| 370 | * @param template the template to be inverted |
| 371 | */ |
| 372 | |
| 373 | public RuleTarget makeInversion(Pattern pattern, NamedTemplate template) throws XPathException { |
| 374 | return null; |
| 375 | } |
| 376 | |
| 377 | /** |
| 378 | * In streaming mode, make the copy operation applied to subexpressions of a complex-content |
| 379 | * sequence constructor into explicit copy-of operations. |
| 380 | */ |
| 381 | |
| 382 | public void makeCopyOperationsExplicit(Expression parent, Operand child) throws XPathException { |
| 383 | // no action unless streaming |
| 384 | } |
| 385 | |
| 386 | /** |
| 387 | * Check the streamability of a template |
| 388 | * |
| 389 | * @param sourceTemplate the source of the template in the stylesheet tree |
| 390 | * @param compiledTemplate the compiled template |
| 391 | * @throws XPathException if the template is declared streamable but does not satisfy the straming rules |
| 392 | */ |
| 393 | |
| 394 | public void checkStreamability(XSLTemplate sourceTemplate, TemplateRule compiledTemplate) throws XPathException { |
| 395 | // no action unless streaming |
| 396 | } |
| 397 | |
| 398 | |
| 399 | //#ifdefined STREAM |
| 400 | |
| 401 | /** |
| 402 | * In streaming mode, optimizer a ForExpression for streaming |
| 403 | * |
| 404 | * @param expr the expression to be optimized |
| 405 | * @return the optimized expression |
| 406 | */ |
| 407 | |
| 408 | public Expression optimizeForExpressionForStreaming(ForExpression expr) throws XPathException { |
| 409 | return expr; |
| 410 | } |
| 411 | |
| 412 | //#endif |
| 413 | |
| 414 | /** |
| 415 | * In streaming mode, optimizer a QuantifiedExpression for streaming |
| 416 | * |
| 417 | * @param expr the expression to be optimized |
| 418 | * @return the optimized expression |
| 419 | */ |
| 420 | |
| 421 | public Expression optimizeQuantifiedExpressionForStreaming(QuantifiedExpression expr) throws XPathException { |
| 422 | return expr; |
| 423 | } |
| 424 | |
| 425 | |
| 426 | /** |
| 427 | * Generate a multi-threaded version of an instruction. |
| 428 | * Supported in Saxon-EE only; ignored with no action in Saxon-HE and Saxon-PE |
| 429 | * |
| 430 | * @param instruction the instruction to be multi-threaded |
| 431 | * @return the multi-threaded version of the instruction |
| 432 | */ |
| 433 | |
| 434 | public Expression generateMultithreadedInstruction(Expression instruction) { |
| 435 | return instruction; |
| 436 | } |
| 437 | |
| 438 | /** |
| 439 | * Generate Java byte code for an expression |
| 440 | * |
| 441 | * @param compilerService |
| 442 | * @param expr the expression to be compiled |
| 443 | * @param objectName the name of the object (e.g. function) being compiled |
| 444 | * @param evaluationMethods The evaluation modes for which code is generated. Currently a subset of |
| 445 | * {@link Expression#PROCESS_METHOD}, {@link Expression#ITERATE_METHOD}. If no code is generated for |
| 446 | */ |
| 447 | |
| 448 | public Expression compileToByteCode(ICompilerService compilerService, Expression expr, String objectName, int evaluationMethods) { |
| 449 | return null; |
| 450 | } |
| 451 | |
| 452 | /** |
| 453 | * Insert a ByteCodeCandidate into the expression tree. A ByteCodeCandidate monitors how many |
| 454 | * times it is executed, and after reaching a certain threshold, generates bytecode for faster |
| 455 | * evaluation of its target expression |
| 456 | * |
| 457 | * @param owner the owning construct in the expression tree |
| 458 | * @param expr the child (target) expression |
| 459 | * @param objectName name to be used in forming the name of the bytecode class |
| 460 | * @param requiredEvaluationModes the evaluation modes for which code should be generated |
| 461 | * @return a new ByteCodeCandidate if the expression is suitable for bytecode generation, |
| 462 | * or the supplied target expression otherwise. |
| 463 | */ |
| 464 | |
| 465 | |
| 466 | public Expression makeByteCodeCandidate(ExpressionOwner owner, Expression expr, String objectName, int requiredEvaluationModes) { |
| 467 | return expr; |
| 468 | } |
| 469 | |
| 470 | public void injectByteCodeCandidates(Expression exp) throws XPathException { |
| 471 | |
| 472 | }; |
| 473 | |
| 474 | public Expression optimizeNumberInstruction(NumberInstruction ni, ContextItemStaticInfo contextInfo) { |
| 475 | return null; |
| 476 | } |
| 477 | |
| 478 | public void assessFunctionStreamability(XSLFunction sourceFunction, UserFunction compiledFunction) throws XPathException { |
| 479 | throw new XPathException("Streamable stylesheet functions are not supported in Saxon-HE", "XTSE3430"); |
| 480 | } |
| 481 | |
| 482 | /** |
| 483 | * Trace optimization actions |
| 484 | * |
| 485 | * @param message the message to be displayed |
| 486 | * @param exp the expression after being rewritten |
| 487 | */ |
| 488 | |
| 489 | public void trace(String message, Expression exp) { |
| 490 | if (tracing) { |
| 491 | Logger err = getConfiguration().getLogger(); |
| 492 | err.info("OPT : At line " + exp.getLocation().getLineNumber() + " of " + exp.getLocation().getSystemId()); |
| 493 | err.info("OPT : " + message); |
| 494 | err.info("OPT : Expression after rewrite: " + exp.toString()); |
| 495 | exp.verifyParentPointers(); |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | public static void trace(Configuration config, String message, Expression exp) { |
| 500 | if (config.getBooleanProperty(Feature.TRACE_OPTIMIZER_DECISIONS)) { |
| 501 | Logger err = config.getLogger(); |
| 502 | err.info("OPT : At line " + exp.getLocation().getLineNumber() + " of " + exp.getLocation().getSystemId()); |
| 503 | err.info("OPT : " + message); |
| 504 | err.info("OPT : Expression after rewrite: " + exp.toString()); |
| 505 | exp.verifyParentPointers(); |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | } |
| 510 |