MLIR 24.0.0git
LegalizeVectorStorage.cpp
Go to the documentation of this file.
1//===- LegalizeVectorStorage.cpp - Ensures SVE loads/stores are legal -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
16
17namespace mlir::arm_sve {
18#define GEN_PASS_DEF_LEGALIZEVECTORSTORAGE
19#include "mlir/Dialect/ArmSVE/Transforms/Passes.h.inc"
20} // namespace mlir::arm_sve
21
22using namespace mlir;
23using namespace mlir::arm_sve;
25// A tag to mark unrealized_conversions produced by this pass. This is used to
26// detect IR this pass failed to completely legalize, and report an error.
27// If everything was successfully legalized, no tagged ops will remain after
28// this pass.
29constexpr StringLiteral kSVELegalizerTag("__arm_sve_legalize_vector_storage__");
30
31/// Definitions:
32///
33/// [1] svbool = vector<...x[16]xi1>, which maps to some multiple of full SVE
34/// predicate registers. A full predicate is the smallest quantity that can be
35/// loaded/stored.
36///
37/// [2] SVE mask = hardware-sized SVE predicate mask, i.e. its trailing
38/// dimension matches the size of a legal SVE vector size (such as
39/// vector<[4]xi1>), but is too small to be stored to memory (i.e smaller than
40/// a svbool).
41
42namespace {
44/// Checks if a vector type is a SVE mask [2].
45bool isSVEMaskType(VectorType type) {
46 return type.getRank() > 0 && type.getElementType().isInteger(1) &&
47 type.getScalableDims().back() && type.getShape().back() < 16 &&
48 llvm::isPowerOf2_32(type.getShape().back()) &&
49 !llvm::is_contained(type.getScalableDims().drop_back(), true);
50}
52VectorType widenScalableMaskTypeToSvbool(VectorType type) {
53 assert(isSVEMaskType(type));
54 return VectorType::Builder(type).setDim(type.getRank() - 1, 16);
55}
57/// A helper for cloning an op and replacing it will a new version, updated by a
58/// callback.
59template <typename TOp, typename TLegalizerCallback>
60void replaceOpWithLegalizedOp(PatternRewriter &rewriter, TOp op,
61 TLegalizerCallback callback) {
62 // Clone the previous op to preserve any properties/attributes.
63 auto newOp = op.clone();
64 rewriter.insert(newOp);
65 rewriter.replaceOp(op, callback(newOp));
66}
67
68/// A helper for cloning an op and replacing it with a new version, updated by a
69/// callback, and an unrealized conversion back to the type of the replaced op.
70template <typename TOp, typename TLegalizerCallback>
71void replaceOpWithUnrealizedConversion(PatternRewriter &rewriter, TOp op,
72 TLegalizerCallback callback) {
73 replaceOpWithLegalizedOp(rewriter, op, [&](TOp newOp) {
74 // Mark our `unrealized_conversion_casts` with a pass label.
75 return UnrealizedConversionCastOp::create(
76 rewriter, op.getLoc(), TypeRange{op.getResult().getType()},
77 ValueRange{callback(newOp)},
79 rewriter.getUnitAttr()));
80 });
81}
82
83/// Extracts the widened SVE memref value (that's legal to store/load) from the
84/// `unrealized_conversion_cast`s added by this pass.
85static FailureOr<Value> getSVELegalizedMemref(Value illegalMemref) {
86 Operation *definingOp = illegalMemref.getDefiningOp();
87 if (!definingOp || !definingOp->hasDiscardableAttr(kSVELegalizerTag))
88 return failure();
89 auto unrealizedConversion =
90 llvm::cast<UnrealizedConversionCastOp>(definingOp);
91 return unrealizedConversion.getOperand(0);
92}
93
94/// The default alignment of an alloca in LLVM may request overaligned sizes for
95/// SVE types, which will fail during stack frame allocation. This rewrite
96/// explicitly adds a reasonable alignment to allocas of scalable types.
97struct RelaxScalableVectorAllocaAlignment
98 : public OpRewritePattern<memref::AllocaOp> {
99 using Base::Base;
100
101 LogicalResult matchAndRewrite(memref::AllocaOp allocaOp,
102 PatternRewriter &rewriter) const override {
103 auto memrefElementType = allocaOp.getType().getElementType();
104 auto vectorType = llvm::dyn_cast<VectorType>(memrefElementType);
105 if (!vectorType || !vectorType.isScalable() || allocaOp.getAlignment())
106 return failure();
107
108 // Set alignment based on the defaults for SVE vectors and predicates.
109 unsigned aligment = vectorType.getElementType().isInteger(1) ? 2 : 16;
110 rewriter.modifyOpInPlace(allocaOp,
111 [&] { allocaOp.setAlignment(aligment); });
112
113 return success();
114 }
115};
116
117/// Replaces allocations of SVE predicates smaller than an svbool [1] (_illegal_
118/// to load/store) with a wider allocation of svbool (_legal_ to load/store)
119/// followed by a tagged unrealized conversion to the original type.
120///
121/// Example
122/// ```
123/// %alloca = memref.alloca() : memref<vector<[4]xi1>>
124/// ```
125/// is rewritten into:
126/// ```
127/// %widened = memref.alloca() {alignment = 1 : i64} : memref<vector<[16]xi1>>
128/// %alloca = builtin.unrealized_conversion_cast %widened
129/// : memref<vector<[16]xi1>> to memref<vector<[4]xi1>>
130/// {__arm_sve_legalize_vector_storage__}
131/// ```
132template <typename AllocLikeOp>
133struct LegalizeSVEMaskAllocation : public OpRewritePattern<AllocLikeOp> {
134 using OpRewritePattern<AllocLikeOp>::OpRewritePattern;
135
136 LogicalResult matchAndRewrite(AllocLikeOp allocLikeOp,
137 PatternRewriter &rewriter) const override {
138 auto vectorType =
139 llvm::dyn_cast<VectorType>(allocLikeOp.getType().getElementType());
140
141 if (!vectorType || !isSVEMaskType(vectorType))
142 return failure();
143
144 // Replace this alloc-like op of an SVE mask [2] with one of a (storable)
145 // svbool mask [1]. A temporary unrealized_conversion_cast is added to the
146 // old type to allow local rewrites.
147 replaceOpWithUnrealizedConversion(
148 rewriter, allocLikeOp, [&](AllocLikeOp newAllocLikeOp) {
149 newAllocLikeOp.getResult().setType(
150 llvm::cast<MemRefType>(newAllocLikeOp.getType().cloneWith(
151 {}, widenScalableMaskTypeToSvbool(vectorType))));
152 return newAllocLikeOp;
153 });
154
155 return success();
156 }
157};
158
159/// Replaces vector.type_casts of unrealized conversions to SVE predicate memref
160/// types that are _illegal_ to load/store from (!= svbool [1]), with type casts
161/// of memref types that are _legal_ to load/store, followed by unrealized
162/// conversions.
163///
164/// Example:
165/// ```
166/// %alloca = builtin.unrealized_conversion_cast %widened
167/// : memref<vector<[16]xi1>> to memref<vector<[8]xi1>>
168/// {__arm_sve_legalize_vector_storage__}
169/// %cast = vector.type_cast %alloca
170/// : memref<vector<3x[8]xi1>> to memref<3xvector<[8]xi1>>
171/// ```
172/// is rewritten into:
173/// ```
174/// %widened_cast = vector.type_cast %widened
175/// : memref<vector<3x[16]xi1>> to memref<3xvector<[16]xi1>>
176/// %cast = builtin.unrealized_conversion_cast %widened_cast
177/// : memref<3xvector<[16]xi1>> to memref<3xvector<[8]xi1>>
178/// {__arm_sve_legalize_vector_storage__}
179/// ```
180struct LegalizeSVEMaskTypeCastConversion
181 : public OpRewritePattern<vector::TypeCastOp> {
182 using Base::Base;
183
184 LogicalResult matchAndRewrite(vector::TypeCastOp typeCastOp,
185 PatternRewriter &rewriter) const override {
186 auto resultType = typeCastOp.getResultMemRefType();
187 auto vectorType = llvm::dyn_cast<VectorType>(resultType.getElementType());
188
189 if (!vectorType || !isSVEMaskType(vectorType))
190 return failure();
191
192 auto legalMemref = getSVELegalizedMemref(typeCastOp.getMemref());
193 if (failed(legalMemref))
194 return failure();
195
196 // Replace this vector.type_cast with one of a (storable) svbool mask [1].
197 replaceOpWithUnrealizedConversion(
198 rewriter, typeCastOp, [&](vector::TypeCastOp newTypeCast) {
199 newTypeCast.setOperand(*legalMemref);
200 newTypeCast.getResult().setType(
201 llvm::cast<MemRefType>(newTypeCast.getType().cloneWith(
202 {}, widenScalableMaskTypeToSvbool(vectorType))));
203 return newTypeCast;
204 });
205
206 return success();
207 }
208};
209
210/// Replaces stores to unrealized conversions to SVE predicate memref types that
211/// are _illegal_ to load/store from (!= svbool [1]), with
212/// `arm_sve.convert_to_svbool`s followed by (legal) wider stores.
213///
214/// Example:
215/// ```
216/// memref.store %mask, %alloca[] : memref<vector<[8]xi1>>
217/// ```
218/// is rewritten into:
219/// ```
220/// %svbool = arm_sve.convert_to_svbool %mask : vector<[8]xi1>
221/// memref.store %svbool, %widened[] : memref<vector<[16]xi1>>
222/// ```
223struct LegalizeSVEMaskStoreConversion
224 : public OpRewritePattern<memref::StoreOp> {
225 using Base::Base;
226
227 LogicalResult matchAndRewrite(memref::StoreOp storeOp,
228 PatternRewriter &rewriter) const override {
229 auto loc = storeOp.getLoc();
230
231 Value valueToStore = storeOp.getValueToStore();
232 auto vectorType = llvm::dyn_cast<VectorType>(valueToStore.getType());
233
234 if (!vectorType || !isSVEMaskType(vectorType))
235 return failure();
236
237 auto legalMemref = getSVELegalizedMemref(storeOp.getMemref());
238 if (failed(legalMemref))
239 return failure();
240
241 auto legalMaskType = widenScalableMaskTypeToSvbool(
242 llvm::cast<VectorType>(valueToStore.getType()));
243 auto convertToSvbool = arm_sve::ConvertToSvboolOp::create(
244 rewriter, loc, legalMaskType, valueToStore);
245 // Replace this store with a conversion to a storable svbool mask [1],
246 // followed by a wider store.
247 replaceOpWithLegalizedOp(rewriter, storeOp,
248 [&](memref::StoreOp newStoreOp) {
249 newStoreOp.setOperand(0, convertToSvbool);
250 newStoreOp.setOperand(1, *legalMemref);
251 return newStoreOp;
252 });
253
254 return success();
255 }
256};
257
258/// Replaces loads from unrealized conversions to SVE predicate memref types
259/// that are _illegal_ to load/store from (!= svbool [1]), types with (legal)
260/// wider loads, followed by `arm_sve.convert_from_svbool`s.
261///
262/// Example:
263/// ```
264/// %reload = memref.load %alloca[] : memref<vector<[4]xi1>>
265/// ```
266/// is rewritten into:
267/// ```
268/// %svbool = memref.load %widened[] : memref<vector<[16]xi1>>
269/// %reload = arm_sve.convert_from_svbool %reload : vector<[4]xi1>
270/// ```
271struct LegalizeSVEMaskLoadConversion : public OpRewritePattern<memref::LoadOp> {
272 using Base::Base;
273
274 LogicalResult matchAndRewrite(memref::LoadOp loadOp,
275 PatternRewriter &rewriter) const override {
276 auto loc = loadOp.getLoc();
277
278 Value loadedMask = loadOp.getResult();
279 auto vectorType = llvm::dyn_cast<VectorType>(loadedMask.getType());
280
281 if (!vectorType || !isSVEMaskType(vectorType))
282 return failure();
283
284 auto legalMemref = getSVELegalizedMemref(loadOp.getMemref());
285 if (failed(legalMemref))
286 return failure();
287
288 auto legalMaskType = widenScalableMaskTypeToSvbool(vectorType);
289 // Replace this load with a legal load of an svbool type, followed by a
290 // conversion back to the original type.
291 replaceOpWithLegalizedOp(rewriter, loadOp, [&](memref::LoadOp newLoadOp) {
292 newLoadOp.setMemRef(*legalMemref);
293 newLoadOp.getResult().setType(legalMaskType);
294 return arm_sve::ConvertFromSvboolOp::create(
295 rewriter, loc, loadedMask.getType(), newLoadOp);
296 });
297
298 return success();
299 }
300};
301
302/// Transforms a `transfer_read` operation so it reads vector of a type that
303/// can be mapped to an LLVM type ("LLVM-legal" type). This is done by
304/// collapsing trailing dimensions so we obtain a vector type with a single
305/// scalable dimension in the rightmost position.
306///
307/// Example:
308/// ```
309/// %v = vector.transfer_read %M[%i, %j, %c0, %c0], %c0_i8
310/// {in_bounds = [false, true, true, true]}
311/// : memref<?x?x2x8xi8>, vector<2x[4]x2x8xi8>
312/// ```
313/// is rewritten to
314/// ```
315/// %collapse_shape = memref.collapse_shape %M [[0], [1, 2, 3]]
316/// : memref<?x?x2x8xi8> into memref<?x?xi8>
317/// %c16 = arith.constant 16 : index
318/// %idx = arith.muli %j, %c16 : index
319/// %0 = vector.transfer_read %collapse_shape[%i, %idx], %c0_i8
320/// {in_bounds = [false, true]}
321/// : memref<?x?xi8>, vector<2x[64]xi8>
322/// %1 = vector.shape_cast %0 : vector<2x[64]xi8> to vector<2x[4]x2x8xi8>
323/// ```
324struct LegalizeTransferRead : public OpRewritePattern<vector::TransferReadOp> {
325 using Base::Base;
326
327 LogicalResult matchAndRewrite(vector::TransferReadOp readOp,
328 PatternRewriter &rewriter) const override {
329
330 // Do not try to transform masked reads. For example, if we have a transfer
331 // to a `vector<[4]x4xi8>` we could have a mask like
332 // 1 1 1 0
333 // 1 1 1 0
334 // 1 1 1 0
335 // 0 0 0 0
336 // Flattening this mask would look like
337 // 1 1 1 0 1 1 1 0 1 1 1 0 0 0 0 0
338 // and we have not yet figured out an efficient way to build such a mask,
339 // neither from the mask operand, nor from the original `vector.create_mask`
340 // operation (if visible at all).
341 if (readOp.isMasked() || readOp.getMask())
342 return rewriter.notifyMatchFailure(readOp,
343 "masked transfers not-supported");
344
345 // General permutation maps are not supported. The issue is with transpose,
346 // broadcast, and other forms of non-identify mapping in the minor
347 // dimensions which is impossible to represent after collapsing (at least
348 // because the resulting "collapsed" maps would have smaller number of
349 // dimension indices).
350 // TODO: We have not had yet the need for it, but some forms of permutation
351 // maps with identity in the minor dimensions voukld be supported, for
352 // example `(i, j, k, p) -> (j, i, k, p)` where we need to collapse only `k`
353 // and `p`.
354 if (!readOp.getPermutationMap().isMinorIdentity())
355 return rewriter.notifyMatchFailure(readOp, "non-identity permutation");
356
357 // We handle transfers of vectors with rank >= 2 and a single scalable
358 // dimension. This transformation aims to transform an LLVM-illegal type
359 // into an LLVM-legal type and one dimensional vectors are already
360 // LLVM-legal, even if scalable. A value of a vector type with more than one
361 // scalable dimension is impossible to represent using a vector type with no
362 // scalable dimensions or a single one. For example a `vector<[4]x[4]xi8>`
363 // would have `4 * 4 * vscale * vscale` elements and this quantity is
364 // impossible to represent as `N` or `N * vscale` (where `N` is a constant).
365 VectorType origVT = readOp.getVectorType();
366 ArrayRef<bool> origScalableDims = origVT.getScalableDims();
367 const int64_t origVRank = origVT.getRank();
368 if (origVRank < 2 || origVT.getNumScalableDims() != 1)
369 return rewriter.notifyMatchFailure(readOp, "wrong dimensions");
370
371 // Number of trailing dimensions to collapse, including the scalable
372 // dimension. Nothing to do if the single scalable dimension is already the
373 // last one.
374 const int64_t numCollapseDims = std::distance(
375 llvm::find(origScalableDims, true), origScalableDims.end());
376 if (numCollapseDims < 2)
377 return rewriter.notifyMatchFailure(readOp,
378 "scalable dimension is trailing");
379
380 // We want a simple memref (not a tensor) with contiguous elements for at
381 // least all the trailing dimensions up to and including the scalable one.
382 auto memTy = dyn_cast<MemRefType>(readOp.getBase().getType());
383 if (!(memTy && memTy.areTrailingDimsContiguous(numCollapseDims)))
384 return rewriter.notifyMatchFailure(
385 readOp, "non-contiguous memref dimensions to collapse");
386
387 // The dimensions to collapse (excluding the scalable one) of the vector and
388 // the memref must match. A dynamic memref dimension is considered
389 // non-matching. The transfers from the dimensions to collapse must be
390 // in-bounds (it follows the corresponding indices would be zero). This
391 // guarantees that the operation transfers a contiguous block
392 // and no padding is necessary.
393 if (!llvm::equal(memTy.getShape().take_back(numCollapseDims - 1),
394 origVT.getShape().take_back(numCollapseDims - 1)))
395 return rewriter.notifyMatchFailure(
396 readOp, "memref and vector dimensions do not match");
397
398 SmallVector<bool> origInBounds = readOp.getInBoundsValues();
399 if (!llvm::all_of(
400 ArrayRef<bool>(origInBounds).take_back(numCollapseDims - 1),
401 [](bool v) { return v; }))
402 return rewriter.notifyMatchFailure(
403 readOp, "out-of-bounds transfer from a dimension to collapse");
404
405 // Collapse the trailing dimensions of the memref.
406 SmallVector<ReassociationIndices> reassoc;
407 for (int64_t i = 0; i < memTy.getRank() - numCollapseDims + 1; ++i)
408 reassoc.push_back({i});
409 for (int64_t i = memTy.getRank() - numCollapseDims + 1; i < memTy.getRank();
410 ++i)
411 reassoc.back().push_back(i);
412 if (!memref::CollapseShapeOp::isGuaranteedCollapsible(memTy, reassoc))
413 return failure();
414 Value collapsedMem = memref::CollapseShapeOp::create(
415 rewriter, readOp.getLoc(), readOp.getBase(), reassoc);
416
417 // Get a vector type with collapsed trailing dimensions.
418 SmallVector<int64_t> shape(origVT.getShape());
419 for (int64_t i = origVRank - numCollapseDims + 1; i < origVRank; ++i)
420 shape[origVRank - numCollapseDims] *= shape[i];
421 shape.pop_back_n(numCollapseDims - 1);
422 auto collapsedVT =
423 VectorType::get(shape, origVT.getElementType(),
424 origScalableDims.drop_back(numCollapseDims - 1));
425
426 // Drop the extra (zero) indices. The index of the scalable dimension now
427 // indexes the collapsed dimension, so scale it by the size of the
428 // dimensions collapsed into it.
429 SmallVector<Value> indices(
430 readOp.getIndices().drop_back(numCollapseDims - 1));
431 Value scale = arith::ConstantIndexOp::create(
432 rewriter, readOp.getLoc(),
433 ShapedType::getNumElements(
434 origVT.getShape().take_back(numCollapseDims - 1)));
435 indices.back() = rewriter.createOrFold<arith::MulIOp>(
436 readOp.getLoc(), indices.back(), scale);
437
438 // Create the new `transfer_read`.
439 auto newReadOp = vector::TransferReadOp::create(
440 rewriter, readOp.getLoc(), collapsedVT, collapsedMem, indices,
441 readOp.getPadding(),
442 ArrayRef<bool>(origInBounds).drop_back(numCollapseDims - 1));
443
444 // Cast back to the original vector type.
445 auto toOrigShape = vector::ShapeCastOp::create(rewriter, readOp.getLoc(),
446 origVT, newReadOp);
447
448 rewriter.replaceOp(readOp, toOrigShape);
449 return success();
450 }
451};
452
453} // namespace
454
456 RewritePatternSet &patterns) {
457 patterns
458 .add<RelaxScalableVectorAllocaAlignment,
459 LegalizeSVEMaskAllocation<memref::AllocaOp>,
460 LegalizeSVEMaskAllocation<memref::AllocOp>,
461 LegalizeSVEMaskTypeCastConversion, LegalizeSVEMaskStoreConversion,
462 LegalizeSVEMaskLoadConversion, LegalizeTransferRead>(
463 patterns.getContext());
464}
465
466namespace {
467struct LegalizeVectorStorage
468 : public arm_sve::impl::LegalizeVectorStorageBase<LegalizeVectorStorage> {
469
470 void runOnOperation() override {
471 RewritePatternSet patterns(&getContext());
473 if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) {
474 signalPassFailure();
475 }
477 target.addDynamicallyLegalOp<UnrealizedConversionCastOp>(
478 [](UnrealizedConversionCastOp unrealizedConversion) {
479 return !unrealizedConversion->hasDiscardableAttr(kSVELegalizerTag);
480 });
481 // This detects if we failed to completely legalize the IR.
482 if (failed(applyPartialConversion(getOperation(), target, {})))
483 signalPassFailure();
484 }
485};
486
487} // namespace
488
490 return std::make_unique<LegalizeVectorStorage>();
491}
return success()
constexpr StringLiteral kSVELegalizerTag("__arm_sve_legalize_vector_storage__")
b getContext())
UnitAttr getUnitAttr()
Definition Builders.cpp:106
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
Operation * insert(Operation *op)
Insert the given operation at the current insertion point and return it.
Definition Builders.cpp:430
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasDiscardableAttr(StringRef name)
Return true if this operation has a discardable attribute with the provided name.
Definition Operation.h:505
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
This is a builder type that keeps local references to arguments.
Builder & setDim(unsigned pos, int64_t val)
Set a dim in shape @pos to val.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:434
void populateLegalizeVectorStoragePatterns(RewritePatternSet &patterns)
Collect a set of patterns to legalize Arm SVE vector storage.
std::unique_ptr< Pass > createLegalizeVectorStoragePass()
Pass to legalize Arm SVE vector storage.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:853
Include the generated interface declarations.
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...