LLVM 24.0.0git
PeepholeOptimizer.cpp
Go to the documentation of this file.
1//===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
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//
9// Perform peephole optimizations on the machine code:
10//
11// - Optimize Extensions
12//
13// Optimization of sign / zero extension instructions. It may be extended to
14// handle other instructions with similar properties.
15//
16// On some targets, some instructions, e.g. X86 sign / zero extension, may
17// leave the source value in the lower part of the result. This optimization
18// will replace some uses of the pre-extension value with uses of the
19// sub-register of the results.
20//
21// - Optimize Comparisons
22//
23// Optimization of comparison instructions. For instance, in this code:
24//
25// sub r1, 1
26// cmp r1, 0
27// bz L1
28//
29// If the "sub" instruction all ready sets (or could be modified to set) the
30// same flag that the "cmp" instruction sets and that "bz" uses, then we can
31// eliminate the "cmp" instruction.
32//
33// Another instance, in this code:
34//
35// sub r1, r3 | sub r1, imm
36// cmp r3, r1 or cmp r1, r3 | cmp r1, imm
37// bge L1
38//
39// If the branch instruction can use flag from "sub", then we can replace
40// "sub" with "subs" and eliminate the "cmp" instruction.
41//
42// - Optimize Loads:
43//
44// Loads that can be folded into a later instruction. A load is foldable
45// if it loads to virtual registers and the virtual register defined has
46// a single use.
47//
48// - Optimize Copies and Bitcast (more generally, target specific copies):
49//
50// Rewrite copies and bitcasts to avoid cross register bank copies
51// when possible.
52// E.g., Consider the following example, where capital and lower
53// letters denote different register file:
54// b = copy A <-- cross-bank copy
55// C = copy b <-- cross-bank copy
56// =>
57// b = copy A <-- cross-bank copy
58// C = copy A <-- same-bank copy
59//
60// E.g., for bitcast:
61// b = bitcast A <-- cross-bank copy
62// C = bitcast b <-- cross-bank copy
63// =>
64// b = bitcast A <-- cross-bank copy
65// C = copy A <-- same-bank copy
66//===----------------------------------------------------------------------===//
67
69#include "llvm/ADT/DenseMap.h"
71#include "llvm/ADT/SmallSet.h"
73#include "llvm/ADT/Statistic.h"
90#include "llvm/MC/LaneBitmask.h"
91#include "llvm/MC/MCInstrDesc.h"
92#include "llvm/Pass.h"
94#include "llvm/Support/Debug.h"
96#include <cassert>
97#include <cstdint>
98#include <utility>
99
100using namespace llvm;
103
104#define DEBUG_TYPE "peephole-opt"
105
106// Optimize Extensions
107static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
108 cl::desc("Aggressive extension optimization"));
109
110static cl::opt<bool>
111 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
112 cl::desc("Disable the peephole optimizer"));
113
114/// Specifiy whether or not the value tracking looks through
115/// complex instructions. When this is true, the value tracker
116/// bails on everything that is not a copy or a bitcast.
117static cl::opt<bool>
118 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
119 cl::desc("Disable advanced copy optimization"));
120
122 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
123 cl::desc("Disable non-allocatable physical register copy optimization"));
124
125// Limit the number of PHI instructions to process
126// in PeepholeOptimizer::getNextSource.
128 RewritePHILimit("rewrite-phi-limit", cl::Hidden, cl::init(10),
129 cl::desc("Limit the length of PHI chains to lookup"));
130
131// Limit the length of recurrence chain when evaluating the benefit of
132// commuting operands.
134 "recurrence-chain-limit", cl::Hidden, cl::init(3),
135 cl::desc("Maximum length of recurrence chain when evaluating the benefit "
136 "of commuting operands"));
137
138STATISTIC(NumReuse, "Number of extension results reused");
139STATISTIC(NumCmps, "Number of compares eliminated");
140STATISTIC(NumImmFold, "Number of move immediate folded");
141STATISTIC(NumLoadFold, "Number of loads folded");
142STATISTIC(NumSelects, "Number of selects optimized");
143STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
144STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
145STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
146
147namespace {
148
149class ValueTrackerResult;
150class RecurrenceInstr;
151
152/// Interface to query instructions amenable to copy rewriting.
153class Rewriter {
154protected:
155 MachineInstr &CopyLike;
156 int CurrentSrcIdx = 0; ///< The index of the source being rewritten.
157public:
158 Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
159 virtual ~Rewriter() = default;
160
161 /// Get the next rewritable source (SrcReg, SrcSubReg) and
162 /// the related value that it affects (DstReg, DstSubReg).
163 /// A source is considered rewritable if its register class and the
164 /// register class of the related DstReg may not be register
165 /// coalescer friendly. In other words, given a copy-like instruction
166 /// not all the arguments may be returned at rewritable source, since
167 /// some arguments are none to be register coalescer friendly.
168 ///
169 /// Each call of this method moves the current source to the next
170 /// rewritable source.
171 /// For instance, let CopyLike be the instruction to rewrite.
172 /// CopyLike has one definition and one source:
173 /// dst.dstSubIdx = CopyLike src.srcSubIdx.
174 ///
175 /// The first call will give the first rewritable source, i.e.,
176 /// the only source this instruction has:
177 /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
178 /// This source defines the whole definition, i.e.,
179 /// (DstReg, DstSubReg) = (dst, dstSubIdx).
180 ///
181 /// The second and subsequent calls will return false, as there is only one
182 /// rewritable source.
183 ///
184 /// \return True if a rewritable source has been found, false otherwise.
185 /// The output arguments are valid if and only if true is returned.
186 virtual bool getNextRewritableSource(RegSubRegPair &Src,
187 RegSubRegPair &Dst) = 0;
188
189 /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
190 /// \return True if the rewriting was possible, false otherwise.
191 virtual bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) = 0;
192};
193
194/// Rewriter for COPY instructions.
195class CopyRewriter : public Rewriter {
196public:
197 CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
198 assert(MI.isCopy() && "Expected copy instruction");
199 }
200 ~CopyRewriter() override = default;
201
202 bool getNextRewritableSource(RegSubRegPair &Src,
203 RegSubRegPair &Dst) override {
204 if (++CurrentSrcIdx > 1)
205 return false;
206
207 // The rewritable source is the argument.
208 const MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
209 Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
210 // What we track are the alternative sources of the definition.
211 const MachineOperand &MODef = CopyLike.getOperand(0);
212 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
213 return true;
214 }
215
216 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
217 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
218 MOSrc.setReg(NewReg);
219 MOSrc.setSubReg(NewSubReg);
220 return true;
221 }
222};
223
224/// Helper class to rewrite uncoalescable copy like instructions
225/// into new COPY (coalescable friendly) instructions.
226class UncoalescableRewriter : public Rewriter {
227 int NumDefs; ///< Number of defs in the bitcast.
228
229public:
230 UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
231 NumDefs = MI.getDesc().getNumDefs();
232 }
233
234 /// \see See Rewriter::getNextRewritableSource()
235 /// All such sources need to be considered rewritable in order to
236 /// rewrite a uncoalescable copy-like instruction. This method return
237 /// each definition that must be checked if rewritable.
238 bool getNextRewritableSource(RegSubRegPair &Src,
239 RegSubRegPair &Dst) override {
240 // Find the next non-dead definition and continue from there.
241 if (CurrentSrcIdx == NumDefs)
242 return false;
243
244 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
245 ++CurrentSrcIdx;
246 if (CurrentSrcIdx == NumDefs)
247 return false;
248 }
249
250 // What we track are the alternative sources of the definition.
251 Src = RegSubRegPair(0, 0);
252 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
253 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
254
255 CurrentSrcIdx++;
256 return true;
257 }
258
259 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
260 return false;
261 }
262};
263
264/// Specialized rewriter for INSERT_SUBREG instruction.
265class InsertSubregRewriter : public Rewriter {
266public:
267 InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
268 assert(MI.isInsertSubreg() && "Invalid instruction");
269 }
270
271 /// \see See Rewriter::getNextRewritableSource()
272 /// Here CopyLike has the following form:
273 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
274 /// Src1 has the same register class has dst, hence, there is
275 /// nothing to rewrite.
276 /// Src2.src2SubIdx, may not be register coalescer friendly.
277 /// Therefore, the first call to this method returns:
278 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
279 /// (DstReg, DstSubReg) = (dst, subIdx).
280 ///
281 /// Subsequence calls will return false.
282 bool getNextRewritableSource(RegSubRegPair &Src,
283 RegSubRegPair &Dst) override {
284 // If we already get the only source we can rewrite, return false.
285 if (CurrentSrcIdx == 2)
286 return false;
287 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
288 CurrentSrcIdx = 2;
289 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
290 Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
291 const MachineOperand &MODef = CopyLike.getOperand(0);
292
293 // We want to track something that is compatible with the
294 // partial definition.
295 if (MODef.getSubReg())
296 // Bail if we have to compose sub-register indices.
297 return false;
298 Dst = RegSubRegPair(MODef.getReg(),
299 (unsigned)CopyLike.getOperand(3).getImm());
300 return true;
301 }
302
303 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
304 if (CurrentSrcIdx != 2)
305 return false;
306 // We are rewriting the inserted reg.
307 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
308 MO.setReg(NewReg);
309 MO.setSubReg(NewSubReg);
310 return true;
311 }
312};
313
314/// Specialized rewriter for EXTRACT_SUBREG instruction.
315class ExtractSubregRewriter : public Rewriter {
316 const TargetInstrInfo &TII;
317
318public:
319 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
320 : Rewriter(MI), TII(TII) {
321 assert(MI.isExtractSubreg() && "Invalid instruction");
322 }
323
324 /// \see Rewriter::getNextRewritableSource()
325 /// Here CopyLike has the following form:
326 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
327 /// There is only one rewritable source: Src.subIdx,
328 /// which defines dst.dstSubIdx.
329 bool getNextRewritableSource(RegSubRegPair &Src,
330 RegSubRegPair &Dst) override {
331 // If we already get the only source we can rewrite, return false.
332 if (CurrentSrcIdx == 1)
333 return false;
334 // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
335 CurrentSrcIdx = 1;
336 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
337 // If we have to compose sub-register indices, bail out.
338 if (MOExtractedReg.getSubReg())
339 return false;
340
341 Src =
342 RegSubRegPair(MOExtractedReg.getReg(), CopyLike.getOperand(2).getImm());
343
344 // We want to track something that is compatible with the definition.
345 const MachineOperand &MODef = CopyLike.getOperand(0);
346 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
347 return true;
348 }
349
350 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
351 // The only source we can rewrite is the input register.
352 if (CurrentSrcIdx != 1)
353 return false;
354
355 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
356
357 // If we find a source that does not require to extract something,
358 // rewrite the operation with a copy.
359 if (!NewSubReg) {
360 // Move the current index to an invalid position.
361 // We do not want another call to this method to be able
362 // to do any change.
363 CurrentSrcIdx = -1;
364 // Rewrite the operation as a COPY.
365 // Get rid of the sub-register index.
366 CopyLike.removeOperand(2);
367 // Morph the operation into a COPY.
368 CopyLike.setDesc(TII.get(TargetOpcode::COPY));
369 return true;
370 }
371 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
372 return true;
373 }
374};
375
376/// Specialized rewriter for REG_SEQUENCE instruction.
377class RegSequenceRewriter : public Rewriter {
378public:
379 RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
380 assert(MI.isRegSequence() && "Invalid instruction");
381 CurrentSrcIdx = -1;
382 }
383
384 /// \see Rewriter::getNextRewritableSource()
385 /// Here CopyLike has the following form:
386 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
387 /// Each call will return a different source, walking all the available
388 /// source.
389 ///
390 /// The first call returns:
391 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
392 /// (DstReg, DstSubReg) = (dst, subIdx1).
393 ///
394 /// The second call returns:
395 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
396 /// (DstReg, DstSubReg) = (dst, subIdx2).
397 ///
398 /// And so on, until all the sources have been traversed, then
399 /// it returns false.
400 bool getNextRewritableSource(RegSubRegPair &Src,
401 RegSubRegPair &Dst) override {
402 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
403 CurrentSrcIdx += 2;
404 if (static_cast<unsigned>(CurrentSrcIdx) >= CopyLike.getNumOperands())
405 return false;
406
407 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
408 Src.Reg = MOInsertedReg.getReg();
409 Src.SubReg = MOInsertedReg.getSubReg();
410
411 // We want to track something that is compatible with the related
412 // partial definition.
413 Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
414
415 const MachineOperand &MODef = CopyLike.getOperand(0);
416 Dst.Reg = MODef.getReg();
417 assert(MODef.getSubReg() == 0 && "cannot have subregister def in SSA");
418 return true;
419 }
420
421 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
422 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
423 MO.setReg(NewReg);
424 MO.setSubReg(NewSubReg);
425 return true;
426 }
427};
428
429class PeepholeOptimizer : private MachineFunction::Delegate {
430 const TargetInstrInfo *TII = nullptr;
431 const TargetRegisterInfo *TRI = nullptr;
432 MachineRegisterInfo *MRI = nullptr;
433 MachineDominatorTree *DT = nullptr; // Machine dominator tree
434 MachineLoopInfo *MLI = nullptr;
435
436public:
437 PeepholeOptimizer(MachineDominatorTree *DT, MachineLoopInfo *MLI)
438 : DT(DT), MLI(MLI) {}
439
440 bool run(MachineFunction &MF);
441 /// Track Def -> Use info used for rewriting copies.
442 using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
443
444 /// Sequence of instructions that formulate recurrence cycle.
445 using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
446
447private:
448 bool optimizeCmpInstr(MachineInstr &MI, MachineFunction &MF,
449 SmallPtrSet<MachineInstr *, 16> &LocalMIs);
450 bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
451 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
452 bool optimizeSelect(MachineInstr &MI,
453 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
454 bool optimizeCondBranch(MachineInstr &MI);
455
456 bool optimizeCoalescableCopyImpl(Rewriter &&CpyRewriter);
457 bool optimizeCoalescableCopy(MachineInstr &MI);
458 bool optimizeUncoalescableCopy(MachineInstr &MI,
459 SmallPtrSetImpl<MachineInstr *> &LocalMIs);
460 bool optimizeRecurrence(MachineInstr &PHI);
461 bool findNextSource(const TargetRegisterClass *DefRC, unsigned DefSubReg,
462 RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
463 bool isMoveImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
464 DenseMap<Register, MachineInstr *> &ImmDefMIs);
465 bool foldImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
466 DenseMap<Register, MachineInstr *> &ImmDefMIs,
467 bool &Deleted);
468
469 /// Finds recurrence cycles, but only ones that formulated around
470 /// a def operand and a use operand that are tied. If there is a use
471 /// operand commutable with the tied use operand, find recurrence cycle
472 /// along that operand as well.
473 bool findTargetRecurrence(Register Reg,
474 const SmallSet<Register, 2> &TargetReg,
475 RecurrenceCycle &RC);
476
477 /// If copy instruction \p MI is a virtual register copy or a copy of a
478 /// constant physical register to a virtual register, track it in the
479 /// set CopySrcMIs. If this virtual register was previously seen as a
480 /// copy, replace the uses of this copy with the previously seen copy's
481 /// destination register.
482 bool foldRedundantCopy(MachineInstr &MI);
483
484 /// Is the register \p Reg a non-allocatable physical register?
485 bool isNAPhysCopy(Register Reg);
486
487 /// If copy instruction \p MI is a non-allocatable virtual<->physical
488 /// register copy, track it in the \p NAPhysToVirtMIs map. If this
489 /// non-allocatable physical register was previously copied to a virtual
490 /// registered and hasn't been clobbered, the virt->phys copy can be
491 /// deleted.
492 bool
493 foldRedundantNAPhysCopy(MachineInstr &MI,
494 DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs);
495
496 bool isLoadFoldable(MachineInstr &MI,
497 SmallSet<Register, 16> &FoldAsLoadDefCandidates);
498
499 /// Try to fold the load defined by \p FoldReg into \p MI using
500 /// TII->optimizeLoadInstr. On success, updates \p LocalMIs, erases the old
501 /// instructions, and returns the replacement; returns nullptr otherwise.
502 MachineInstr *foldLoadInto(MachineFunction &MF, MachineInstr &MI,
503 Register FoldReg,
504 SmallPtrSet<MachineInstr *, 16> &LocalMIs);
505
506 /// Check whether \p MI is understood by the register coalescer
507 /// but may require some rewriting.
508 static bool isCoalescableCopy(const MachineInstr &MI) {
509 // SubregToRegs are not interesting, because they are already register
510 // coalescer friendly.
511 return MI.isCopy() ||
512 (!DisableAdvCopyOpt && (MI.isRegSequence() || MI.isInsertSubreg() ||
513 MI.isExtractSubreg()));
514 }
515
516 /// Check whether \p MI is a copy like instruction that is
517 /// not recognized by the register coalescer.
518 static bool isUncoalescableCopy(const MachineInstr &MI) {
519 return MI.isBitcast() || (!DisableAdvCopyOpt && (MI.isRegSequenceLike() ||
520 MI.isInsertSubregLike() ||
521 MI.isExtractSubregLike()));
522 }
523
524 MachineInstr &rewriteSource(MachineInstr &CopyLike, RegSubRegPair Def,
525 RewriteMapTy &RewriteMap);
526
527 // Set of copies to virtual registers keyed by source register. Never
528 // holds any physreg which requires def tracking.
529 DenseMap<RegSubRegPair, MachineInstr *> CopySrcMIs;
530
531 // MachineFunction::Delegate implementation. Used to maintain CopySrcMIs.
532 void MF_HandleInsertion(MachineInstr &MI) override {}
533
534 bool getCopySrc(MachineInstr &MI, RegSubRegPair &SrcPair) {
535 if (!MI.isCopy())
536 return false;
537
538 Register SrcReg = MI.getOperand(1).getReg();
539 unsigned SrcSubReg = MI.getOperand(1).getSubReg();
540 if (!SrcReg.isVirtual() && !MRI->isConstantPhysReg(SrcReg))
541 return false;
542
543 SrcPair = RegSubRegPair(SrcReg, SrcSubReg);
544 return true;
545 }
546
547 // If a COPY instruction is to be deleted or changed, we should also remove
548 // it from CopySrcMIs.
549 void deleteChangedCopy(MachineInstr &MI) {
550 RegSubRegPair SrcPair;
551 if (!getCopySrc(MI, SrcPair))
552 return;
553
554 auto It = CopySrcMIs.find(SrcPair);
555 if (It != CopySrcMIs.end() && It->second == &MI)
556 CopySrcMIs.erase(It);
557 }
558
559 void MF_HandleRemoval(MachineInstr &MI) override { deleteChangedCopy(MI); }
560
561 void MF_HandleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID) override {
562 deleteChangedCopy(MI);
563 }
564};
565
566class PeepholeOptimizerLegacy : public MachineFunctionPass {
567public:
568 static char ID; // Pass identification
569
570 PeepholeOptimizerLegacy() : MachineFunctionPass(ID) {}
571
572 bool runOnMachineFunction(MachineFunction &MF) override;
573
574 void getAnalysisUsage(AnalysisUsage &AU) const override {
575 AU.setPreservesCFG();
577 AU.addRequired<MachineLoopInfoWrapperPass>();
578 if (Aggressive) {
579 AU.addRequired<MachineDominatorTreeWrapperPass>();
580 }
581 }
582
583 MachineFunctionProperties getRequiredProperties() const override {
584 return MachineFunctionProperties().setIsSSA();
585 }
586};
587
588/// Helper class to hold instructions that are inside recurrence cycles.
589/// The recurrence cycle is formulated around 1) a def operand and its
590/// tied use operand, or 2) a def operand and a use operand that is commutable
591/// with another use operand which is tied to the def operand. In the latter
592/// case, index of the tied use operand and the commutable use operand are
593/// maintained with CommutePair.
594class RecurrenceInstr {
595public:
596 using IndexPair = std::pair<unsigned, unsigned>;
597
598 RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
599 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
600 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
601
602 MachineInstr *getMI() const { return MI; }
603 std::optional<IndexPair> getCommutePair() const { return CommutePair; }
604
605private:
606 MachineInstr *MI;
607 std::optional<IndexPair> CommutePair;
608};
609
610/// Helper class to hold a reply for ValueTracker queries.
611/// Contains the returned sources for a given search and the instructions
612/// where the sources were tracked from.
613class ValueTrackerResult {
614private:
615 /// Track all sources found by one ValueTracker query.
617
618 /// Instruction using the sources in 'RegSrcs'.
619 const MachineInstr *Inst = nullptr;
620
621public:
622 ValueTrackerResult() = default;
623
624 ValueTrackerResult(Register Reg, unsigned SubReg) { addSource(Reg, SubReg); }
625
626 bool isValid() const { return getNumSources() > 0; }
627
628 void setInst(const MachineInstr *I) { Inst = I; }
629 const MachineInstr *getInst() const { return Inst; }
630
631 void clear() {
632 RegSrcs.clear();
633 Inst = nullptr;
634 }
635
636 void addSource(Register SrcReg, unsigned SrcSubReg) {
637 RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
638 }
639
640 void setSource(int Idx, Register SrcReg, unsigned SrcSubReg) {
641 assert(Idx < getNumSources() && "Reg pair source out of index");
642 RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
643 }
644
645 int getNumSources() const { return RegSrcs.size(); }
646
647 RegSubRegPair getSrc(int Idx) const { return RegSrcs[Idx]; }
648
649 Register getSrcReg(int Idx) const {
650 assert(Idx < getNumSources() && "Reg source out of index");
651 return RegSrcs[Idx].Reg;
652 }
653
654 unsigned getSrcSubReg(int Idx) const {
655 assert(Idx < getNumSources() && "SubReg source out of index");
656 return RegSrcs[Idx].SubReg;
657 }
658
659 bool operator==(const ValueTrackerResult &Other) const {
660 if (Other.getInst() != getInst())
661 return false;
662
663 if (Other.getNumSources() != getNumSources())
664 return false;
665
666 for (int i = 0, e = Other.getNumSources(); i != e; ++i)
667 if (Other.getSrcReg(i) != getSrcReg(i) ||
668 Other.getSrcSubReg(i) != getSrcSubReg(i))
669 return false;
670 return true;
671 }
672};
673
674/// Helper class to track the possible sources of a value defined by
675/// a (chain of) copy related instructions.
676/// Given a definition (instruction and definition index), this class
677/// follows the use-def chain to find successive suitable sources.
678/// The given source can be used to rewrite the definition into
679/// def = COPY src.
680///
681/// For instance, let us consider the following snippet:
682/// v0 =
683/// v2 = INSERT_SUBREG v1, v0, sub0
684/// def = COPY v2.sub0
685///
686/// Using a ValueTracker for def = COPY v2.sub0 will give the following
687/// suitable sources:
688/// v2.sub0 and v0.
689/// Then, def can be rewritten into def = COPY v0.
690class ValueTracker {
691private:
692 /// The current point into the use-def chain.
693 const MachineInstr *Def = nullptr;
694
695 /// The index of the definition in Def.
696 unsigned DefIdx = 0;
697
698 /// The sub register index of the definition.
699 unsigned DefSubReg;
700
701 /// The register where the value can be found.
702 Register Reg;
703
704 /// MachineRegisterInfo used to perform tracking.
705 const MachineRegisterInfo &MRI;
706
707 /// Optional TargetInstrInfo used to perform some complex tracking.
708 const TargetInstrInfo *TII;
709
710 /// Dispatcher to the right underlying implementation of getNextSource.
711 ValueTrackerResult getNextSourceImpl();
712
713 /// Specialized version of getNextSource for Copy instructions.
714 ValueTrackerResult getNextSourceFromCopy();
715
716 /// Specialized version of getNextSource for Bitcast instructions.
717 ValueTrackerResult getNextSourceFromBitcast();
718
719 /// Specialized version of getNextSource for RegSequence instructions.
720 ValueTrackerResult getNextSourceFromRegSequence();
721
722 /// Specialized version of getNextSource for InsertSubreg instructions.
723 ValueTrackerResult getNextSourceFromInsertSubreg();
724
725 /// Specialized version of getNextSource for ExtractSubreg instructions.
726 ValueTrackerResult getNextSourceFromExtractSubreg();
727
728 /// Specialized version of getNextSource for SubregToReg instructions.
729 ValueTrackerResult getNextSourceFromSubregToReg();
730
731 /// Specialized version of getNextSource for PHI instructions.
732 ValueTrackerResult getNextSourceFromPHI();
733
734public:
735 /// Create a ValueTracker instance for the value defined by \p Reg.
736 /// \p DefSubReg represents the sub register index the value tracker will
737 /// track. It does not need to match the sub register index used in the
738 /// definition of \p Reg.
739 /// If \p Reg is a physical register, a value tracker constructed with
740 /// this constructor will not find any alternative source.
741 /// Indeed, when \p Reg is a physical register that constructor does not
742 /// know which definition of \p Reg it should track.
743 /// Use the next constructor to track a physical register.
744 ValueTracker(Register Reg, unsigned DefSubReg, const MachineRegisterInfo &MRI,
745 const TargetInstrInfo *TII = nullptr)
746 : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
747 if (!Reg.isPhysical()) {
748 MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
749 if (DI != MRI.def_end()) {
750 Def = DI->getParent();
751 DefIdx = DI.getOperandNo();
752 }
753 }
754 }
755
756 /// Following the use-def chain, get the next available source
757 /// for the tracked value.
758 /// \return A ValueTrackerResult containing a set of registers
759 /// and sub registers with tracked values. A ValueTrackerResult with
760 /// an empty set of registers means no source was found.
761 ValueTrackerResult getNextSource();
762};
763
764} // end anonymous namespace
765
766char PeepholeOptimizerLegacy::ID = 0;
767
768char &llvm::PeepholeOptimizerLegacyID = PeepholeOptimizerLegacy::ID;
769
770INITIALIZE_PASS_BEGIN(PeepholeOptimizerLegacy, DEBUG_TYPE,
771 "Peephole Optimizations", false, false)
774INITIALIZE_PASS_END(PeepholeOptimizerLegacy, DEBUG_TYPE,
775 "Peephole Optimizations", false, false)
776
777/// If instruction is a copy-like instruction, i.e. it reads a single register
778/// and writes a single register and it does not modify the source, and if the
779/// source value is preserved as a sub-register of the result, then replace all
780/// reachable uses of the source with the subreg of the result.
781///
782/// Do not generate an EXTRACT that is used only in a debug use, as this changes
783/// the code. Since this code does not currently share EXTRACTs, just ignore all
784/// debug uses.
785bool PeepholeOptimizer::optimizeExtInstr(
787 SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
788 Register SrcReg, DstReg;
789 unsigned SubIdx;
790 if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
791 return false;
792
793 if (DstReg.isPhysical() || SrcReg.isPhysical())
794 return false;
795
796 if (MRI->hasOneNonDBGUse(SrcReg))
797 // No other uses.
798 return false;
799
800 // Ensure DstReg can get a register class that actually supports
801 // sub-registers. Don't change the class until we commit.
802 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
803 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
804 if (!DstRC)
805 return false;
806
807 // The ext instr may be operating on a sub-register of SrcReg as well.
808 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
809 // register.
810 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
811 // SrcReg:SubIdx should be replaced.
812 bool UseSrcSubIdx =
813 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
814
815 // The source has other uses. See if we can replace the other uses with use of
816 // the result of the extension.
818 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
819 ReachedBBs.insert(UI.getParent());
820
821 // Uses that are in the same BB of uses of the result of the instruction.
823
824 // Uses that the result of the instruction can reach.
826
827 bool ExtendLife = true;
828 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
829 MachineInstr *UseMI = UseMO.getParent();
830 if (UseMI == &MI)
831 continue;
832
833 if (UseMI->isPHI()) {
834 ExtendLife = false;
835 continue;
836 }
837
838 // Only accept uses of SrcReg:SubIdx.
839 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
840 continue;
841
842 // It's an error to translate this:
843 //
844 // %reg1025 = <sext> %reg1024
845 // ...
846 // %reg1026 = SUBREG_TO_REG %reg1024, 4
847 //
848 // into this:
849 //
850 // %reg1025 = <sext> %reg1024
851 // ...
852 // %reg1027 = COPY %reg1025:4
853 // %reg1026 = SUBREG_TO_REG %reg1027, 4
854 //
855 // The problem here is that SUBREG_TO_REG is there to assert that an
856 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
857 // the COPY here, it will give us the value after the <sext>, not the
858 // original value of %reg1024 before <sext>.
859 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
860 continue;
861
862 MachineBasicBlock *UseMBB = UseMI->getParent();
863 if (UseMBB == &MBB) {
864 // Local uses that come after the extension.
865 if (!LocalMIs.count(UseMI))
866 Uses.push_back(&UseMO);
867 } else if (ReachedBBs.count(UseMBB)) {
868 // Non-local uses where the result of the extension is used. Always
869 // replace these unless it's a PHI.
870 Uses.push_back(&UseMO);
871 } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
872 // We may want to extend the live range of the extension result in order
873 // to replace these uses.
874 ExtendedUses.push_back(&UseMO);
875 } else {
876 // Both will be live out of the def MBB anyway. Don't extend live range of
877 // the extension result.
878 ExtendLife = false;
879 break;
880 }
881 }
882
883 if (ExtendLife && !ExtendedUses.empty())
884 // Extend the liveness of the extension result.
885 Uses.append(ExtendedUses.begin(), ExtendedUses.end());
886
887 // Now replace all uses.
888 bool Changed = false;
889 if (!Uses.empty()) {
890 SmallPtrSet<MachineBasicBlock *, 4> PHIBBs;
891
892 // Look for PHI uses of the extended result, we don't want to extend the
893 // liveness of a PHI input. It breaks all kinds of assumptions down
894 // stream. A PHI use is expected to be the kill of its source values.
895 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
896 if (UI.isPHI())
897 PHIBBs.insert(UI.getParent());
898
899 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
900 for (MachineOperand *UseMO : Uses) {
901 MachineInstr *UseMI = UseMO->getParent();
902 MachineBasicBlock *UseMBB = UseMI->getParent();
903 if (PHIBBs.count(UseMBB))
904 continue;
905
906 // About to add uses of DstReg, clear DstReg's kill flags.
907 if (!Changed) {
908 MRI->clearKillFlags(DstReg);
909 MRI->constrainRegClass(DstReg, DstRC);
910 }
911
912 // SubReg defs are illegal in machine SSA phase,
913 // we should not generate SubReg defs.
914 //
915 // For example, for the instructions:
916 //
917 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
918 // %3:gprc_and_gprc_nor0 = COPY %0.sub_32:g8rc
919 //
920 // We should generate:
921 //
922 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
923 // %6:gprc_and_gprc_nor0 = COPY %1.sub_32:g8rc_and_g8rc_nox0
924 // %3:gprc_and_gprc_nor0 = COPY %6:gprc_and_gprc_nor0
925 //
926 if (UseSrcSubIdx)
927 RC = MRI->getRegClass(UseMI->getOperand(0).getReg());
928
929 Register NewVR = MRI->createVirtualRegister(RC);
930 BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
931 TII->get(TargetOpcode::COPY), NewVR)
932 .addReg(DstReg, {}, SubIdx);
933 if (UseSrcSubIdx)
934 UseMO->setSubReg(0);
935
936 UseMO->setReg(NewVR);
937 ++NumReuse;
938 Changed = true;
939 }
940 }
941
942 return Changed;
943}
944
945/// If the instruction is a compare and the previous instruction it's comparing
946/// against already sets (or could be modified to set) the same flag as the
947/// compare, then we can remove the comparison and use the flag from the
948/// previous instruction.
949bool PeepholeOptimizer::optimizeCmpInstr(
952 // If this instruction is a comparison against zero and isn't comparing a
953 // physical register, we can try to optimize it.
954 Register SrcReg, SrcReg2;
955 int64_t CmpMask, CmpValue;
956 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
957 SrcReg.isPhysical() || SrcReg2.isPhysical())
958 return false;
959
960 // Attempt to optimize the comparison instruction.
961 LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI);
962 if (!TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI))
963 return false;
964
965 LLVM_DEBUG(dbgs() << " -> Successfully optimized compare!\n");
966 LocalMIs.erase(&MI);
967 ++NumCmps;
968
969 // The eliminated compare may have been the extra use preventing a
970 // load from being folded into the flag-setting instruction.
971 if (SrcReg.isVirtual() && MRI->hasOneNonDBGUser(SrcReg)) {
972 MachineInstr *FlagProducer = MRI->use_nodbg_begin(SrcReg)->getParent();
973 MachineInstr *LoadMI = MRI->getVRegDef(SrcReg);
974 // No store between LoadMI and FlagProducer that could change the value.
975 if (LocalMIs.count(FlagProducer) && LoadMI && LoadMI->canFoldAsLoad() &&
976 LoadMI->mayLoad() && LocalMIs.count(LoadMI) &&
978 make_range(std::next(LoadMI->getIterator()),
979 FlagProducer->getIterator()),
980 [](const MachineInstr &I) { return I.isLoadFoldBarrier(); }))
981 foldLoadInto(MF, *FlagProducer, SrcReg, LocalMIs);
982 }
983
984 return true;
985}
986
987/// Optimize a select instruction.
988bool PeepholeOptimizer::optimizeSelect(
989 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
990 assert(MI.isSelect() && "Should only be called when MI->isSelect() is true");
991 if (!TII->optimizeSelect(MI, LocalMIs))
992 return false;
993 LLVM_DEBUG(dbgs() << "Deleting select: " << MI);
994 MI.eraseFromParent();
995 ++NumSelects;
996 return true;
997}
998
999/// Check if a simpler conditional branch can be generated.
1000bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
1001 return TII->optimizeCondBranch(MI);
1002}
1003
1004/// Try to find a better source value that shares the same register file to
1005/// replace \p RegSubReg in an instruction like
1006/// `DefRC.DefSubReg = COPY RegSubReg`
1007///
1008/// When true is returned, the \p RewriteMap can be used by the client to
1009/// retrieve all Def -> Use along the way up to the next source. Any found
1010/// Use that is not itself a key for another entry, is the next source to
1011/// use. During the search for the next source, multiple sources can be found
1012/// given multiple incoming sources of a PHI instruction. In this case, we
1013/// look in each PHI source for the next source; all found next sources must
1014/// share the same register file as \p Reg and \p SubReg. The client should
1015/// then be capable to rewrite all intermediate PHIs to get the next source.
1016/// \return False if no alternative sources are available. True otherwise.
1017bool PeepholeOptimizer::findNextSource(const TargetRegisterClass *DefRC,
1018 unsigned DefSubReg,
1019 RegSubRegPair RegSubReg,
1020 RewriteMapTy &RewriteMap) {
1021 // Do not try to find a new source for a physical register.
1022 // So far we do not have any motivating example for doing that.
1023 // Thus, instead of maintaining untested code, we will revisit that if
1024 // that changes at some point.
1025 Register Reg = RegSubReg.Reg;
1026 RegSubRegPair CurSrcPair = RegSubReg;
1027 SmallVector<RegSubRegPair, 4> SrcToLook = {CurSrcPair};
1028
1029 unsigned PHICount = 0;
1030
1031 // Remember the last suitable source in case the search meets an invalid
1032 // source.
1033 bool FoundSuitable = false;
1034 RegSubRegPair SuitablePair = RegSubReg;
1035 bool Aborted = false;
1036 do {
1037 CurSrcPair = SrcToLook.pop_back_val();
1038 // As explained above, do not handle physical registers
1039 if (CurSrcPair.Reg.isPhysical()) {
1040 Aborted = true;
1041 break;
1042 }
1043
1044 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
1045
1046 // Follow the chain of copies until we find a more suitable source, a phi
1047 // or have to abort.
1048 while (true) {
1049 ValueTrackerResult Res = ValTracker.getNextSource();
1050 // Abort at the end of a chain (without finding a suitable source).
1051 if (!Res.isValid()) {
1052 Aborted = true;
1053 break;
1054 }
1055
1056 // Insert the Def -> Use entry for the recently found source.
1057 auto [InsertPt, WasInserted] = RewriteMap.try_emplace(CurSrcPair, Res);
1058
1059 if (!WasInserted) {
1060 const ValueTrackerResult &CurSrcRes = InsertPt->second;
1061
1062 assert(CurSrcRes == Res && "ValueTrackerResult found must match");
1063 // An existent entry with multiple sources is a PHI cycle we must avoid.
1064 // Otherwise it's an entry with a valid next source we already found.
1065 if (CurSrcRes.getNumSources() > 1) {
1067 << "findNextSource: found PHI cycle, aborting...\n");
1068 Aborted = true;
1069 }
1070 break;
1071 }
1072
1073 // ValueTrackerResult usually have one source unless it's the result from
1074 // a PHI instruction. Add the found PHI edges to be looked up further.
1075 unsigned NumSrcs = Res.getNumSources();
1076 if (NumSrcs > 1) {
1077 PHICount++;
1078 if (PHICount >= RewritePHILimit) {
1079 LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
1080 Aborted = true;
1081 break;
1082 }
1083
1084 for (unsigned i = 0; i < NumSrcs; ++i)
1085 SrcToLook.push_back(Res.getSrc(i));
1086 break;
1087 }
1088
1089 CurSrcPair = Res.getSrc(0);
1090 // Do not extend the live-ranges of physical registers as they add
1091 // constraints to the register allocator. Moreover, if we want to extend
1092 // the live-range of a physical register, unlike SSA virtual register,
1093 // we will have to check that they aren't redefine before the related use.
1094 if (CurSrcPair.Reg.isPhysical()) {
1095 Aborted = true;
1096 break;
1097 }
1098
1099 // Keep following the chain if the value isn't any better yet.
1100 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
1101 if (!TRI->shouldRewriteCopySrc(DefRC, DefSubReg, SrcRC,
1102 CurSrcPair.SubReg))
1103 continue;
1104
1105 // We currently cannot deal with subreg operands on PHI instructions
1106 // (see insertPHI()).
1107 if (PHICount > 0 && CurSrcPair.SubReg != 0)
1108 continue;
1109
1110 // Don't stop at the first suitable source if it is still a subregister;
1111 // keep tracing to try to reach a deeper source. Remember it.
1112 if (CurSrcPair.SubReg != 0) {
1113 SuitablePair = CurSrcPair;
1114 FoundSuitable = true;
1115 continue;
1116 }
1117
1118 // We found a suitable source, and are done with this chain.
1119 break;
1120 }
1121
1122 // A dead-ended chain ends all exploration
1123 if (Aborted)
1124 break;
1125 } while (!SrcToLook.empty());
1126
1127 if (Aborted) {
1128 // If aborted with an invalid source, restore the suitable so far, if any.
1129 if (!FoundSuitable)
1130 return false;
1131
1132 CurSrcPair = SuitablePair;
1133 RewriteMap.erase(SuitablePair);
1134 }
1135
1136 // If we did not find a more suitable source, there is nothing to optimize.
1137 return CurSrcPair.Reg != Reg;
1138}
1139
1140/// Insert a PHI instruction with incoming edges \p SrcRegs that are
1141/// guaranteed to have the same register class. This is necessary whenever we
1142/// successfully traverse a PHI instruction and find suitable sources coming
1143/// from its edges. By inserting a new PHI, we provide a rewritten PHI def
1144/// suitable to be used in a new COPY instruction.
1146 const TargetInstrInfo &TII,
1147 const SmallVectorImpl<RegSubRegPair> &SrcRegs,
1148 MachineInstr &OrigPHI) {
1149 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
1150
1151 const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
1152 // NewRC is only correct if no subregisters are involved. findNextSource()
1153 // should have rejected those cases already.
1154 assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
1155 Register NewVR = MRI.createVirtualRegister(NewRC);
1156 MachineBasicBlock *MBB = OrigPHI.getParent();
1157 MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
1158 TII.get(TargetOpcode::PHI), NewVR);
1159
1160 unsigned MBBOpIdx = 2;
1161 for (const RegSubRegPair &RegPair : SrcRegs) {
1162 MIB.addReg(RegPair.Reg, {}, RegPair.SubReg);
1163 MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
1164 // Since we're extended the lifetime of RegPair.Reg, clear the
1165 // kill flags to account for that and make RegPair.Reg reaches
1166 // the new PHI.
1167 MRI.clearKillFlags(RegPair.Reg);
1168 MBBOpIdx += 2;
1169 }
1170
1171 return *MIB;
1172}
1173
1174/// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find
1175/// the new source to use for rewrite. If \p HandleMultipleSources is true and
1176/// multiple sources for a given \p Def are found along the way, we found a
1177/// PHI instructions that needs to be rewritten.
1178/// TODO: HandleMultipleSources should be removed once we test PHI handling
1179/// with coalescable copies.
1180static RegSubRegPair
1182 RegSubRegPair Def,
1183 const PeepholeOptimizer::RewriteMapTy &RewriteMap,
1184 bool HandleMultipleSources = true) {
1185 RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
1186 while (true) {
1187 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
1188 // If there are no entries on the map, LookupSrc is the new source.
1189 if (!Res.isValid())
1190 return LookupSrc;
1191
1192 // There's only one source for this definition, keep searching...
1193 unsigned NumSrcs = Res.getNumSources();
1194 if (NumSrcs == 1) {
1195 LookupSrc.Reg = Res.getSrcReg(0);
1196 LookupSrc.SubReg = Res.getSrcSubReg(0);
1197 continue;
1198 }
1199
1200 // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1201 if (!HandleMultipleSources)
1202 break;
1203
1204 // Multiple sources, recurse into each source to find a new source
1205 // for it. Then, rewrite the PHI accordingly to its new edges.
1207 for (unsigned i = 0; i < NumSrcs; ++i) {
1208 RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
1209 NewPHISrcs.push_back(
1210 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
1211 }
1212
1213 // Build the new PHI node and return its def register as the new source.
1214 MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
1215 MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
1216 LLVM_DEBUG(dbgs() << "-- getNewSource\n");
1217 LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI);
1218 LLVM_DEBUG(dbgs() << " With: " << NewPHI);
1219 const MachineOperand &MODef = NewPHI.getOperand(0);
1220 return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
1221 }
1222
1223 return RegSubRegPair(0, 0);
1224}
1225
1226bool PeepholeOptimizer::optimizeCoalescableCopyImpl(Rewriter &&CpyRewriter) {
1227 bool Changed = false;
1228 // Get the right rewriter for the current copy.
1229 // Rewrite each rewritable source.
1230 RegSubRegPair Dst;
1231 RegSubRegPair TrackPair;
1232 while (CpyRewriter.getNextRewritableSource(TrackPair, Dst)) {
1233 if (Dst.Reg.isPhysical()) {
1234 // Do not try to find a new source for a physical register.
1235 // So far we do not have any motivating example for doing that.
1236 // Thus, instead of maintaining untested code, we will revisit that if
1237 // that changes at some point.
1238 continue;
1239 }
1240
1241 const TargetRegisterClass *DefRC = MRI->getRegClass(Dst.Reg);
1242
1243 // Keep track of PHI nodes and its incoming edges when looking for sources.
1244 RewriteMapTy RewriteMap;
1245 // Try to find a more suitable source. If we failed to do so, or get the
1246 // actual source, move to the next source.
1247 if (!findNextSource(DefRC, Dst.SubReg, TrackPair, RewriteMap))
1248 continue;
1249
1250 // Get the new source to rewrite. TODO: Only enable handling of multiple
1251 // sources (PHIs) once we have a motivating example and testcases for it.
1252 RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
1253 /*HandleMultipleSources=*/false);
1254 assert(TrackPair.Reg != NewSrc.Reg &&
1255 "should not rewrite source to original value");
1256 if (!NewSrc.Reg)
1257 continue;
1258
1259 if (NewSrc.SubReg) {
1260 // Verify the register class supports the subregister index. ARM's
1261 // copy-like queries return register:subreg pairs where the register's
1262 // current class does not directly support the subregister index.
1263 const TargetRegisterClass *RC = MRI->getRegClass(NewSrc.Reg);
1264 const TargetRegisterClass *WithSubRC =
1265 TRI->getSubClassWithSubReg(RC, NewSrc.SubReg);
1266 if (!MRI->constrainRegClass(NewSrc.Reg, WithSubRC))
1267 continue;
1268 Changed = true;
1269 }
1270
1271 // Rewrite source.
1272 if (CpyRewriter.RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1273 // We may have extended the live-range of NewSrc, account for that.
1274 MRI->clearKillFlags(NewSrc.Reg);
1275 Changed = true;
1276 }
1277 }
1278
1279 // TODO: We could have a clean-up method to tidy the instruction.
1280 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1281 // => v0 = COPY v1
1282 // Currently we haven't seen motivating example for that and we
1283 // want to avoid untested code.
1284 NumRewrittenCopies += Changed;
1285 return Changed;
1286}
1287
1288/// Optimize generic copy instructions to avoid cross register bank copy.
1289/// The optimization looks through a chain of copies and tries to find a source
1290/// that has a compatible register class.
1291/// Two register classes are considered to be compatible if they share the same
1292/// register bank.
1293/// New copies issued by this optimization are register allocator
1294/// friendly. This optimization does not remove any copy as it may
1295/// overconstrain the register allocator, but replaces some operands
1296/// when possible.
1297/// \pre isCoalescableCopy(*MI) is true.
1298/// \return True, when \p MI has been rewritten. False otherwise.
1299bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
1300 assert(isCoalescableCopy(MI) && "Invalid argument");
1301 assert(MI.getDesc().getNumDefs() == 1 &&
1302 "Coalescer can understand multiple defs?!");
1303 const MachineOperand &MODef = MI.getOperand(0);
1304 // Do not rewrite physical definitions.
1305 if (MODef.getReg().isPhysical())
1306 return false;
1307
1308 switch (MI.getOpcode()) {
1309 case TargetOpcode::COPY:
1310 return optimizeCoalescableCopyImpl(CopyRewriter(MI));
1311 case TargetOpcode::INSERT_SUBREG:
1312 return optimizeCoalescableCopyImpl(InsertSubregRewriter(MI));
1313 case TargetOpcode::EXTRACT_SUBREG:
1314 return optimizeCoalescableCopyImpl(ExtractSubregRewriter(MI, *TII));
1315 case TargetOpcode::REG_SEQUENCE:
1316 return optimizeCoalescableCopyImpl(RegSequenceRewriter(MI));
1317 default:
1318 // Handle uncoalescable copy-like instructions.
1319 if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1320 MI.isExtractSubregLike())
1321 return optimizeCoalescableCopyImpl(UncoalescableRewriter(MI));
1322 return false;
1323 }
1324}
1325
1326/// Rewrite the source found through \p Def, by using the \p RewriteMap
1327/// and create a new COPY instruction. More info about RewriteMap in
1328/// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1329/// Uncoalescable copies, since they are copy like instructions that aren't
1330/// recognized by the register allocator.
1331MachineInstr &PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
1332 RegSubRegPair Def,
1333 RewriteMapTy &RewriteMap) {
1334 assert(!Def.Reg.isPhysical() && "We do not rewrite physical registers");
1335
1336 // Find the new source to use in the COPY rewrite.
1337 RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
1338
1339 // Insert the COPY.
1340 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1341 Register NewVReg = MRI->createVirtualRegister(DefRC);
1342
1343 if (NewSrc.SubReg) {
1344 const TargetRegisterClass *NewSrcRC = MRI->getRegClass(NewSrc.Reg);
1345 const TargetRegisterClass *WithSubRC =
1346 TRI->getSubClassWithSubReg(NewSrcRC, NewSrc.SubReg);
1347
1348 // The new source may not directly support the subregister, but we should be
1349 // able to assume it is constrainable to support the subregister (otherwise
1350 // ValueTracker was lying and reported a useless value).
1351 if (!MRI->constrainRegClass(NewSrc.Reg, WithSubRC))
1352 llvm_unreachable("replacement register cannot support subregister");
1353 }
1354
1355 MachineInstr *NewCopy =
1356 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1357 TII->get(TargetOpcode::COPY), NewVReg)
1358 .addReg(NewSrc.Reg, {}, NewSrc.SubReg);
1359
1360 if (Def.SubReg) {
1361 NewCopy->getOperand(0).setSubReg(Def.SubReg);
1362 NewCopy->getOperand(0).setIsUndef();
1363 }
1364
1365 LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
1366 LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike);
1367 LLVM_DEBUG(dbgs() << " With: " << *NewCopy);
1368 MRI->replaceRegWith(Def.Reg, NewVReg);
1369 MRI->clearKillFlags(NewVReg);
1370
1371 // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1372 // account for that.
1373 MRI->clearKillFlags(NewSrc.Reg);
1374
1375 return *NewCopy;
1376}
1377
1378/// Optimize copy-like instructions to create
1379/// register coalescer friendly instruction.
1380/// The optimization tries to kill-off the \p MI by looking
1381/// through a chain of copies to find a source that has a compatible
1382/// register class.
1383/// If such a source is found, it replace \p MI by a generic COPY
1384/// operation.
1385/// \pre isUncoalescableCopy(*MI) is true.
1386/// \return True, when \p MI has been optimized. In that case, \p MI has
1387/// been removed from its parent.
1388/// All COPY instructions created, are inserted in \p LocalMIs.
1389bool PeepholeOptimizer::optimizeUncoalescableCopy(
1390 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1391 assert(isUncoalescableCopy(MI) && "Invalid argument");
1392 UncoalescableRewriter CpyRewriter(MI);
1393
1394 // Rewrite each rewritable source by generating new COPYs. This works
1395 // differently from optimizeCoalescableCopy since it first makes sure that all
1396 // definitions can be rewritten.
1397 RewriteMapTy RewriteMap;
1398 RegSubRegPair Src;
1400 SmallVector<RegSubRegPair, 4> RewritePairs;
1401 while (CpyRewriter.getNextRewritableSource(Src, Def)) {
1402 // If a physical register is here, this is probably for a good reason.
1403 // Do not rewrite that.
1404 if (Def.Reg.isPhysical())
1405 return false;
1406
1407 // FIXME: Uncoalescable copies are treated differently by
1408 // UncoalescableRewriter, and this probably should not share
1409 // API. getNextRewritableSource really finds rewritable defs.
1410 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1411
1412 // If we do not know how to rewrite this definition, there is no point
1413 // in trying to kill this instruction.
1414 if (!findNextSource(DefRC, Def.SubReg, Def, RewriteMap))
1415 return false;
1416
1417 RewritePairs.push_back(Def);
1418 }
1419
1420 // The change is possible for all defs, do it.
1421 for (const RegSubRegPair &Def : RewritePairs) {
1422 // Rewrite the "copy" in a way the register coalescer understands.
1423 MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
1424 LocalMIs.insert(&NewCopy);
1425 }
1426
1427 // MI is now dead.
1428 LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI);
1429 MI.eraseFromParent();
1430 ++NumUncoalescableCopies;
1431 return true;
1432}
1433
1434/// Check whether MI is a candidate for folding into a later instruction.
1435/// We only fold loads to virtual registers and the virtual register defined
1436/// has a single user.
1437bool PeepholeOptimizer::isLoadFoldable(
1438 MachineInstr &MI, SmallSet<Register, 16> &FoldAsLoadDefCandidates) {
1439 if (!MI.canFoldAsLoad() || !MI.mayLoad())
1440 return false;
1441 const MCInstrDesc &MCID = MI.getDesc();
1442 if (MCID.getNumDefs() != 1)
1443 return false;
1444
1445 Register Reg = MI.getOperand(0).getReg();
1446 // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
1447 // loads. It should be checked when processing uses of the load, since
1448 // uses can be removed during peephole.
1449 if (Reg.isVirtual() && !MI.getOperand(0).getSubReg() &&
1450 MRI->hasOneNonDBGUser(Reg)) {
1451 FoldAsLoadDefCandidates.insert(Reg);
1452 return true;
1453 }
1454 return false;
1455}
1456
1457MachineInstr *
1458PeepholeOptimizer::foldLoadInto(MachineFunction &MF, MachineInstr &MI,
1459 Register FoldReg,
1460 SmallPtrSet<MachineInstr *, 16> &LocalMIs) {
1461 Register Reg = FoldReg;
1462 MachineInstr *DefMI = nullptr;
1463 MachineInstr *CopyMI = nullptr;
1464 MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI, Reg, DefMI, CopyMI);
1465 if (!FoldMI)
1466 return nullptr;
1467 LLVM_DEBUG(dbgs() << "Replacing: " << MI << " With: " << *FoldMI);
1468 LocalMIs.erase(&MI);
1469 LocalMIs.erase(DefMI);
1470 LocalMIs.insert(FoldMI);
1471 if (CopyMI)
1472 LocalMIs.insert(CopyMI);
1473 if (MI.shouldUpdateAdditionalCallInfo())
1474 MF.moveAdditionalCallInfo(&MI, FoldMI);
1475 MI.eraseFromParent();
1477 MRI->markUsesInDebugValueAsUndef(FoldReg);
1478 ++NumLoadFold;
1479 return FoldMI;
1480}
1481
1482bool PeepholeOptimizer::isMoveImmediate(
1483 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
1484 DenseMap<Register, MachineInstr *> &ImmDefMIs) {
1485 const MCInstrDesc &MCID = MI.getDesc();
1486 if (MCID.getNumDefs() != 1 || !MI.getOperand(0).isReg())
1487 return false;
1488 Register Reg = MI.getOperand(0).getReg();
1489 if (!Reg.isVirtual())
1490 return false;
1491
1492 int64_t ImmVal;
1493 if (!MI.isMoveImmediate() && !TII->getConstValDefinedInReg(MI, Reg, ImmVal))
1494 return false;
1495
1496 ImmDefMIs.insert(std::make_pair(Reg, &MI));
1497 ImmDefRegs.insert(Reg);
1498 return true;
1499}
1500
1501/// Try folding register operands that are defined by move immediate
1502/// instructions, i.e. a trivial constant folding optimization, if
1503/// and only if the def and use are in the same BB.
1504bool PeepholeOptimizer::foldImmediate(
1505 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
1506 DenseMap<Register, MachineInstr *> &ImmDefMIs, bool &Deleted) {
1507 Deleted = false;
1508 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1509 MachineOperand &MO = MI.getOperand(i);
1510 if (!MO.isReg() || MO.isDef())
1511 continue;
1512 Register Reg = MO.getReg();
1513 if (!Reg.isVirtual())
1514 continue;
1515 if (ImmDefRegs.count(Reg) == 0)
1516 continue;
1517 auto II = ImmDefMIs.find(Reg);
1518 assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
1519 if (TII->foldImmediate(MI, *II->second, Reg, MRI)) {
1520 ++NumImmFold;
1521 // foldImmediate can delete ImmDefMI if MI was its only user. If ImmDefMI
1522 // is not deleted, and we happened to get a same MI, we can delete MI and
1523 // replace its users.
1524 if (MRI->getVRegDef(Reg) &&
1526 Register DstReg = MI.getOperand(0).getReg();
1527 if (DstReg.isVirtual() &&
1528 MRI->getRegClass(DstReg) == MRI->getRegClass(Reg)) {
1529 MRI->replaceRegWith(DstReg, Reg);
1530 MRI->clearKillFlags(Reg);
1531 MI.eraseFromParent();
1532 Deleted = true;
1533 }
1534 }
1535 return true;
1536 }
1537 }
1538 return false;
1539}
1540
1541// FIXME: This is very simple and misses some cases which should be handled when
1542// motivating examples are found.
1543//
1544// The copy rewriting logic should look at uses as well as defs and be able to
1545// eliminate copies across blocks.
1546//
1547// Later copies that are subregister extracts will also not be eliminated since
1548// only the first copy is considered.
1549//
1550// e.g.
1551// %1 = COPY %0
1552// %2 = COPY %0:sub1
1553//
1554// Should replace %2 uses with %1:sub1
1555bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI) {
1556 assert(MI.isCopy() && "expected a COPY machine instruction");
1557
1558 RegSubRegPair SrcPair;
1559 if (!getCopySrc(MI, SrcPair))
1560 return false;
1561
1562 Register DstReg = MI.getOperand(0).getReg();
1563 if (!DstReg.isVirtual())
1564 return false;
1565
1566 if (CopySrcMIs.insert(std::make_pair(SrcPair, &MI)).second) {
1567 // First copy of this reg seen.
1568 return false;
1569 }
1570
1571 MachineInstr *PrevCopy = CopySrcMIs.find(SrcPair)->second;
1572
1573 assert(SrcPair.SubReg == PrevCopy->getOperand(1).getSubReg() &&
1574 "Unexpected mismatching subreg!");
1575
1576 Register PrevDstReg = PrevCopy->getOperand(0).getReg();
1577
1578 // Only replace if the copy register class is the same.
1579 //
1580 // TODO: If we have multiple copies to different register classes, we may want
1581 // to track multiple copies of the same source register.
1582 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1583 return false;
1584
1585 MRI->replaceRegWith(DstReg, PrevDstReg);
1586
1587 // Lifetime of the previous copy has been extended.
1588 MRI->clearKillFlags(PrevDstReg);
1589 return true;
1590}
1591
1592bool PeepholeOptimizer::isNAPhysCopy(Register Reg) {
1593 return Reg.isPhysical() && !MRI->isAllocatable(Reg);
1594}
1595
1596bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1597 MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs) {
1598 assert(MI.isCopy() && "expected a COPY machine instruction");
1599
1601 return false;
1602
1603 Register DstReg = MI.getOperand(0).getReg();
1604 Register SrcReg = MI.getOperand(1).getReg();
1605 if (isNAPhysCopy(SrcReg) && DstReg.isVirtual()) {
1606 // %vreg = COPY $physreg
1607 // Avoid using a datastructure which can track multiple live non-allocatable
1608 // phys->virt copies since LLVM doesn't seem to do this.
1609 NAPhysToVirtMIs.insert({SrcReg, &MI});
1610 return false;
1611 }
1612
1613 if (!(SrcReg.isVirtual() && isNAPhysCopy(DstReg)))
1614 return false;
1615
1616 // $physreg = COPY %vreg
1617 auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1618 if (PrevCopy == NAPhysToVirtMIs.end()) {
1619 // We can't remove the copy: there was an intervening clobber of the
1620 // non-allocatable physical register after the copy to virtual.
1621 LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
1622 << MI);
1623 return false;
1624 }
1625
1626 Register PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1627 if (PrevDstReg == SrcReg) {
1628 // Remove the virt->phys copy: we saw the virtual register definition, and
1629 // the non-allocatable physical register's state hasn't changed since then.
1630 LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
1631 ++NumNAPhysCopies;
1632 return true;
1633 }
1634
1635 // Potential missed optimization opportunity: we saw a different virtual
1636 // register get a copy of the non-allocatable physical register, and we only
1637 // track one such copy. Avoid getting confused by this new non-allocatable
1638 // physical register definition, and remove it from the tracked copies.
1639 LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
1640 NAPhysToVirtMIs.erase(PrevCopy);
1641 return false;
1642}
1643
1644/// \bried Returns true if \p MO is a virtual register operand.
1646 return MO.isReg() && MO.getReg().isVirtual();
1647}
1648
1649bool PeepholeOptimizer::findTargetRecurrence(
1650 Register Reg, const SmallSet<Register, 2> &TargetRegs,
1651 RecurrenceCycle &RC) {
1652 // Recurrence found if Reg is in TargetRegs.
1653 if (TargetRegs.count(Reg))
1654 return true;
1655
1656 // TODO: Curerntly, we only allow the last instruction of the recurrence
1657 // cycle (the instruction that feeds the PHI instruction) to have more than
1658 // one uses to guarantee that commuting operands does not tie registers
1659 // with overlapping live range. Once we have actual live range info of
1660 // each register, this constraint can be relaxed.
1661 if (!MRI->hasOneNonDBGUse(Reg))
1662 return false;
1663
1664 // Give up if the reccurrence chain length is longer than the limit.
1665 if (RC.size() >= MaxRecurrenceChain)
1666 return false;
1667
1668 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1669 unsigned Idx = MI.findRegisterUseOperandIdx(Reg, /*TRI=*/nullptr);
1670
1671 // Only interested in recurrences whose instructions have only one def, which
1672 // is a virtual register.
1673 if (MI.getDesc().getNumDefs() != 1)
1674 return false;
1675
1676 MachineOperand &DefOp = MI.getOperand(0);
1677 if (!isVirtualRegisterOperand(DefOp))
1678 return false;
1679
1680 // Check if def operand of MI is tied to any use operand. We are only
1681 // interested in the case that all the instructions in the recurrence chain
1682 // have there def operand tied with one of the use operand.
1683 unsigned TiedUseIdx;
1684 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1685 return false;
1686
1687 if (Idx == TiedUseIdx) {
1688 RC.push_back(RecurrenceInstr(&MI));
1689 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1690 } else {
1691 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1692 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1693 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1694 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1695 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1696 }
1697 }
1698
1699 return false;
1700}
1701
1702/// Phi instructions will eventually be lowered to copy instructions.
1703/// If phi is in a loop header, a recurrence may formulated around the source
1704/// and destination of the phi. For such case commuting operands of the
1705/// instructions in the recurrence may enable coalescing of the copy instruction
1706/// generated from the phi. For example, if there is a recurrence of
1707///
1708/// LoopHeader:
1709/// %1 = phi(%0, %100)
1710/// LoopLatch:
1711/// %0<def, tied1> = ADD %2<def, tied0>, %1
1712///
1713/// , the fact that %0 and %2 are in the same tied operands set makes
1714/// the coalescing of copy instruction generated from the phi in
1715/// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1716/// %2 have overlapping live range. This introduces additional move
1717/// instruction to the final assembly. However, if we commute %2 and
1718/// %1 of ADD instruction, the redundant move instruction can be
1719/// avoided.
1720bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1721 SmallSet<Register, 2> TargetRegs;
1722 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1723 MachineOperand &MO = PHI.getOperand(Idx);
1724 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1725 TargetRegs.insert(MO.getReg());
1726 }
1727
1728 bool Changed = false;
1729 RecurrenceCycle RC;
1730 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1731 // Commutes operands of instructions in RC if necessary so that the copy to
1732 // be generated from PHI can be coalesced.
1733 LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1734 for (auto &RI : RC) {
1735 LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1736 auto CP = RI.getCommutePair();
1737 if (CP) {
1738 Changed = true;
1739 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1740 (*CP).second);
1741 LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1742 }
1743 }
1744 }
1745
1746 return Changed;
1747}
1748
1749PreservedAnalyses
1752 MFPropsModifier _(*this, MF);
1753 auto *DT =
1754 Aggressive ? &MFAM.getResult<MachineDominatorTreeAnalysis>(MF) : nullptr;
1755 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
1756 PeepholeOptimizer Impl(DT, MLI);
1757 bool Changed = Impl.run(MF);
1758 if (!Changed)
1759 return PreservedAnalyses::all();
1760
1762 PA.preserveSet<CFGAnalyses>();
1763 return PA;
1764}
1765
1766bool PeepholeOptimizerLegacy::runOnMachineFunction(MachineFunction &MF) {
1767 if (skipFunction(MF.getFunction()))
1768 return false;
1769 auto *DT = Aggressive
1770 ? &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree()
1771 : nullptr;
1772 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
1773 PeepholeOptimizer Impl(DT, MLI);
1774 return Impl.run(MF);
1775}
1776
1777bool PeepholeOptimizer::run(MachineFunction &MF) {
1778
1779 LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1780 LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1781
1782 if (DisablePeephole)
1783 return false;
1784
1785 TII = MF.getSubtarget().getInstrInfo();
1787 MRI = &MF.getRegInfo();
1788 MF.setDelegate(this);
1789
1790 bool Changed = false;
1791
1792 for (MachineBasicBlock &MBB : MF) {
1793 bool SeenMoveImm = false;
1794
1795 // During this forward scan, at some point it needs to answer the question
1796 // "given a pointer to an MI in the current BB, is it located before or
1797 // after the current instruction".
1798 // To perform this, the following set keeps track of the MIs already seen
1799 // during the scan, if a MI is not in the set, it is assumed to be located
1800 // after. Newly created MIs have to be inserted in the set as well.
1802 SmallSet<Register, 4> ImmDefRegs;
1804 SmallSet<Register, 16> FoldAsLoadDefCandidates;
1805
1806 // Track when a non-allocatable physical register is copied to a virtual
1807 // register so that useless moves can be removed.
1808 //
1809 // $physreg is the map index; MI is the last valid `%vreg = COPY $physreg`
1810 // without any intervening re-definition of $physreg.
1811 DenseMap<Register, MachineInstr *> NAPhysToVirtMIs;
1812
1813 CopySrcMIs.clear();
1814
1815 bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1816
1817 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1818 MII != MIE;) {
1819 MachineInstr *MI = &*MII;
1820 // We may be erasing MI below, increment MII now.
1821 ++MII;
1822 LocalMIs.insert(MI);
1823
1824 // Skip debug instructions. They should not affect this peephole
1825 // optimization.
1826 if (MI->isDebugInstr())
1827 continue;
1828
1829 if (MI->isPosition())
1830 continue;
1831
1832 if (IsLoopHeader && MI->isPHI()) {
1833 if (optimizeRecurrence(*MI)) {
1834 Changed = true;
1835 continue;
1836 }
1837 }
1838
1839 if (!MI->isCopy()) {
1840 for (const MachineOperand &MO : MI->operands()) {
1841 // Visit all operands: definitions can be implicit or explicit.
1842 if (MO.isReg()) {
1843 Register Reg = MO.getReg();
1844 if (MO.isDef() && isNAPhysCopy(Reg)) {
1845 const auto &Def = NAPhysToVirtMIs.find(Reg);
1846 if (Def != NAPhysToVirtMIs.end()) {
1847 // A new definition of the non-allocatable physical register
1848 // invalidates previous copies.
1850 << "NAPhysCopy: invalidating because of " << *MI);
1851 NAPhysToVirtMIs.erase(Def);
1852 }
1853 }
1854 } else if (MO.isRegMask()) {
1855 const uint32_t *RegMask = MO.getRegMask();
1856 NAPhysToVirtMIs.remove_if([&](const auto &RegMI) {
1857 if (!MachineOperand::clobbersPhysReg(RegMask, RegMI.first))
1858 return false;
1860 << "NAPhysCopy: invalidating because of " << *MI);
1861 return true;
1862 });
1863 }
1864 }
1865 }
1866
1867 if (MI->isImplicitDef() || MI->isKill())
1868 continue;
1869
1870 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1871 // Blow away all non-allocatable physical registers knowledge since we
1872 // don't know what's correct anymore.
1873 //
1874 // FIXME: handle explicit asm clobbers.
1875 LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
1876 << *MI);
1877 NAPhysToVirtMIs.clear();
1878 }
1879
1880 if (MI->isCompare() && optimizeCmpInstr(*MI, MF, LocalMIs)) {
1881 Changed = true;
1882 continue;
1883 }
1884
1885 if ((isUncoalescableCopy(*MI) &&
1886 optimizeUncoalescableCopy(*MI, LocalMIs)) ||
1887 (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
1888 // MI is deleted.
1889 LocalMIs.erase(MI);
1890 Changed = true;
1891 continue;
1892 }
1893
1894 if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
1895 Changed = true;
1896 continue;
1897 }
1898
1899 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
1900 // MI is just rewritten.
1901 Changed = true;
1902 continue;
1903 }
1904
1905 if (MI->isCopy() && (foldRedundantCopy(*MI) ||
1906 foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
1907 LocalMIs.erase(MI);
1908 LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI << "\n");
1909 MI->eraseFromParent();
1910 Changed = true;
1911 continue;
1912 }
1913
1914 if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
1915 SeenMoveImm = true;
1916 } else {
1917 Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
1918 // optimizeExtInstr might have created new instructions after MI
1919 // and before the already incremented MII. Adjust MII so that the
1920 // next iteration sees the new instructions.
1921 MII = MI;
1922 ++MII;
1923 if (SeenMoveImm) {
1924 bool Deleted;
1925 Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs, Deleted);
1926 if (Deleted) {
1927 LocalMIs.erase(MI);
1928 continue;
1929 }
1930 }
1931 }
1932
1933 // Check whether MI is a load candidate for folding into a later
1934 // instruction. If MI is not a candidate, check whether we can fold an
1935 // earlier load into MI.
1936 if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
1937 !FoldAsLoadDefCandidates.empty()) {
1938
1939 // We visit each operand even after successfully folding a previous
1940 // one. This allows us to fold multiple loads into a single
1941 // instruction. We do assume that optimizeLoadInstr doesn't insert
1942 // foldable uses earlier in the argument list. Since we don't restart
1943 // iteration, we'd miss such cases.
1944 const MCInstrDesc &MIDesc = MI->getDesc();
1945 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands(); ++i) {
1946 const MachineOperand &MOp = MI->getOperand(i);
1947 if (!MOp.isReg())
1948 continue;
1949 Register FoldAsLoadDefReg = MOp.getReg();
1950 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1951 // We need to fold load after optimizeCmpInstr, since
1952 // optimizeCmpInstr can enable folding by converting SUB to CMP.
1953 Register FoldedReg = FoldAsLoadDefReg;
1954 if (MachineInstr *FoldMI =
1955 foldLoadInto(MF, *MI, FoldAsLoadDefReg, LocalMIs)) {
1956 FoldAsLoadDefCandidates.erase(FoldedReg);
1957 // MI is replaced with FoldMI so we can continue trying to fold
1958 Changed = true;
1959 MI = FoldMI;
1960 }
1961 }
1962 }
1963 }
1964
1965 // If we run into an instruction we can't fold across, discard
1966 // the load candidates. Note: We might be able to fold *into* this
1967 // instruction, so this needs to be after the folding logic.
1968 if (MI->isLoadFoldBarrier()) {
1969 LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
1970 FoldAsLoadDefCandidates.clear();
1971 }
1972 }
1973 }
1974
1975 MF.resetDelegate(this);
1976 return Changed;
1977}
1978
1979ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1980 assert(Def->isCopy() && "Invalid definition");
1981 // Copy instruction are supposed to be: Def = Src.
1982 // If someone breaks this assumption, bad things will happen everywhere.
1983 // There may be implicit uses preventing the copy to be moved across
1984 // some target specific register definitions
1985 assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&
1986 "Invalid number of operands");
1987 assert(!Def->hasImplicitDef() && "Only implicit uses are allowed");
1988 assert(!Def->getOperand(DefIdx).getSubReg() && "no subregister defs in SSA");
1989
1990 // Otherwise, we want the whole source.
1991 const MachineOperand &Src = Def->getOperand(1);
1992 if (Src.isUndef())
1993 return ValueTrackerResult();
1994
1995 Register SrcReg = Src.getReg();
1996 unsigned SubReg = Src.getSubReg();
1997 if (DefSubReg) {
1998 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1999 SubReg = TRI->composeSubRegIndices(SubReg, DefSubReg);
2000
2001 if (SrcReg.isVirtual()) {
2002 // TODO: Try constraining on rewrite if we can
2003 const TargetRegisterClass *RegRC = MRI.getRegClass(SrcReg);
2004 if (!TRI->isSubRegValidForRegClass(RegRC, SubReg))
2005 return ValueTrackerResult();
2006 } else {
2007 if (!TRI->getSubReg(SrcReg, SubReg))
2008 return ValueTrackerResult();
2009 }
2010 }
2011
2012 return ValueTrackerResult(SrcReg, SubReg);
2013}
2014
2015ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
2016 assert(Def->isBitcast() && "Invalid definition");
2017
2018 // Bail if there are effects that a plain copy will not expose.
2019 if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
2020 return ValueTrackerResult();
2021
2022 // Bitcasts with more than one def are not supported.
2023 if (Def->getDesc().getNumDefs() != 1)
2024 return ValueTrackerResult();
2025
2026 assert(!Def->getOperand(DefIdx).getSubReg() && "no subregister defs in SSA");
2027
2028 unsigned SrcIdx = Def->getNumOperands();
2029 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
2030 ++OpIdx) {
2031 const MachineOperand &MO = Def->getOperand(OpIdx);
2032 if (!MO.isReg() || !MO.getReg())
2033 continue;
2034 // Ignore dead implicit defs.
2035 if (MO.isImplicit() && MO.isDead())
2036 continue;
2037 assert(!MO.isDef() && "We should have skipped all the definitions by now");
2038 if (SrcIdx != EndOpIdx)
2039 // Multiple sources?
2040 return ValueTrackerResult();
2041 SrcIdx = OpIdx;
2042 }
2043
2044 // In some rare case, Def has no input, SrcIdx is out of bound,
2045 // getOperand(SrcIdx) will fail below.
2046 if (SrcIdx >= Def->getNumOperands())
2047 return ValueTrackerResult();
2048
2049 const MachineOperand &DefOp = Def->getOperand(DefIdx);
2050
2051 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
2052 // will break the assumed guarantees for the upper bits.
2053 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
2054 if (UseMI.isSubregToReg())
2055 return ValueTrackerResult();
2056 }
2057
2058 const MachineOperand &Src = Def->getOperand(SrcIdx);
2059 if (Src.isUndef())
2060 return ValueTrackerResult();
2061 return ValueTrackerResult(Src.getReg(), Src.getSubReg());
2062}
2063
2064ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
2065 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
2066 "Invalid definition");
2067
2068 assert(!Def->getOperand(DefIdx).getSubReg() && "illegal subregister def");
2069
2071 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
2072 return ValueTrackerResult();
2073
2074 // We are looking at:
2075 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
2076 //
2077 // Check if one of the operands exactly defines the subreg we are interested
2078 // in.
2079 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
2080 if (RegSeqInput.SubIdx == DefSubReg)
2081 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
2082 }
2083
2084 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2085
2086 // If we did not find an exact match, see if we can do a composition to
2087 // extract a sub-subregister.
2088 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
2089 LaneBitmask DefMask = TRI->getSubRegIndexLaneMask(DefSubReg);
2090 LaneBitmask ThisOpRegMask = TRI->getSubRegIndexLaneMask(RegSeqInput.SubIdx);
2091
2092 // Check that this extract reads a subset of this single reg_sequence input.
2093 //
2094 // FIXME: We should be able to filter this in terms of the indexes directly
2095 // without checking the lanemasks.
2096 if ((DefMask & ThisOpRegMask) != DefMask)
2097 continue;
2098
2099 unsigned ReverseDefCompose =
2100 TRI->reverseComposeSubRegIndices(RegSeqInput.SubIdx, DefSubReg);
2101 if (!ReverseDefCompose)
2102 continue;
2103
2104 unsigned ComposedDefInSrcReg1 =
2105 TRI->composeSubRegIndices(RegSeqInput.SubReg, ReverseDefCompose);
2106
2107 // TODO: We should be able to defer checking if the result register class
2108 // supports the index to continue looking for a rewritable source.
2109 //
2110 // TODO: Should we modify the register class to support the index?
2111 const TargetRegisterClass *SrcRC = MRI.getRegClass(RegSeqInput.Reg);
2112 if (!TRI->isSubRegValidForRegClass(SrcRC, ComposedDefInSrcReg1))
2113 return ValueTrackerResult();
2114
2115 return ValueTrackerResult(RegSeqInput.Reg, ComposedDefInSrcReg1);
2116 }
2117
2118 // If the subreg we are tracking is super-defined by another subreg,
2119 // we could follow this value. However, this would require to compose
2120 // the subreg and we do not do that for now.
2121 return ValueTrackerResult();
2122}
2123
2124ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
2125 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
2126 "Invalid definition");
2127 assert(!Def->getOperand(DefIdx).getSubReg() && "no subreg defs in SSA");
2128
2130 RegSubRegPairAndIdx InsertedReg;
2131 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
2132 return ValueTrackerResult();
2133
2134 // We are looking at:
2135 // Def = INSERT_SUBREG v0, v1, sub1
2136 // There are two cases:
2137 // 1. DefSubReg == sub1, get v1.
2138 // 2. DefSubReg != sub1, the value may be available through v0.
2139
2140 // #1 Check if the inserted register matches the required sub index.
2141 if (InsertedReg.SubIdx == DefSubReg) {
2142 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
2143 }
2144 // #2 Otherwise, if the sub register we are looking for is not partial
2145 // defined by the inserted element, we can look through the main
2146 // register (v0).
2147 const MachineOperand &MODef = Def->getOperand(DefIdx);
2148 // If the result register (Def) and the base register (v0) do not
2149 // have the same register class or if we have to compose
2150 // subregisters, bail out.
2151 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
2152 BaseReg.SubReg)
2153 return ValueTrackerResult();
2154
2155 // Get the TRI and check if the inserted sub-register overlaps with the
2156 // sub-register we are tracking.
2157 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
2158 if ((TRI->getSubRegIndexLaneMask(DefSubReg) &
2159 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx))
2160 .any())
2161 return ValueTrackerResult();
2162 // At this point, the value is available in v0 via the same subreg
2163 // we used for Def.
2164 return ValueTrackerResult(BaseReg.Reg, DefSubReg);
2165}
2166
2167ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
2168 assert((Def->isExtractSubreg() || Def->isExtractSubregLike()) &&
2169 "Invalid definition");
2170 // We are looking at:
2171 // Def = EXTRACT_SUBREG v0, sub0
2172
2173 // Bail if we have to compose sub registers.
2174 // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
2175 if (DefSubReg)
2176 return ValueTrackerResult();
2177
2178 RegSubRegPairAndIdx ExtractSubregInputReg;
2179 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
2180 return ValueTrackerResult();
2181
2182 // Bail if we have to compose sub registers.
2183 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
2184 if (ExtractSubregInputReg.SubReg)
2185 return ValueTrackerResult();
2186 // Otherwise, the value is available in the v0.sub0.
2187 return ValueTrackerResult(ExtractSubregInputReg.Reg,
2188 ExtractSubregInputReg.SubIdx);
2189}
2190
2191ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2192 assert(Def->isSubregToReg() && "Invalid definition");
2193 // We are looking at:
2194 // Def = SUBREG_TO_REG v0, sub0
2195
2196 // Bail if we have to compose sub registers.
2197 // If DefSubReg != sub0, we would have to check that all the bits
2198 // we track are included in sub0 and if yes, we would have to
2199 // determine the right subreg in v0.
2200 if (DefSubReg != Def->getOperand(2).getImm())
2201 return ValueTrackerResult();
2202 // Bail if we have to compose sub registers.
2203 // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2204 if (Def->getOperand(1).getSubReg())
2205 return ValueTrackerResult();
2206
2207 return ValueTrackerResult(Def->getOperand(1).getReg(),
2208 Def->getOperand(2).getImm());
2209}
2210
2211/// Explore each PHI incoming operand and return its sources.
2212ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2213 assert(Def->isPHI() && "Invalid definition");
2214 ValueTrackerResult Res;
2215
2216 // Return all register sources for PHI instructions.
2217 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2218 const MachineOperand &MO = Def->getOperand(i);
2219 assert(MO.isReg() && "Invalid PHI instruction");
2220 // We have no code to deal with undef operands. They shouldn't happen in
2221 // normal programs anyway.
2222 if (MO.isUndef())
2223 return ValueTrackerResult();
2224 Res.addSource(MO.getReg(), MO.getSubReg());
2225 }
2226
2227 return Res;
2228}
2229
2230ValueTrackerResult ValueTracker::getNextSourceImpl() {
2231 assert(Def && "This method needs a valid definition");
2232
2233 assert(((Def->getOperand(DefIdx).isDef() &&
2234 (DefIdx < Def->getDesc().getNumDefs() ||
2235 Def->getDesc().isVariadic())) ||
2236 Def->getOperand(DefIdx).isImplicit()) &&
2237 "Invalid DefIdx");
2238 if (Def->isCopy())
2239 return getNextSourceFromCopy();
2240 if (Def->isBitcast())
2241 return getNextSourceFromBitcast();
2242 // All the remaining cases involve "complex" instructions.
2243 // Bail if we did not ask for the advanced tracking.
2245 return ValueTrackerResult();
2246 if (Def->isRegSequence() || Def->isRegSequenceLike())
2247 return getNextSourceFromRegSequence();
2248 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2249 return getNextSourceFromInsertSubreg();
2250 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2251 return getNextSourceFromExtractSubreg();
2252 if (Def->isSubregToReg())
2253 return getNextSourceFromSubregToReg();
2254 if (Def->isPHI())
2255 return getNextSourceFromPHI();
2256 return ValueTrackerResult();
2257}
2258
2259ValueTrackerResult ValueTracker::getNextSource() {
2260 // If we reach a point where we cannot move up in the use-def chain,
2261 // there is nothing we can get.
2262 if (!Def)
2263 return ValueTrackerResult();
2264
2265 ValueTrackerResult Res = getNextSourceImpl();
2266 if (Res.isValid()) {
2267 // Update definition, definition index, and subregister for the
2268 // next call of getNextSource.
2269 // Update the current register.
2270 bool OneRegSrc = Res.getNumSources() == 1;
2271 if (OneRegSrc)
2272 Reg = Res.getSrcReg(0);
2273 // Update the result before moving up in the use-def chain
2274 // with the instruction containing the last found sources.
2275 Res.setInst(Def);
2276
2277 // If we can still move up in the use-def chain, move to the next
2278 // definition.
2279 if (!Reg.isPhysical() && OneRegSrc) {
2281 if (DI != MRI.def_end()) {
2282 Def = DI->getParent();
2283 DefIdx = DI.getOperandNo();
2284 DefSubReg = Res.getSrcSubReg(0);
2285 } else {
2286 Def = nullptr;
2287 }
2288 return Res;
2289 }
2290 }
2291 // If we end up here, this means we will not be able to find another source
2292 // for the next iteration. Make sure any new call to getNextSource bails out
2293 // early by cutting the use-def chain.
2294 Def = nullptr;
2295 return Res;
2296}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock & MBB
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static cl::opt< unsigned > RewritePHILimit("rewrite-phi-limit", cl::Hidden, cl::init(10), cl::desc("Limit the length of PHI chains to lookup"))
static cl::opt< bool > DisablePeephole("disable-peephole", cl::Hidden, cl::init(false), cl::desc("Disable the peephole optimizer"))
static cl::opt< unsigned > MaxRecurrenceChain("recurrence-chain-limit", cl::Hidden, cl::init(3), cl::desc("Maximum length of recurrence chain when evaluating the benefit " "of commuting operands"))
static cl::opt< bool > DisableNAPhysCopyOpt("disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable non-allocatable physical register copy optimization"))
static bool isVirtualRegisterOperand(MachineOperand &MO)
\bried Returns true if MO is a virtual register operand.
static MachineInstr & insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const SmallVectorImpl< RegSubRegPair > &SrcRegs, MachineInstr &OrigPHI)
Insert a PHI instruction with incoming edges SrcRegs that are guaranteed to have the same register cl...
static cl::opt< bool > Aggressive("aggressive-ext-opt", cl::Hidden, cl::desc("Aggressive extension optimization"))
static cl::opt< bool > DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable advanced copy optimization"))
Specifiy whether or not the value tracking looks through complex instructions.
TargetInstrInfo::RegSubRegPairAndIdx RegSubRegPairAndIdx
static RegSubRegPair getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII, RegSubRegPair Def, const PeepholeOptimizer::RewriteMapTy &RewriteMap, bool HandleMultipleSources=true)
Given a Def.Reg and Def.SubReg pair, use RewriteMap to find the new source to use for rewrite.
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Virtual Register Rewriter
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
bool erase(const KeyT &Val)
Definition DenseMap.h:377
bool remove_if(Predicate Pred)
Remove entries that match the given predicate.
Definition DenseMap.h:393
iterator end()
Definition DenseMap.h:141
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:284
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &Mask, int64_t &Value) const override
For a comparison instruction, return the source registers in SrcReg and SrcReg2 if having two registe...
bool isLoopHeader(const BlockT *BB) const
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
An RAII based helper class to modify MachineFunctionProperties when running pass.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void moveAdditionalCallInfo(const MachineInstr *Old, const MachineInstr *New)
Move the call site info from Old to \New call site info.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
void setDelegate(Delegate *delegate)
Set the delegate.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
LLVM_ABI bool isIdenticalTo(const MachineInstr &Other, MICheckType Check=CheckDefs) const
Return true if this instruction is identical to Other.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool canFoldAsLoad(QueryType Type=IgnoreBundle) const
Return true for instructions that can be folded as memory operands in other instructions.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
MachineBasicBlock * getMBB() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
unsigned getOperandNo() const
getOperandNo - Return the operand # of this MachineOperand in its MachineInstr.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
use_nodbg_iterator use_nodbg_begin(Register RegNo) const
LLVM_ABI void markUsesInDebugValueAsUndef(Register Reg) const
markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the specified register as undefined wh...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
def_iterator def_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
LLVM_ABI bool hasOneNonDBGUser(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
defusechain_iterator< false, true, false, true, false > def_iterator
def_iterator/def_begin/def_end - Walk all defs of the specified register.
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
static def_iterator def_end()
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
static const unsigned CommuteAnyOperandIndex
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
MCInstrDesc const & getDesc(MCInstrInfo const &MCII, MCInst const &MCI)
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI char & PeepholeOptimizerLegacyID
PeepholeOptimizer - This pass performs peephole optimizations - like extension and comparison elimina...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
A pair composed of a pair of a register and a sub-register index, and another sub-register index.
A pair composed of a register and a sub-register index.