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