Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/BranchFolding.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- BranchFolding.cpp - Fold machine code branch instructions ----------===//
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
// This pass forwards branches to unconditional branches to make them branch
10
// directly to the target block.  This pass often results in dead MBB's, which
11
// it then removes.
12
//
13
// Note that this pass must be run after register allocation, it cannot handle
14
// SSA form. It also must handle virtual registers for targets that emit virtual
15
// ISA (e.g. NVPTX).
16
//
17
//===----------------------------------------------------------------------===//
18
19
#include "BranchFolding.h"
20
#include "llvm/ADT/BitVector.h"
21
#include "llvm/ADT/DenseMap.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/SmallPtrSet.h"
24
#include "llvm/ADT/SmallSet.h"
25
#include "llvm/ADT/SmallVector.h"
26
#include "llvm/ADT/Statistic.h"
27
#include "llvm/CodeGen/Analysis.h"
28
#include "llvm/CodeGen/LivePhysRegs.h"
29
#include "llvm/CodeGen/MachineBasicBlock.h"
30
#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31
#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
32
#include "llvm/CodeGen/MachineFunction.h"
33
#include "llvm/CodeGen/MachineFunctionPass.h"
34
#include "llvm/CodeGen/MachineInstr.h"
35
#include "llvm/CodeGen/MachineInstrBuilder.h"
36
#include "llvm/CodeGen/MachineJumpTableInfo.h"
37
#include "llvm/CodeGen/MachineLoopInfo.h"
38
#include "llvm/CodeGen/MachineModuleInfo.h"
39
#include "llvm/CodeGen/MachineOperand.h"
40
#include "llvm/CodeGen/MachineRegisterInfo.h"
41
#include "llvm/CodeGen/TargetInstrInfo.h"
42
#include "llvm/CodeGen/TargetOpcodes.h"
43
#include "llvm/CodeGen/TargetPassConfig.h"
44
#include "llvm/CodeGen/TargetRegisterInfo.h"
45
#include "llvm/CodeGen/TargetSubtargetInfo.h"
46
#include "llvm/IR/DebugInfoMetadata.h"
47
#include "llvm/IR/DebugLoc.h"
48
#include "llvm/IR/Function.h"
49
#include "llvm/MC/LaneBitmask.h"
50
#include "llvm/MC/MCRegisterInfo.h"
51
#include "llvm/Pass.h"
52
#include "llvm/Support/BlockFrequency.h"
53
#include "llvm/Support/BranchProbability.h"
54
#include "llvm/Support/CommandLine.h"
55
#include "llvm/Support/Debug.h"
56
#include "llvm/Support/ErrorHandling.h"
57
#include "llvm/Support/raw_ostream.h"
58
#include "llvm/Target/TargetMachine.h"
59
#include <cassert>
60
#include <cstddef>
61
#include <iterator>
62
#include <numeric>
63
#include <vector>
64
65
using namespace llvm;
66
67
#define DEBUG_TYPE "branch-folder"
68
69
STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
70
STATISTIC(NumBranchOpts, "Number of branches optimized");
71
STATISTIC(NumTailMerge , "Number of block tails merged");
72
STATISTIC(NumHoist     , "Number of times common instructions are hoisted");
73
STATISTIC(NumTailCalls,  "Number of tail calls optimized");
74
75
static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
76
                              cl::init(cl::BOU_UNSET), cl::Hidden);
77
78
// Throttle for huge numbers of predecessors (compile speed problems)
79
static cl::opt<unsigned>
80
TailMergeThreshold("tail-merge-threshold",
81
          cl::desc("Max number of predecessors to consider tail merging"),
82
          cl::init(150), cl::Hidden);
83
84
// Heuristic for tail merging (and, inversely, tail duplication).
85
// TODO: This should be replaced with a target query.
86
static cl::opt<unsigned>
87
TailMergeSize("tail-merge-size",
88
              cl::desc("Min number of instructions to consider tail merging"),
89
              cl::init(3), cl::Hidden);
90
91
namespace {
92
93
  /// BranchFolderPass - Wrap branch folder in a machine function pass.
94
  class BranchFolderPass : public MachineFunctionPass {
95
  public:
96
    static char ID;
97
98
34.5k
    explicit BranchFolderPass(): MachineFunctionPass(ID) {}
99
100
    bool runOnMachineFunction(MachineFunction &MF) override;
101
102
34.2k
    void getAnalysisUsage(AnalysisUsage &AU) const override {
103
34.2k
      AU.addRequired<MachineBlockFrequencyInfo>();
104
34.2k
      AU.addRequired<MachineBranchProbabilityInfo>();
105
34.2k
      AU.addRequired<TargetPassConfig>();
106
34.2k
      MachineFunctionPass::getAnalysisUsage(AU);
107
34.2k
    }
108
  };
109
110
} // end anonymous namespace
111
112
char BranchFolderPass::ID = 0;
113
114
char &llvm::BranchFolderPassID = BranchFolderPass::ID;
115
116
INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE,
117
                "Control Flow Optimizer", false, false)
118
119
489k
bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
120
489k
  if (skipFunction(MF.getFunction()))
121
271
    return false;
122
489k
123
489k
  TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
124
489k
  // TailMerge can create jump into if branches that make CFG irreducible for
125
489k
  // HW that requires structurized CFG.
126
489k
  bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
127
489k
                         
PassConfig->getEnableTailMerge()486k
;
128
489k
  BranchFolder::MBFIWrapper MBBFreqInfo(
129
489k
      getAnalysis<MachineBlockFrequencyInfo>());
130
489k
  BranchFolder Folder(EnableTailMerge, /*CommonHoist=*/true, MBBFreqInfo,
131
489k
                      getAnalysis<MachineBranchProbabilityInfo>());
132
489k
  return Folder.OptimizeFunction(MF, MF.getSubtarget().getInstrInfo(),
133
489k
                                 MF.getSubtarget().getRegisterInfo(),
134
489k
                                 getAnalysisIfAvailable<MachineModuleInfo>());
135
489k
}
136
137
BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist,
138
                           MBFIWrapper &FreqInfo,
139
                           const MachineBranchProbabilityInfo &ProbInfo,
140
                           unsigned MinTailLength)
141
    : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
142
654k
      MBBFreqInfo(FreqInfo), MBPI(ProbInfo) {
143
654k
  if (MinCommonTailLength == 0)
144
541k
    MinCommonTailLength = TailMergeSize;
145
654k
  switch (FlagEnableTailMerge) {
146
654k
  
case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break654k
;
147
654k
  
case cl::BOU_TRUE: EnableTailMerge = true; break3
;
148
654k
  
case cl::BOU_FALSE: EnableTailMerge = false; break63
;
149
654k
  }
150
654k
}
151
152
207k
void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
153
207k
  assert(MBB->pred_empty() && "MBB must be dead!");
154
207k
  LLVM_DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
155
207k
156
207k
  MachineFunction *MF = MBB->getParent();
157
207k
  // drop all successors.
158
396k
  while (!MBB->succ_empty())
159
188k
    MBB->removeSuccessor(MBB->succ_end()-1);
160
207k
161
207k
  // Avoid matching if this pointer gets reused.
162
207k
  TriedMerging.erase(MBB);
163
207k
164
207k
  // Remove the block.
165
207k
  MF->erase(MBB);
166
207k
  EHScopeMembership.erase(MBB);
167
207k
  if (MLI)
168
10.4k
    MLI->removeBlock(MBB);
169
207k
}
170
171
bool BranchFolder::OptimizeFunction(MachineFunction &MF,
172
                                    const TargetInstrInfo *tii,
173
                                    const TargetRegisterInfo *tri,
174
                                    MachineModuleInfo *mmi,
175
654k
                                    MachineLoopInfo *mli, bool AfterPlacement) {
176
654k
  if (!tii) 
return false0
;
177
654k
178
654k
  TriedMerging.clear();
179
654k
180
654k
  MachineRegisterInfo &MRI = MF.getRegInfo();
181
654k
  AfterBlockPlacement = AfterPlacement;
182
654k
  TII = tii;
183
654k
  TRI = tri;
184
654k
  MMI = mmi;
185
654k
  MLI = mli;
186
654k
  this->MRI = &MRI;
187
654k
188
654k
  UpdateLiveIns = MRI.tracksLiveness() && 
TRI->trackLivenessAfterRegAlloc(MF)652k
;
189
654k
  if (!UpdateLiveIns)
190
11.1k
    MRI.invalidateLiveness();
191
654k
192
654k
  // Fix CFG.  The later algorithms expect it to be right.
193
654k
  bool MadeChange = false;
194
5.21M
  for (MachineBasicBlock &MBB : MF) {
195
5.21M
    MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
196
5.21M
    SmallVector<MachineOperand, 4> Cond;
197
5.21M
    if (!TII->analyzeBranch(MBB, TBB, FBB, Cond, true))
198
4.33M
      MadeChange |= MBB.CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
199
5.21M
  }
200
654k
201
654k
  // Recalculate EH scope membership.
202
654k
  EHScopeMembership = getEHScopeMembership(MF);
203
654k
204
654k
  bool MadeChangeThisIteration = true;
205
1.44M
  while (MadeChangeThisIteration) {
206
785k
    MadeChangeThisIteration    = TailMergeBlocks(MF);
207
785k
    // No need to clean up if tail merging does not change anything after the
208
785k
    // block placement.
209
785k
    if (!AfterBlockPlacement || 
MadeChangeThisIteration122k
)
210
673k
      MadeChangeThisIteration |= OptimizeBranches(MF);
211
785k
    if (EnableHoistCommonCode)
212
606k
      MadeChangeThisIteration |= HoistCommonCode(MF);
213
785k
    MadeChange |= MadeChangeThisIteration;
214
785k
  }
215
654k
216
654k
  // See if any jump tables have become dead as the code generator
217
654k
  // did its thing.
218
654k
  MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
219
654k
  if (!JTI)
220
648k
    return MadeChange;
221
5.85k
222
5.85k
  // Walk the function to find jump tables that are live.
223
5.85k
  BitVector JTIsLive(JTI->getJumpTables().size());
224
641k
  for (const MachineBasicBlock &BB : MF) {
225
641k
    for (const MachineInstr &I : BB)
226
10.9M
      
for (const MachineOperand &Op : I.operands())3.13M
{
227
10.9M
        if (!Op.isJTI()) 
continue10.9M
;
228
17.3k
229
17.3k
        // Remember that this JT is live.
230
17.3k
        JTIsLive.set(Op.getIndex());
231
17.3k
      }
232
641k
  }
233
5.85k
234
5.85k
  // Finally, remove dead jump tables.  This happens when the
235
5.85k
  // indirect jump was unreachable (and thus deleted).
236
12.2k
  for (unsigned i = 0, e = JTIsLive.size(); i != e; 
++i6.35k
)
237
6.35k
    if (!JTIsLive.test(i)) {
238
7
      JTI->RemoveJumpTable(i);
239
7
      MadeChange = true;
240
7
    }
241
5.85k
242
5.85k
  return MadeChange;
243
5.85k
}
244
245
//===----------------------------------------------------------------------===//
246
//  Tail Merging of Blocks
247
//===----------------------------------------------------------------------===//
248
249
/// HashMachineInstr - Compute a hash value for MI and its operands.
250
7.06M
static unsigned HashMachineInstr(const MachineInstr &MI) {
251
7.06M
  unsigned Hash = MI.getOpcode();
252
29.9M
  for (unsigned i = 0, e = MI.getNumOperands(); i != e; 
++i22.8M
) {
253
22.8M
    const MachineOperand &Op = MI.getOperand(i);
254
22.8M
255
22.8M
    // Merge in bits from the operand if easy. We can't use MachineOperand's
256
22.8M
    // hash_code here because it's not deterministic and we sort by hash value
257
22.8M
    // later.
258
22.8M
    unsigned OperandHash = 0;
259
22.8M
    switch (Op.getType()) {
260
22.8M
    case MachineOperand::MO_Register:
261
13.0M
      OperandHash = Op.getReg();
262
13.0M
      break;
263
22.8M
    case MachineOperand::MO_Immediate:
264
4.61M
      OperandHash = Op.getImm();
265
4.61M
      break;
266
22.8M
    case MachineOperand::MO_MachineBasicBlock:
267
3.19M
      OperandHash = Op.getMBB()->getNumber();
268
3.19M
      break;
269
22.8M
    case MachineOperand::MO_FrameIndex:
270
7.02k
    case MachineOperand::MO_ConstantPoolIndex:
271
7.02k
    case MachineOperand::MO_JumpTableIndex:
272
7.02k
      OperandHash = Op.getIndex();
273
7.02k
      break;
274
1.23M
    case MachineOperand::MO_GlobalAddress:
275
1.23M
    case MachineOperand::MO_ExternalSymbol:
276
1.23M
      // Global address / external symbol are too hard, don't bother, but do
277
1.23M
      // pull in the offset.
278
1.23M
      OperandHash = Op.getOffset();
279
1.23M
      break;
280
1.23M
    default:
281
844k
      break;
282
22.8M
    }
283
22.8M
284
22.8M
    Hash += ((OperandHash << 3) | Op.getType()) << (i & 31);
285
22.8M
  }
286
7.06M
  return Hash;
287
7.06M
}
288
289
/// HashEndOfMBB - Hash the last instruction in the MBB.
290
7.21M
static unsigned HashEndOfMBB(const MachineBasicBlock &MBB) {
291
7.21M
  MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
292
7.21M
  if (I == MBB.end())
293
159k
    return 0;
294
7.06M
295
7.06M
  return HashMachineInstr(*I);
296
7.06M
}
297
298
///  Whether MI should be counted as an instruction when calculating common tail.
299
45.3M
static bool countsAsInstruction(const MachineInstr &MI) {
300
45.3M
  return !(MI.isDebugInstr() || 
MI.isCFIInstruction()45.3M
);
301
45.3M
}
302
303
/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
304
/// of instructions they actually have in common together at their end.  Return
305
/// iterators for the first shared instruction in each block.
306
static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
307
                                        MachineBasicBlock *MBB2,
308
                                        MachineBasicBlock::iterator &I1,
309
5.96M
                                        MachineBasicBlock::iterator &I2) {
310
5.96M
  I1 = MBB1->end();
311
5.96M
  I2 = MBB2->end();
312
5.96M
313
5.96M
  unsigned TailLen = 0;
314
21.9M
  while (I1 != MBB1->begin() && 
I2 != MBB2->begin()21.3M
) {
315
21.1M
    --I1; --I2;
316
21.1M
    // Skip debugging pseudos; necessary to avoid changing the code.
317
21.2M
    while (!countsAsInstruction(*I1)) {
318
2.08k
      if (I1==MBB1->begin()) {
319
0
        while (!countsAsInstruction(*I2)) {
320
0
          if (I2==MBB2->begin()) {
321
0
            // I1==DBG at begin; I2==DBG at begin
322
0
            goto SkipTopCFIAndReturn;
323
0
          }
324
0
          --I2;
325
0
        }
326
0
        ++I2;
327
0
        // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
328
0
        goto SkipTopCFIAndReturn;
329
2.08k
      }
330
2.08k
      --I1;
331
2.08k
    }
332
21.1M
    // I1==first (untested) non-DBG preceding known match
333
21.2M
    
while (21.1M
!countsAsInstruction(*I2)) {
334
2.08k
      if (I2==MBB2->begin()) {
335
0
        ++I1;
336
0
        // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
337
0
        goto SkipTopCFIAndReturn;
338
0
      }
339
2.08k
      --I2;
340
2.08k
    }
341
21.1M
    // I1, I2==first (untested) non-DBGs preceding known match
342
21.1M
    if (!I1->isIdenticalTo(*I2) ||
343
21.1M
        // FIXME: This check is dubious. It's used to get around a problem where
344
21.1M
        // people incorrectly expect inline asm directives to remain in the same
345
21.1M
        // relative order. This is untenable because normal compiler
346
21.1M
        // optimizations (like this one) may reorder and/or merge these
347
21.1M
        // directives.
348
21.1M
        
I1->isInlineAsm()15.9M
) {
349
5.21M
      ++I1; ++I2;
350
5.21M
      break;
351
5.21M
    }
352
15.9M
    ++TailLen;
353
15.9M
  }
354
5.96M
  // Back past possible debugging pseudos at beginning of block.  This matters
355
5.96M
  // when one block differs from the other only by whether debugging pseudos
356
5.96M
  // are present at the beginning. (This way, the various checks later for
357
5.96M
  // I1==MBB1->begin() work as expected.)
358
5.96M
  if (I1 == MBB1->begin() && 
I2 != MBB2->begin()645k
) {
359
200k
    --I2;
360
200k
    while (I2->isDebugInstr()) {
361
1
      if (I2 == MBB2->begin())
362
1
        return TailLen;
363
0
      --I2;
364
0
    }
365
200k
    ++I2;
366
200k
  }
367
5.96M
  
if (5.96M
I2 == MBB2->begin()5.96M
&&
I1 != MBB1->begin()558k
) {
368
114k
    --I1;
369
114k
    while (I1->isDebugInstr()) {
370
1
      if (I1 == MBB1->begin())
371
0
        return TailLen;
372
1
      --I1;
373
1
    }
374
114k
    ++I1;
375
114k
  }
376
5.96M
377
5.96M
SkipTopCFIAndReturn:
378
5.96M
  // Ensure that I1 and I2 do not point to a CFI_INSTRUCTION. This can happen if
379
5.96M
  // I1 and I2 are non-identical when compared and then one or both of them ends
380
5.96M
  // up pointing to a CFI instruction after being incremented. For example:
381
5.96M
  /*
382
5.96M
    BB1:
383
5.96M
    ...
384
5.96M
    INSTRUCTION_A
385
5.96M
    ADD32ri8  <- last common instruction
386
5.96M
    ...
387
5.96M
    BB2:
388
5.96M
    ...
389
5.96M
    INSTRUCTION_B
390
5.96M
    CFI_INSTRUCTION
391
5.96M
    ADD32ri8  <- last common instruction
392
5.96M
    ...
393
5.96M
  */
394
5.96M
  // When INSTRUCTION_A and INSTRUCTION_B are compared as not equal, after
395
5.96M
  // incrementing the iterators, I1 will point to ADD, however I2 will point to
396
5.96M
  // the CFI instruction. Later on, this leads to BB2 being 'hacked off' at the
397
5.96M
  // wrong place (in ReplaceTailWithBranchTo()) which results in losing this CFI
398
5.96M
  // instruction.
399
5.96M
  while (I1 != MBB1->end() && 
I1->isCFIInstruction()4.88M
) {
400
152
    ++I1;
401
152
  }
402
5.96M
403
5.96M
  while (I2 != MBB2->end() && 
I2->isCFIInstruction()4.88M
) {
404
152
    ++I2;
405
152
  }
406
5.96M
407
5.96M
  return TailLen;
408
5.96M
}
409
410
void BranchFolder::replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
411
198k
                                           MachineBasicBlock &NewDest) {
412
198k
  if (UpdateLiveIns) {
413
198k
    // OldInst should always point to an instruction.
414
198k
    MachineBasicBlock &OldMBB = *OldInst->getParent();
415
198k
    LiveRegs.clear();
416
198k
    LiveRegs.addLiveOuts(OldMBB);
417
198k
    // Move backward to the place where will insert the jump.
418
198k
    MachineBasicBlock::iterator I = OldMBB.end();
419
748k
    do {
420
748k
      --I;
421
748k
      LiveRegs.stepBackward(*I);
422
748k
    } while (I != OldInst);
423
198k
424
198k
    // Merging the tails may have switched some undef operand to non-undef ones.
425
198k
    // Add IMPLICIT_DEFS into OldMBB as necessary to have a definition of the
426
198k
    // register.
427
685k
    for (MachineBasicBlock::RegisterMaskPair P : NewDest.liveins()) {
428
685k
      // We computed the liveins with computeLiveIn earlier and should only see
429
685k
      // full registers:
430
685k
      assert(P.LaneMask == LaneBitmask::getAll() &&
431
685k
             "Can only handle full register.");
432
685k
      MCPhysReg Reg = P.PhysReg;
433
685k
      if (!LiveRegs.available(*MRI, Reg))
434
685k
        continue;
435
1
      DebugLoc DL;
436
1
      BuildMI(OldMBB, OldInst, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Reg);
437
1
    }
438
198k
  }
439
198k
440
198k
  TII->ReplaceTailWithBranchTo(OldInst, &NewDest);
441
198k
  ++NumTailMerge;
442
198k
}
443
444
MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
445
                                            MachineBasicBlock::iterator BBI1,
446
65.8k
                                            const BasicBlock *BB) {
447
65.8k
  if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
448
6
    return nullptr;
449
65.8k
450
65.8k
  MachineFunction &MF = *CurMBB.getParent();
451
65.8k
452
65.8k
  // Create the fall-through block.
453
65.8k
  MachineFunction::iterator MBBI = CurMBB.getIterator();
454
65.8k
  MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(BB);
455
65.8k
  CurMBB.getParent()->insert(++MBBI, NewMBB);
456
65.8k
457
65.8k
  // Move all the successors of this block to the specified block.
458
65.8k
  NewMBB->transferSuccessors(&CurMBB);
459
65.8k
460
65.8k
  // Add an edge from CurMBB to NewMBB for the fall-through.
461
65.8k
  CurMBB.addSuccessor(NewMBB);
462
65.8k
463
65.8k
  // Splice the code over.
464
65.8k
  NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
465
65.8k
466
65.8k
  // NewMBB belongs to the same loop as CurMBB.
467
65.8k
  if (MLI)
468
5.68k
    if (MachineLoop *ML = MLI->getLoopFor(&CurMBB))
469
210
      ML->addBasicBlockToLoop(NewMBB, MLI->getBase());
470
65.8k
471
65.8k
  // NewMBB inherits CurMBB's block frequency.
472
65.8k
  MBBFreqInfo.setBlockFreq(NewMBB, MBBFreqInfo.getBlockFreq(&CurMBB));
473
65.8k
474
65.8k
  if (UpdateLiveIns)
475
65.8k
    computeAndAddLiveIns(LiveRegs, *NewMBB);
476
65.8k
477
65.8k
  // Add the new block to the EH scope.
478
65.8k
  const auto &EHScopeI = EHScopeMembership.find(&CurMBB);
479
65.8k
  if (EHScopeI != EHScopeMembership.end()) {
480
0
    auto n = EHScopeI->second;
481
0
    EHScopeMembership[NewMBB] = n;
482
0
  }
483
65.8k
484
65.8k
  return NewMBB;
485
65.8k
}
486
487
/// EstimateRuntime - Make a rough estimate for how long it will take to run
488
/// the specified code.
489
static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
490
153k
                                MachineBasicBlock::iterator E) {
491
153k
  unsigned Time = 0;
492
491k
  for (; I != E; 
++I337k
) {
493
337k
    if (!countsAsInstruction(*I))
494
101
      continue;
495
337k
    if (I->isCall())
496
22.5k
      Time += 10;
497
314k
    else if (I->mayLoad() || 
I->mayStore()272k
)
498
69.4k
      Time += 2;
499
245k
    else
500
245k
      ++Time;
501
337k
  }
502
153k
  return Time;
503
153k
}
504
505
// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
506
// branches temporarily for tail merging).  In the case where CurMBB ends
507
// with a conditional branch to the next block, optimize by reversing the
508
// test and conditionally branching to SuccMBB instead.
509
static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
510
3.79M
                    const TargetInstrInfo *TII) {
511
3.79M
  MachineFunction *MF = CurMBB->getParent();
512
3.79M
  MachineFunction::iterator I = std::next(MachineFunction::iterator(CurMBB));
513
3.79M
  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
514
3.79M
  SmallVector<MachineOperand, 4> Cond;
515
3.79M
  DebugLoc dl = CurMBB->findBranchDebugLoc();
516
3.79M
  if (I != MF->end() && 
!TII->analyzeBranch(*CurMBB, TBB, FBB, Cond, true)3.73M
) {
517
3.73M
    MachineBasicBlock *NextBB = &*I;
518
3.73M
    if (TBB == NextBB && 
!Cond.empty()2.19M
&&
!FBB2.19M
) {
519
2.19M
      if (!TII->reverseBranchCondition(Cond)) {
520
2.19M
        TII->removeBranch(*CurMBB);
521
2.19M
        TII->insertBranch(*CurMBB, SuccBB, nullptr, Cond, dl);
522
2.19M
        return;
523
2.19M
      }
524
1.59M
    }
525
3.73M
  }
526
1.59M
  TII->insertBranch(*CurMBB, SuccBB, nullptr,
527
1.59M
                    SmallVector<MachineOperand, 0>(), dl);
528
1.59M
}
529
530
bool
531
11.0M
BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
532
11.0M
  if (getHash() < o.getHash())
533
4.91M
    return true;
534
6.15M
  if (getHash() > o.getHash())
535
2.43M
    return false;
536
3.72M
  if (getBlock()->getNumber() < o.getBlock()->getNumber())
537
2.45M
    return true;
538
1.27M
  if (getBlock()->getNumber() > o.getBlock()->getNumber())
539
1.27M
    return false;
540
0
  // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
541
0
  // an object with itself.
542
0
#ifndef _GLIBCXX_DEBUG
543
0
  llvm_unreachable("Predecessor appears twice");
544
#else
545
  return false;
546
#endif
547
}
548
549
BlockFrequency
550
8.66M
BranchFolder::MBFIWrapper::getBlockFreq(const MachineBasicBlock *MBB) const {
551
8.66M
  auto I = MergedBBFreq.find(MBB);
552
8.66M
553
8.66M
  if (I != MergedBBFreq.end())
554
105k
    return I->second;
555
8.56M
556
8.56M
  return MBFI.getBlockFreq(MBB);
557
8.56M
}
558
559
void BranchFolder::MBFIWrapper::setBlockFreq(const MachineBasicBlock *MBB,
560
166k
                                             BlockFrequency F) {
561
166k
  MergedBBFreq[MBB] = F;
562
166k
}
563
564
raw_ostream &
565
BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
566
0
                                          const MachineBasicBlock *MBB) const {
567
0
  return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
568
0
}
569
570
raw_ostream &
571
BranchFolder::MBFIWrapper::printBlockFreq(raw_ostream &OS,
572
0
                                          const BlockFrequency Freq) const {
573
0
  return MBFI.printBlockFreq(OS, Freq);
574
0
}
575
576
0
void BranchFolder::MBFIWrapper::view(const Twine &Name, bool isSimple) {
577
0
  MBFI.view(Name, isSimple);
578
0
}
579
580
uint64_t
581
113k
BranchFolder::MBFIWrapper::getEntryFreq() const {
582
113k
  return MBFI.getEntryFreq();
583
113k
}
584
585
/// CountTerminators - Count the number of terminators in the given
586
/// block and set I to the position of the first non-terminator, if there
587
/// is one, or MBB->end() otherwise.
588
static unsigned CountTerminators(MachineBasicBlock *MBB,
589
139k
                                 MachineBasicBlock::iterator &I) {
590
139k
  I = MBB->end();
591
139k
  unsigned NumTerms = 0;
592
166k
  while (true) {
593
166k
    if (I == MBB->begin()) {
594
353
      I = MBB->end();
595
353
      break;
596
353
    }
597
166k
    --I;
598
166k
    if (!I->isTerminator()) 
break139k
;
599
26.9k
    ++NumTerms;
600
26.9k
  }
601
139k
  return NumTerms;
602
139k
}
603
604
/// A no successor, non-return block probably ends in unreachable and is cold.
605
/// Also consider a block that ends in an indirect branch to be a return block,
606
/// since many targets use plain indirect branches to return.
607
334k
static bool blockEndsInUnreachable(const MachineBasicBlock *MBB) {
608
334k
  if (!MBB->succ_empty())
609
179k
    return false;
610
154k
  if (MBB->empty())
611
0
    return true;
612
154k
  return !(MBB->back().isReturn() || 
MBB->back().isIndirectBranch()36.9k
);
613
154k
}
614
615
/// ProfitableToMerge - Check if two machine basic blocks have a common tail
616
/// and decide if it would be profitable to merge those tails.  Return the
617
/// length of the common tail and iterators to the first common instruction
618
/// in each block.
619
/// MBB1, MBB2      The blocks to check
620
/// MinCommonTailLength  Minimum size of tail block to be merged.
621
/// CommonTailLen   Out parameter to record the size of the shared tail between
622
///                 MBB1 and MBB2
623
/// I1, I2          Iterator references that will be changed to point to the first
624
///                 instruction in the common tail shared by MBB1,MBB2
625
/// SuccBB          A common successor of MBB1, MBB2 which are in a canonical form
626
///                 relative to SuccBB
627
/// PredBB          The layout predecessor of SuccBB, if any.
628
/// EHScopeMembership  map from block to EH scope #.
629
/// AfterPlacement  True if we are merging blocks after layout. Stricter
630
///                 thresholds apply to prevent undoing tail-duplication.
631
static bool
632
ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2,
633
                  unsigned MinCommonTailLength, unsigned &CommonTailLen,
634
                  MachineBasicBlock::iterator &I1,
635
                  MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB,
636
                  MachineBasicBlock *PredBB,
637
                  DenseMap<const MachineBasicBlock *, int> &EHScopeMembership,
638
5.96M
                  bool AfterPlacement) {
639
5.96M
  // It is never profitable to tail-merge blocks from two different EH scopes.
640
5.96M
  if (!EHScopeMembership.empty()) {
641
122
    auto EHScope1 = EHScopeMembership.find(MBB1);
642
122
    assert(EHScope1 != EHScopeMembership.end());
643
122
    auto EHScope2 = EHScopeMembership.find(MBB2);
644
122
    assert(EHScope2 != EHScopeMembership.end());
645
122
    if (EHScope1->second != EHScope2->second)
646
105
      return false;
647
5.96M
  }
648
5.96M
649
5.96M
  CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
650
5.96M
  if (CommonTailLen == 0)
651
1.08M
    return false;
652
4.88M
  LLVM_DEBUG(dbgs() << "Common tail length of " << printMBBReference(*MBB1)
653
4.88M
                    << " and " << printMBBReference(*MBB2) << " is "
654
4.88M
                    << CommonTailLen << '\n');
655
4.88M
656
4.88M
  // It's almost always profitable to merge any number of non-terminator
657
4.88M
  // instructions with the block that falls through into the common successor.
658
4.88M
  // This is true only for a single successor. For multiple successors, we are
659
4.88M
  // trading a conditional branch for an unconditional one.
660
4.88M
  // TODO: Re-visit successor size for non-layout tail merging.
661
4.88M
  if ((MBB1 == PredBB || 
MBB2 == PredBB4.68M
) &&
662
4.88M
      
(294k
!AfterPlacement294k
||
MBB1->succ_size() == 1162k
)) {
663
139k
    MachineBasicBlock::iterator I;
664
139k
    unsigned NumTerms = CountTerminators(MBB1 == PredBB ? 
MBB2102k
:
MBB137.5k
, I);
665
139k
    if (CommonTailLen > NumTerms)
666
124k
      return true;
667
4.76M
  }
668
4.76M
669
4.76M
  // If these are identical non-return blocks with no successors, merge them.
670
4.76M
  // Such blocks are typically cold calls to noreturn functions like abort, and
671
4.76M
  // are unlikely to become a fallthrough target after machine block placement.
672
4.76M
  // Tail merging these blocks is unlikely to create additional unconditional
673
4.76M
  // branches, and will reduce the size of this cold code.
674
4.76M
  if (I1 == MBB1->begin() && 
I2 == MBB2->begin()506k
&&
675
4.76M
      
blockEndsInUnreachable(MBB1)315k
&&
blockEndsInUnreachable(MBB2)18.4k
)
676
18.4k
    return true;
677
4.74M
678
4.74M
  // If one of the blocks can be completely merged and happens to be in
679
4.74M
  // a position where the other could fall through into it, merge any number
680
4.74M
  // of instructions, because it can be done without a branch.
681
4.74M
  // TODO: If the blocks are not adjacent, move one of them so that they are?
682
4.74M
  if (MBB1->isLayoutSuccessor(MBB2) && 
I2 == MBB2->begin()25.1k
)
683
992
    return true;
684
4.74M
  if (MBB2->isLayoutSuccessor(MBB1) && 
I1 == MBB1->begin()249k
)
685
11.4k
    return true;
686
4.73M
687
4.73M
  // If both blocks are identical and end in a branch, merge them unless they
688
4.73M
  // both have a fallthrough predecessor and successor.
689
4.73M
  // We can only do this after block placement because it depends on whether
690
4.73M
  // there are fallthroughs, and we don't know until after layout.
691
4.73M
  if (AfterPlacement && 
I1 == MBB1->begin()2.12M
&&
I2 == MBB2->begin()144k
) {
692
58.6k
    auto BothFallThrough = [](MachineBasicBlock *MBB) {
693
58.6k
      if (MBB->succ_size() != 0 && 
!MBB->canFallThrough()41.0k
)
694
40.4k
        return false;
695
18.2k
      MachineFunction::iterator I(MBB);
696
18.2k
      MachineFunction *MF = MBB->getParent();
697
18.2k
      return (MBB != &*MF->begin()) && std::prev(I)->canFallThrough();
698
18.2k
    };
699
51.9k
    if (!BothFallThrough(MBB1) || 
!BothFallThrough(MBB2)6.71k
)
700
47.6k
      return true;
701
4.68M
  }
702
4.68M
703
4.68M
  // If both blocks have an unconditional branch temporarily stripped out,
704
4.68M
  // count that as an additional common instruction for the following
705
4.68M
  // heuristics. This heuristic is only accurate for single-succ blocks, so to
706
4.68M
  // make sure that during layout merging and duplicating don't crash, we check
707
4.68M
  // for that when merging during layout.
708
4.68M
  unsigned EffectiveTailLen = CommonTailLen;
709
4.68M
  if (SuccBB && 
MBB1 != PredBB2.77M
&&
MBB2 != PredBB2.66M
&&
710
4.68M
      
(2.60M
MBB1->succ_size() == 12.60M
||
!AfterPlacement1.40M
) &&
711
4.68M
      
!MBB1->back().isBarrier()1.23M
&&
712
4.68M
      
!MBB2->back().isBarrier()1.23M
)
713
1.23M
    ++EffectiveTailLen;
714
4.68M
715
4.68M
  // Check if the common tail is long enough to be worthwhile.
716
4.68M
  if (EffectiveTailLen >= MinCommonTailLength)
717
1.62M
    return true;
718
3.06M
719
3.06M
  // If we are optimizing for code size, 2 instructions in common is enough if
720
3.06M
  // we don't have to split a block.  At worst we will be introducing 1 new
721
3.06M
  // branch instruction, which is likely to be smaller than the 2
722
3.06M
  // instructions that would be deleted in the merge.
723
3.06M
  MachineFunction *MF = MBB1->getParent();
724
3.06M
  return EffectiveTailLen >= 2 && 
MF->getFunction().hasOptSize()2.57M
&&
725
3.06M
         
(2.45k
I1 == MBB1->begin()2.45k
||
I2 == MBB2->begin()1.85k
);
726
3.06M
}
727
728
unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
729
                                        unsigned MinCommonTailLength,
730
                                        MachineBasicBlock *SuccBB,
731
3.39M
                                        MachineBasicBlock *PredBB) {
732
3.39M
  unsigned maxCommonTailLength = 0U;
733
3.39M
  SameTails.clear();
734
3.39M
  MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
735
3.39M
  MPIterator HighestMPIter = std::prev(MergePotentials.end());
736
3.39M
  for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
737
3.39M
                  B = MergePotentials.begin();
738
7.58M
       CurMPIter != B && 
CurMPIter->getHash() == CurHash5.32M
;
--CurMPIter4.18M
) {
739
9.41M
    for (MPIterator I = std::prev(CurMPIter); I->getHash() == CurHash; 
--I5.22M
) {
740
5.96M
      unsigned CommonTailLen;
741
5.96M
      if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
742
5.96M
                            MinCommonTailLength,
743
5.96M
                            CommonTailLen, TrialBBI1, TrialBBI2,
744
5.96M
                            SuccBB, PredBB,
745
5.96M
                            EHScopeMembership,
746
5.96M
                            AfterBlockPlacement)) {
747
1.82M
        if (CommonTailLen > maxCommonTailLength) {
748
124k
          SameTails.clear();
749
124k
          maxCommonTailLength = CommonTailLen;
750
124k
          HighestMPIter = CurMPIter;
751
124k
          SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
752
124k
        }
753
1.82M
        if (HighestMPIter == CurMPIter &&
754
1.82M
            
CommonTailLen == maxCommonTailLength433k
)
755
365k
          SameTails.push_back(SameTailElt(I, TrialBBI2));
756
1.82M
      }
757
5.96M
      if (I == B)
758
740k
        break;
759
5.96M
    }
760
4.18M
  }
761
3.39M
  return maxCommonTailLength;
762
3.39M
}
763
764
void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
765
                                        MachineBasicBlock *SuccBB,
766
3.29M
                                        MachineBasicBlock *PredBB) {
767
3.29M
  MPIterator CurMPIter, B;
768
3.29M
  for (CurMPIter = std::prev(MergePotentials.end()),
769
3.29M
      B = MergePotentials.begin();
770
7.07M
       CurMPIter->getHash() == CurHash; 
--CurMPIter3.77M
) {
771
4.01M
    // Put the unconditional branch back, if we need one.
772
4.01M
    MachineBasicBlock *CurMBB = CurMPIter->getBlock();
773
4.01M
    if (SuccBB && 
CurMBB != PredBB3.66M
)
774
2.17M
      FixTail(CurMBB, SuccBB, TII);
775
4.01M
    if (CurMPIter == B)
776
233k
      break;
777
4.01M
  }
778
3.29M
  if (CurMPIter->getHash() != CurHash)
779
3.06M
    CurMPIter++;
780
3.29M
  MergePotentials.erase(CurMPIter, MergePotentials.end());
781
3.29M
}
782
783
bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
784
                                             MachineBasicBlock *SuccBB,
785
                                             unsigned maxCommonTailLength,
786
65.8k
                                             unsigned &commonTailIndex) {
787
65.8k
  commonTailIndex = 0;
788
65.8k
  unsigned TimeEstimate = ~0U;
789
219k
  for (unsigned i = 0, e = SameTails.size(); i != e; 
++i153k
) {
790
184k
    // Use PredBB if possible; that doesn't require a new branch.
791
184k
    if (SameTails[i].getBlock() == PredBB) {
792
30.4k
      commonTailIndex = i;
793
30.4k
      break;
794
30.4k
    }
795
153k
    // Otherwise, make a (fairly bogus) choice based on estimate of
796
153k
    // how long it will take the various blocks to execute.
797
153k
    unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
798
153k
                                 SameTails[i].getTailStartPos());
799
153k
    if (t <= TimeEstimate) {
800
140k
      TimeEstimate = t;
801
140k
      commonTailIndex = i;
802
140k
    }
803
153k
  }
804
65.8k
805
65.8k
  MachineBasicBlock::iterator BBI =
806
65.8k
    SameTails[commonTailIndex].getTailStartPos();
807
65.8k
  MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
808
65.8k
809
65.8k
  LLVM_DEBUG(dbgs() << "\nSplitting " << printMBBReference(*MBB) << ", size "
810
65.8k
                    << maxCommonTailLength);
811
65.8k
812
65.8k
  // If the split block unconditionally falls-thru to SuccBB, it will be
813
65.8k
  // merged. In control flow terms it should then take SuccBB's name. e.g. If
814
65.8k
  // SuccBB is an inner loop, the common tail is still part of the inner loop.
815
65.8k
  const BasicBlock *BB = (SuccBB && 
MBB->succ_size() == 140.9k
) ?
816
33.1k
    
SuccBB->getBasicBlock()32.6k
: MBB->getBasicBlock();
817
65.8k
  MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI, BB);
818
65.8k
  if (!newMBB) {
819
6
    LLVM_DEBUG(dbgs() << "... failed!");
820
6
    return false;
821
6
  }
822
65.8k
823
65.8k
  SameTails[commonTailIndex].setBlock(newMBB);
824
65.8k
  SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
825
65.8k
826
65.8k
  // If we split PredBB, newMBB is the new predecessor.
827
65.8k
  if (PredBB == MBB)
828
30.4k
    PredBB = newMBB;
829
65.8k
830
65.8k
  return true;
831
65.8k
}
832
833
static void
834
mergeOperations(MachineBasicBlock::iterator MBBIStartPos,
835
198k
                MachineBasicBlock &MBBCommon) {
836
198k
  MachineBasicBlock *MBB = MBBIStartPos->getParent();
837
198k
  // Note CommonTailLen does not necessarily matches the size of
838
198k
  // the common BB nor all its instructions because of debug
839
198k
  // instructions differences.
840
198k
  unsigned CommonTailLen = 0;
841
947k
  for (auto E = MBB->end(); MBBIStartPos != E; 
++MBBIStartPos748k
)
842
748k
    ++CommonTailLen;
843
198k
844
198k
  MachineBasicBlock::reverse_iterator MBBI = MBB->rbegin();
845
198k
  MachineBasicBlock::reverse_iterator MBBIE = MBB->rend();
846
198k
  MachineBasicBlock::reverse_iterator MBBICommon = MBBCommon.rbegin();
847
198k
  MachineBasicBlock::reverse_iterator MBBIECommon = MBBCommon.rend();
848
198k
849
947k
  while (CommonTailLen--) {
850
748k
    assert(MBBI != MBBIE && "Reached BB end within common tail length!");
851
748k
    (void)MBBIE;
852
748k
853
748k
    if (!countsAsInstruction(*MBBI)) {
854
229
      ++MBBI;
855
229
      continue;
856
229
    }
857
748k
858
748k
    
while (748k
(MBBICommon != MBBIECommon) && !countsAsInstruction(*MBBICommon))
859
228
      ++MBBICommon;
860
748k
861
748k
    assert(MBBICommon != MBBIECommon &&
862
748k
           "Reached BB end within common tail length!");
863
748k
    assert(MBBICommon->isIdenticalTo(*MBBI) && "Expected matching MIIs!");
864
748k
865
748k
    // Merge MMOs from memory operations in the common block.
866
748k
    if (MBBICommon->mayLoad() || 
MBBICommon->mayStore()554k
)
867
211k
      MBBICommon->cloneMergedMemRefs(*MBB->getParent(), {&*MBBICommon, &*MBBI});
868
748k
    // Drop undef flags if they aren't present in all merged instructions.
869
3.56M
    for (unsigned I = 0, E = MBBICommon->getNumOperands(); I != E; 
++I2.81M
) {
870
2.81M
      MachineOperand &MO = MBBICommon->getOperand(I);
871
2.81M
      if (MO.isReg() && 
MO.isUndef()2.00M
) {
872
31.3k
        const MachineOperand &OtherMO = MBBI->getOperand(I);
873
31.3k
        if (!OtherMO.isUndef())
874
27
          MO.setIsUndef(false);
875
31.3k
      }
876
2.81M
    }
877
748k
878
748k
    ++MBBI;
879
748k
    ++MBBICommon;
880
748k
  }
881
198k
}
882
883
100k
void BranchFolder::mergeCommonTails(unsigned commonTailIndex) {
884
100k
  MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
885
100k
886
100k
  std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
887
399k
  for (unsigned int i = 0 ; i != SameTails.size() ; 
++i298k
) {
888
298k
    if (i != commonTailIndex) {
889
198k
      NextCommonInsts[i] = SameTails[i].getTailStartPos();
890
198k
      mergeOperations(SameTails[i].getTailStartPos(), *MBB);
891
198k
    } else {
892
100k
      assert(SameTails[i].getTailStartPos() == MBB->begin() &&
893
100k
          "MBB is not a common tail only block");
894
100k
    }
895
298k
  }
896
100k
897
323k
  for (auto &MI : *MBB) {
898
323k
    if (!countsAsInstruction(MI))
899
194
      continue;
900
322k
    DebugLoc DL = MI.getDebugLoc();
901
1.39M
    for (unsigned int i = 0 ; i < NextCommonInsts.size() ; 
i++1.07M
) {
902
1.07M
      if (i == commonTailIndex)
903
322k
        continue;
904
748k
905
748k
      auto &Pos = NextCommonInsts[i];
906
748k
      assert(Pos != SameTails[i].getBlock()->end() &&
907
748k
          "Reached BB end within common tail");
908
748k
      while (!countsAsInstruction(*Pos)) {
909
227
        ++Pos;
910
227
        assert(Pos != SameTails[i].getBlock()->end() &&
911
227
            "Reached BB end within common tail");
912
227
      }
913
748k
      assert(MI.isIdenticalTo(*Pos) && "Expected matching MIIs!");
914
748k
      DL = DILocation::getMergedLocation(DL, Pos->getDebugLoc());
915
748k
      NextCommonInsts[i] = ++Pos;
916
748k
    }
917
322k
    MI.setDebugLoc(DL);
918
322k
  }
919
100k
920
100k
  if (UpdateLiveIns) {
921
100k
    LivePhysRegs NewLiveIns(*TRI);
922
100k
    computeLiveIns(NewLiveIns, *MBB);
923
100k
    LiveRegs.init(*TRI);
924
100k
925
100k
    // The flag merging may lead to some register uses no longer using the
926
100k
    // <undef> flag, add IMPLICIT_DEFs in the predecessors as necessary.
927
124k
    for (MachineBasicBlock *Pred : MBB->predecessors()) {
928
124k
      LiveRegs.clear();
929
124k
      LiveRegs.addLiveOuts(*Pred);
930
124k
      MachineBasicBlock::iterator InsertBefore = Pred->getFirstTerminator();
931
1.30M
      for (unsigned Reg : NewLiveIns) {
932
1.30M
        if (!LiveRegs.available(*MRI, Reg))
933
1.29M
          continue;
934
43
        DebugLoc DL;
935
43
        BuildMI(*Pred, InsertBefore, DL, TII->get(TargetOpcode::IMPLICIT_DEF),
936
43
                Reg);
937
43
      }
938
124k
    }
939
100k
940
100k
    MBB->clearLiveIns();
941
100k
    addLiveIns(*MBB, NewLiveIns);
942
100k
  }
943
100k
}
944
945
// See if any of the blocks in MergePotentials (which all have SuccBB as a
946
// successor, or all have no successor if it is null) can be tail-merged.
947
// If there is a successor, any blocks in MergePotentials that are not
948
// tail-merged and are not immediately before Succ must have an unconditional
949
// branch to Succ added (but the predecessor/successor lists need no
950
// adjustment). The lone predecessor of Succ that falls through into Succ,
951
// if any, is given in PredBB.
952
// MinCommonTailLength - Except for the special cases below, tail-merge if
953
// there are at least this many instructions in common.
954
bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
955
                                      MachineBasicBlock *PredBB,
956
2.22M
                                      unsigned MinCommonTailLength) {
957
2.22M
  bool MadeChange = false;
958
2.22M
959
2.22M
  LLVM_DEBUG(
960
2.22M
      dbgs() << "\nTryTailMergeBlocks: ";
961
2.22M
      for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i) dbgs()
962
2.22M
      << printMBBReference(*MergePotentials[i].getBlock())
963
2.22M
      << (i == e - 1 ? "" : ", ");
964
2.22M
      dbgs() << "\n"; if (SuccBB) {
965
2.22M
        dbgs() << "  with successor " << printMBBReference(*SuccBB) << '\n';
966
2.22M
        if (PredBB)
967
2.22M
          dbgs() << "  which has fall-through from "
968
2.22M
                 << printMBBReference(*PredBB) << "\n";
969
2.22M
      } dbgs() << "Looking for common tails of at least "
970
2.22M
               << MinCommonTailLength << " instruction"
971
2.22M
               << (MinCommonTailLength == 1 ? "" : "s") << '\n';);
972
2.22M
973
2.22M
  // Sort by hash value so that blocks with identical end sequences sort
974
2.22M
  // together.
975
2.22M
  array_pod_sort(MergePotentials.begin(), MergePotentials.end());
976
2.22M
977
2.22M
  // Walk through equivalence sets looking for actual exact matches.
978
5.61M
  while (MergePotentials.size() > 1) {
979
3.39M
    unsigned CurHash = MergePotentials.back().getHash();
980
3.39M
981
3.39M
    // Build SameTails, identifying the set of blocks with this hash code
982
3.39M
    // and with the maximum number of instructions in common.
983
3.39M
    unsigned maxCommonTailLength = ComputeSameTails(CurHash,
984
3.39M
                                                    MinCommonTailLength,
985
3.39M
                                                    SuccBB, PredBB);
986
3.39M
987
3.39M
    // If we didn't find any pair that has at least MinCommonTailLength
988
3.39M
    // instructions in common, remove all blocks with this hash code and retry.
989
3.39M
    if (SameTails.empty()) {
990
3.29M
      RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
991
3.29M
      continue;
992
3.29M
    }
993
100k
994
100k
    // If one of the blocks is the entire common tail (and not the entry
995
100k
    // block, which we can't jump to), we can treat all blocks with this same
996
100k
    // tail at once.  Use PredBB if that is one of the possibilities, as that
997
100k
    // will not introduce any extra branches.
998
100k
    MachineBasicBlock *EntryBB =
999
100k
        &MergePotentials.front().getBlock()->getParent()->front();
1000
100k
    unsigned commonTailIndex = SameTails.size();
1001
100k
    // If there are two blocks, check to see if one can be made to fall through
1002
100k
    // into the other.
1003
100k
    if (SameTails.size() == 2 &&
1004
100k
        
SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock())77.9k
&&
1005
100k
        
SameTails[1].tailIsWholeBlock()1.33k
)
1006
449
      commonTailIndex = 1;
1007
100k
    else if (SameTails.size() == 2 &&
1008
100k
             SameTails[1].getBlock()->isLayoutSuccessor(
1009
77.5k
                                                     SameTails[0].getBlock()) &&
1010
100k
             
SameTails[0].tailIsWholeBlock()23.5k
)
1011
7.83k
      commonTailIndex = 0;
1012
92.3k
    else {
1013
92.3k
      // Otherwise just pick one, favoring the fall-through predecessor if
1014
92.3k
      // there is one.
1015
292k
      for (unsigned i = 0, e = SameTails.size(); i != e; 
++i199k
) {
1016
244k
        MachineBasicBlock *MBB = SameTails[i].getBlock();
1017
244k
        if (MBB == EntryBB && 
SameTails[i].tailIsWholeBlock()216
)
1018
2
          continue;
1019
244k
        if (MBB == PredBB) {
1020
44.5k
          commonTailIndex = i;
1021
44.5k
          break;
1022
44.5k
        }
1023
199k
        if (SameTails[i].tailIsWholeBlock())
1024
42.3k
          commonTailIndex = i;
1025
199k
      }
1026
92.3k
    }
1027
100k
1028
100k
    if (commonTailIndex == SameTails.size() ||
1029
100k
        
(65.2k
SameTails[commonTailIndex].getBlock() == PredBB65.2k
&&
1030
65.8k
         
!SameTails[commonTailIndex].tailIsWholeBlock()45.3k
)) {
1031
65.8k
      // None of the blocks consist entirely of the common tail.
1032
65.8k
      // Split a block so that one does.
1033
65.8k
      if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
1034
65.8k
                                     maxCommonTailLength, commonTailIndex)) {
1035
6
        RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
1036
6
        continue;
1037
6
      }
1038
100k
    }
1039
100k
1040
100k
    MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
1041
100k
1042
100k
    // Recompute common tail MBB's edge weights and block frequency.
1043
100k
    setCommonTailEdgeWeights(*MBB);
1044
100k
1045
100k
    // Merge debug locations, MMOs and undef flags across identical instructions
1046
100k
    // for common tail.
1047
100k
    mergeCommonTails(commonTailIndex);
1048
100k
1049
100k
    // MBB is common tail.  Adjust all other BB's to jump to this one.
1050
100k
    // Traversal must be forwards so erases work.
1051
100k
    LLVM_DEBUG(dbgs() << "\nUsing common tail in " << printMBBReference(*MBB)
1052
100k
                      << " for ");
1053
399k
    for (unsigned int i=0, e = SameTails.size(); i != e; 
++i298k
) {
1054
298k
      if (commonTailIndex == i)
1055
100k
        continue;
1056
198k
      LLVM_DEBUG(dbgs() << printMBBReference(*SameTails[i].getBlock())
1057
198k
                        << (i == e - 1 ? "" : ", "));
1058
198k
      // Hack the end off BB i, making it jump to BB commonTailIndex instead.
1059
198k
      replaceTailWithBranchTo(SameTails[i].getTailStartPos(), *MBB);
1060
198k
      // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
1061
198k
      MergePotentials.erase(SameTails[i].getMPIter());
1062
198k
    }
1063
100k
    LLVM_DEBUG(dbgs() << "\n");
1064
100k
    // We leave commonTailIndex in the worklist in case there are other blocks
1065
100k
    // that match it with a smaller number of instructions.
1066
100k
    MadeChange = true;
1067
100k
  }
1068
2.22M
  return MadeChange;
1069
2.22M
}
1070
1071
786k
bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
1072
786k
  bool MadeChange = false;
1073
786k
  if (!EnableTailMerge)
1074
25.0k
    return MadeChange;
1075
760k
1076
760k
  // First find blocks with no successors.
1077
760k
  // Block placement may create new tail merging opportunities for these blocks.
1078
760k
  MergePotentials.clear();
1079
8.70M
  for (MachineBasicBlock &MBB : MF) {
1080
8.70M
    if (MergePotentials.size() == TailMergeThreshold)
1081
2
      break;
1082
8.70M
    if (!TriedMerging.count(&MBB) && 
MBB.succ_empty()8.69M
)
1083
1.17M
      MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(MBB), &MBB));
1084
8.70M
  }
1085
760k
1086
760k
  // If this is a large problem, avoid visiting the same basic blocks
1087
760k
  // multiple times.
1088
760k
  if (MergePotentials.size() == TailMergeThreshold)
1089
154
    
for (unsigned i = 0, e = MergePotentials.size(); 2
i != e;
++i152
)
1090
152
      TriedMerging.insert(MergePotentials[i].getBlock());
1091
760k
1092
760k
  // See if we can do any tail merging on those.
1093
760k
  if (MergePotentials.size() >= 2)
1094
121k
    MadeChange |= TryTailMergeBlocks(nullptr, nullptr, MinCommonTailLength);
1095
760k
1096
760k
  // Look at blocks (IBB) with multiple predecessors (PBB).
1097
760k
  // We change each predecessor to a canonical form, by
1098
760k
  // (1) temporarily removing any unconditional branch from the predecessor
1099
760k
  // to IBB, and
1100
760k
  // (2) alter conditional branches so they branch to the other block
1101
760k
  // not IBB; this may require adding back an unconditional branch to IBB
1102
760k
  // later, where there wasn't one coming in.  E.g.
1103
760k
  //   Bcc IBB
1104
760k
  //   fallthrough to QBB
1105
760k
  // here becomes
1106
760k
  //   Bncc QBB
1107
760k
  // with a conceptual B to IBB after that, which never actually exists.
1108
760k
  // With those changes, we see whether the predecessors' tails match,
1109
760k
  // and merge them if so.  We change things out of canonical form and
1110
760k
  // back to the way they were later in the process.  (OptimizeBranches
1111
760k
  // would undo some of this, but we can't use it, because we'd get into
1112
760k
  // a compile-time infinite loop repeatedly doing and undoing the same
1113
760k
  // transformations.)
1114
760k
1115
760k
  for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1116
8.73M
       I != E; 
++I7.96M
) {
1117
7.96M
    if (I->pred_size() < 2) 
continue5.23M
;
1118
2.73M
    SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
1119
2.73M
    MachineBasicBlock *IBB = &*I;
1120
2.73M
    MachineBasicBlock *PredBB = &*std::prev(I);
1121
2.73M
    MergePotentials.clear();
1122
2.73M
    MachineLoop *ML;
1123
2.73M
1124
2.73M
    // Bail if merging after placement and IBB is the loop header because
1125
2.73M
    // -- If merging predecessors that belong to the same loop as IBB, the
1126
2.73M
    // common tail of merged predecessors may become the loop top if block
1127
2.73M
    // placement is called again and the predecessors may branch to this common
1128
2.73M
    // tail and require more branches. This can be relaxed if
1129
2.73M
    // MachineBlockPlacement::findBestLoopTop is more flexible.
1130
2.73M
    // --If merging predecessors that do not belong to the same loop as IBB, the
1131
2.73M
    // loop info of IBB's loop and the other loops may be affected. Calling the
1132
2.73M
    // block placement again may make big change to the layout and eliminate the
1133
2.73M
    // reason to do tail merging here.
1134
2.73M
    if (AfterBlockPlacement && 
MLI915k
) {
1135
915k
      ML = MLI->getLoopFor(IBB);
1136
915k
      if (ML && 
IBB == ML->getHeader()410k
)
1137
215k
        continue;
1138
2.51M
    }
1139
2.51M
1140
6.64M
    
for (MachineBasicBlock *PBB : I->predecessors())2.51M
{
1141
6.64M
      if (MergePotentials.size() == TailMergeThreshold)
1142
19
        break;
1143
6.64M
1144
6.64M
      if (TriedMerging.count(PBB))
1145
8.46k
        continue;
1146
6.64M
1147
6.64M
      // Skip blocks that loop to themselves, can't tail merge these.
1148
6.64M
      if (PBB == IBB)
1149
285k
        continue;
1150
6.35M
1151
6.35M
      // Visit each predecessor only once.
1152
6.35M
      if (!UniquePreds.insert(PBB).second)
1153
0
        continue;
1154
6.35M
1155
6.35M
      // Skip blocks which may jump to a landing pad. Can't tail merge these.
1156
6.35M
      if (PBB->hasEHPadSuccessor())
1157
93.9k
        continue;
1158
6.26M
1159
6.26M
      // After block placement, only consider predecessors that belong to the
1160
6.26M
      // same loop as IBB.  The reason is the same as above when skipping loop
1161
6.26M
      // header.
1162
6.26M
      if (AfterBlockPlacement && 
MLI1.95M
)
1163
1.95M
        if (ML != MLI->getLoopFor(PBB))
1164
203k
          continue;
1165
6.05M
1166
6.05M
      MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1167
6.05M
      SmallVector<MachineOperand, 4> Cond;
1168
6.05M
      if (!TII->analyzeBranch(*PBB, TBB, FBB, Cond, true)) {
1169
6.04M
        // Failing case: IBB is the target of a cbr, and we cannot reverse the
1170
6.04M
        // branch.
1171
6.04M
        SmallVector<MachineOperand, 4> NewCond(Cond);
1172
6.04M
        if (!Cond.empty() && 
TBB == IBB3.19M
) {
1173
2.46M
          if (TII->reverseBranchCondition(NewCond))
1174
68
            continue;
1175
2.46M
          // This is the QBB case described above
1176
2.46M
          if (!FBB) {
1177
2.05M
            auto Next = ++PBB->getIterator();
1178
2.05M
            if (Next != MF.end())
1179
2.05M
              FBB = &*Next;
1180
2.05M
          }
1181
2.46M
        }
1182
6.04M
1183
6.04M
        // Remove the unconditional branch at the end, if any.
1184
6.04M
        
if (6.04M
TBB6.04M
&&
(4.44M
Cond.empty()4.44M
||
FBB3.19M
)) {
1185
3.93M
          DebugLoc dl = PBB->findBranchDebugLoc();
1186
3.93M
          TII->removeBranch(*PBB);
1187
3.93M
          if (!Cond.empty())
1188
2.68M
            // reinsert conditional branch only, for now
1189
2.68M
            TII->insertBranch(*PBB, (TBB == IBB) ? 
FBB2.46M
:
TBB219k
, nullptr,
1190
2.68M
                              NewCond, dl);
1191
3.93M
        }
1192
6.04M
1193
6.04M
        MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(*PBB), PBB));
1194
6.04M
      }
1195
6.05M
    }
1196
2.51M
1197
2.51M
    // If this is a large problem, avoid visiting the same basic blocks multiple
1198
2.51M
    // times.
1199
2.51M
    if (MergePotentials.size() == TailMergeThreshold)
1200
2.57k
      
for (unsigned i = 0, e = MergePotentials.size(); 19
i != e;
++i2.55k
)
1201
2.55k
        TriedMerging.insert(MergePotentials[i].getBlock());
1202
2.51M
1203
2.51M
    if (MergePotentials.size() >= 2)
1204
2.10M
      MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1205
2.51M
1206
2.51M
    // Reinsert an unconditional branch if needed. The 1 below can occur as a
1207
2.51M
    // result of removing blocks in TryTailMergeBlocks.
1208
2.51M
    PredBB = &*std::prev(I); // this may have been changed in TryTailMergeBlocks
1209
2.51M
    if (MergePotentials.size() == 1 &&
1210
2.51M
        
MergePotentials.begin()->getBlock() != PredBB2.28M
)
1211
1.61M
      FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1212
2.51M
  }
1213
760k
1214
760k
  return MadeChange;
1215
760k
}
1216
1217
100k
void BranchFolder::setCommonTailEdgeWeights(MachineBasicBlock &TailMBB) {
1218
100k
  SmallVector<BlockFrequency, 2> EdgeFreqLs(TailMBB.succ_size());
1219
100k
  BlockFrequency AccumulatedMBBFreq;
1220
100k
1221
100k
  // Aggregate edge frequency of successor edge j:
1222
100k
  //  edgeFreq(j) = sum (freq(bb) * edgeProb(bb, j)),
1223
100k
  //  where bb is a basic block that is in SameTails.
1224
298k
  for (const auto &Src : SameTails) {
1225
298k
    const MachineBasicBlock *SrcMBB = Src.getBlock();
1226
298k
    BlockFrequency BlockFreq = MBBFreqInfo.getBlockFreq(SrcMBB);
1227
298k
    AccumulatedMBBFreq += BlockFreq;
1228
298k
1229
298k
    // It is not necessary to recompute edge weights if TailBB has less than two
1230
298k
    // successors.
1231
298k
    if (TailMBB.succ_size() <= 1)
1232
274k
      continue;
1233
24.8k
1234
24.8k
    auto EdgeFreq = EdgeFreqLs.begin();
1235
24.8k
1236
24.8k
    for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1237
74.6k
         SuccI != SuccE; 
++SuccI, ++EdgeFreq49.7k
)
1238
49.7k
      *EdgeFreq += BlockFreq * MBPI.getEdgeProbability(SrcMBB, *SuccI);
1239
24.8k
  }
1240
100k
1241
100k
  MBBFreqInfo.setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1242
100k
1243
100k
  if (TailMBB.succ_size() <= 1)
1244
88.7k
    return;
1245
11.8k
1246
11.8k
  auto SumEdgeFreq =
1247
11.8k
      std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(), BlockFrequency(0))
1248
11.8k
          .getFrequency();
1249
11.8k
  auto EdgeFreq = EdgeFreqLs.begin();
1250
11.8k
1251
11.8k
  if (SumEdgeFreq > 0) {
1252
11.6k
    for (auto SuccI = TailMBB.succ_begin(), SuccE = TailMBB.succ_end();
1253
35.0k
         SuccI != SuccE; 
++SuccI, ++EdgeFreq23.3k
) {
1254
23.3k
      auto Prob = BranchProbability::getBranchProbability(
1255
23.3k
          EdgeFreq->getFrequency(), SumEdgeFreq);
1256
23.3k
      TailMBB.setSuccProbability(SuccI, Prob);
1257
23.3k
    }
1258
11.6k
  }
1259
11.8k
}
1260
1261
//===----------------------------------------------------------------------===//
1262
//  Branch Optimization
1263
//===----------------------------------------------------------------------===//
1264
1265
673k
bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
1266
673k
  bool MadeChange = false;
1267
673k
1268
673k
  // Make sure blocks are numbered in order
1269
673k
  MF.RenumberBlocks();
1270
673k
  // Renumbering blocks alters EH scope membership, recalculate it.
1271
673k
  EHScopeMembership = getEHScopeMembership(MF);
1272
673k
1273
673k
  for (MachineFunction::iterator I = std::next(MF.begin()), E = MF.end();
1274
6.81M
       I != E; ) {
1275
6.14M
    MachineBasicBlock *MBB = &*I++;
1276
6.14M
    MadeChange |= OptimizeBlock(MBB);
1277
6.14M
1278
6.14M
    // If it is dead, remove it.
1279
6.14M
    if (MBB->pred_empty()) {
1280
207k
      RemoveDeadBlock(MBB);
1281
207k
      MadeChange = true;
1282
207k
      ++NumDeadBlocks;
1283
207k
    }
1284
6.14M
  }
1285
673k
1286
673k
  return MadeChange;
1287
673k
}
1288
1289
// Blocks should be considered empty if they contain only debug info;
1290
// else the debug info would affect codegen.
1291
13.2M
static bool IsEmptyBlock(MachineBasicBlock *MBB) {
1292
13.2M
  return MBB->getFirstNonDebugInstr() == MBB->end();
1293
13.2M
}
1294
1295
// Blocks with only debug info and branches should be considered the same
1296
// as blocks with only branches.
1297
1.21M
static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
1298
1.21M
  MachineBasicBlock::iterator I = MBB->getFirstNonDebugInstr();
1299
1.21M
  assert(I != MBB->end() && "empty block!");
1300
1.21M
  return I->isBranch();
1301
1.21M
}
1302
1303
/// IsBetterFallthrough - Return true if it would be clearly better to
1304
/// fall-through to MBB1 than to fall through into MBB2.  This has to return
1305
/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
1306
/// result in infinite loops.
1307
static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
1308
20.3k
                                MachineBasicBlock *MBB2) {
1309
20.3k
  // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
1310
20.3k
  // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
1311
20.3k
  // optimize branches that branch to either a return block or an assert block
1312
20.3k
  // into a fallthrough to the return.
1313
20.3k
  MachineBasicBlock::iterator MBB1I = MBB1->getLastNonDebugInstr();
1314
20.3k
  MachineBasicBlock::iterator MBB2I = MBB2->getLastNonDebugInstr();
1315
20.3k
  if (MBB1I == MBB1->end() || 
MBB2I == MBB2->end()20.3k
)
1316
12
    return false;
1317
20.3k
1318
20.3k
  // If there is a clear successor ordering we make sure that one block
1319
20.3k
  // will fall through to the next
1320
20.3k
  if (MBB1->isSuccessor(MBB2)) 
return true50
;
1321
20.2k
  if (MBB2->isSuccessor(MBB1)) 
return false0
;
1322
20.2k
1323
20.2k
  return MBB2I->isCall() && 
!MBB1I->isCall()4.02k
;
1324
20.2k
}
1325
1326
/// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1327
/// instructions on the block.
1328
725k
static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1329
725k
  MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
1330
725k
  if (I != MBB.end() && I->isBranch())
1331
722k
    return I->getDebugLoc();
1332
3.13k
  return DebugLoc();
1333
3.13k
}
1334
1335
static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII,
1336
                                       MachineBasicBlock &MBB,
1337
5.28k
                                       MachineBasicBlock &PredMBB) {
1338
5.28k
  auto InsertBefore = PredMBB.getFirstTerminator();
1339
5.28k
  for (MachineInstr &MI : MBB.instrs())
1340
3
    if (MI.isDebugInstr()) {
1341
3
      TII->duplicate(PredMBB, InsertBefore, MI);
1342
3
      LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to pred: "
1343
3
                        << MI);
1344
3
    }
1345
5.28k
}
1346
1347
static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII,
1348
                                     MachineBasicBlock &MBB,
1349
115
                                     MachineBasicBlock &SuccMBB) {
1350
115
  auto InsertBefore = SuccMBB.SkipPHIsAndLabels(SuccMBB.begin());
1351
115
  for (MachineInstr &MI : MBB.instrs())
1352
1
    if (MI.isDebugInstr()) {
1353
1
      TII->duplicate(SuccMBB, InsertBefore, MI);
1354
1
      LLVM_DEBUG(dbgs() << "Copied debug entity from empty block to succ: "
1355
1
                        << MI);
1356
1
    }
1357
115
}
1358
1359
// Try to salvage DBG_VALUE instructions from an otherwise empty block. If such
1360
// a basic block is removed we would lose the debug information unless we have
1361
// copied the information to a predecessor/successor.
1362
//
1363
// TODO: This function only handles some simple cases. An alternative would be
1364
// to run a heavier analysis, such as the LiveDebugValues pass, before we do
1365
// branch folding.
1366
static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII,
1367
50.9k
                                           MachineBasicBlock &MBB) {
1368
50.9k
  assert(IsEmptyBlock(&MBB) && "Expected an empty block (except debug info).");
1369
50.9k
  // If this MBB is the only predecessor of a successor it is legal to copy
1370
50.9k
  // DBG_VALUE instructions to the beginning of the successor.
1371
50.9k
  for (MachineBasicBlock *SuccBB : MBB.successors())
1372
42.1k
    if (SuccBB->pred_size() == 1)
1373
115
      copyDebugInfoToSuccessor(TII, MBB, *SuccBB);
1374
50.9k
  // If this MBB is the only successor of a predecessor it is legal to copy the
1375
50.9k
  // DBG_VALUE instructions to the end of the predecessor (just before the
1376
50.9k
  // terminators, assuming that the terminator isn't affecting the DBG_VALUE).
1377
50.9k
  for (MachineBasicBlock *PredBB : MBB.predecessors())
1378
53.2k
    if (PredBB->succ_size() == 1)
1379
5.28k
      copyDebugInfoToPredecessor(TII, MBB, *PredBB);
1380
50.9k
}
1381
1382
6.14M
bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1383
6.14M
  bool MadeChange = false;
1384
6.14M
  MachineFunction &MF = *MBB->getParent();
1385
6.86M
ReoptimizeBlock:
1386
6.86M
1387
6.86M
  MachineFunction::iterator FallThrough = MBB->getIterator();
1388
6.86M
  ++FallThrough;
1389
6.86M
1390
6.86M
  // Make sure MBB and FallThrough belong to the same EH scope.
1391
6.86M
  bool SameEHScope = true;
1392
6.86M
  if (!EHScopeMembership.empty() && 
FallThrough != MF.end()1.11k
) {
1393
920
    auto MBBEHScope = EHScopeMembership.find(MBB);
1394
920
    assert(MBBEHScope != EHScopeMembership.end());
1395
920
    auto FallThroughEHScope = EHScopeMembership.find(&*FallThrough);
1396
920
    assert(FallThroughEHScope != EHScopeMembership.end());
1397
920
    SameEHScope = MBBEHScope->second == FallThroughEHScope->second;
1398
920
  }
1399
6.86M
1400
6.86M
  // If this block is empty, make everyone use its fall-through, not the block
1401
6.86M
  // explicitly.  Landing pads should not do this since the landing-pad table
1402
6.86M
  // points to this block.  Blocks with their addresses taken shouldn't be
1403
6.86M
  // optimized away.
1404
6.86M
  if (IsEmptyBlock(MBB) && 
!MBB->isEHPad()50.9k
&&
!MBB->hasAddressTaken()50.9k
&&
1405
6.86M
      
SameEHScope50.9k
) {
1406
50.9k
    salvageDebugInfoFromEmptyBlock(TII, *MBB);
1407
50.9k
    // Dead block?  Leave for cleanup later.
1408
50.9k
    if (MBB->pred_empty()) 
return MadeChange4.74k
;
1409
46.2k
1410
46.2k
    if (FallThrough == MF.end()) {
1411
285
      // TODO: Simplify preds to not branch here if possible!
1412
45.9k
    } else if (FallThrough->isEHPad()) {
1413
536
      // Don't rewrite to a landing pad fallthough.  That could lead to the case
1414
536
      // where a BB jumps to more than one landing pad.
1415
536
      // TODO: Is it ever worth rewriting predecessors which don't already
1416
536
      // jump to a landing pad, and so can safely jump to the fallthrough?
1417
45.3k
    } else if (MBB->isSuccessor(&*FallThrough)) {
1418
42.1k
      // Rewrite all predecessors of the old block to go to the fallthrough
1419
42.1k
      // instead.
1420
91.1k
      while (!MBB->pred_empty()) {
1421
48.9k
        MachineBasicBlock *Pred = *(MBB->pred_end()-1);
1422
48.9k
        Pred->ReplaceUsesOfBlockWith(MBB, &*FallThrough);
1423
48.9k
      }
1424
42.1k
      // If MBB was the target of a jump table, update jump tables to go to the
1425
42.1k
      // fallthrough instead.
1426
42.1k
      if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1427
1.68k
        MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1428
42.1k
      MadeChange = true;
1429
42.1k
    }
1430
46.2k
    return MadeChange;
1431
46.2k
  }
1432
6.81M
1433
6.81M
  // Check to see if we can simplify the terminator of the block before this
1434
6.81M
  // one.
1435
6.81M
  MachineBasicBlock &PrevBB = *std::prev(MachineFunction::iterator(MBB));
1436
6.81M
1437
6.81M
  MachineBasicBlock *PriorTBB = nullptr, *PriorFBB = nullptr;
1438
6.81M
  SmallVector<MachineOperand, 4> PriorCond;
1439
6.81M
  bool PriorUnAnalyzable =
1440
6.81M
      TII->analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
1441
6.81M
  if (!PriorUnAnalyzable) {
1442
6.60M
    // If the CFG for the prior block has extra edges, remove them.
1443
6.60M
    MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1444
6.60M
                                              !PriorCond.empty());
1445
6.60M
1446
6.60M
    // If the previous branch is conditional and both conditions go to the same
1447
6.60M
    // destination, remove the branch, replacing it with an unconditional one or
1448
6.60M
    // a fall-through.
1449
6.60M
    if (PriorTBB && 
PriorTBB == PriorFBB5.02M
) {
1450
13
      DebugLoc dl = getBranchDebugLoc(PrevBB);
1451
13
      TII->removeBranch(PrevBB);
1452
13
      PriorCond.clear();
1453
13
      if (PriorTBB != MBB)
1454
3
        TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1455
13
      MadeChange = true;
1456
13
      ++NumBranchOpts;
1457
13
      goto ReoptimizeBlock;
1458
13
    }
1459
6.60M
1460
6.60M
    // If the previous block unconditionally falls through to this block and
1461
6.60M
    // this block has no other predecessors, move the contents of this block
1462
6.60M
    // into the prior block. This doesn't usually happen when SimplifyCFG
1463
6.60M
    // has been used, but it can happen if tail merging splits a fall-through
1464
6.60M
    // predecessor of a block.
1465
6.60M
    // This has to check PrevBB->succ_size() because EH edges are ignored by
1466
6.60M
    // AnalyzeBranch.
1467
6.60M
    if (PriorCond.empty() && 
!PriorTBB2.69M
&&
MBB->pred_size() == 11.57M
&&
1468
6.60M
        
PrevBB.succ_size() == 1149k
&&
1469
6.60M
        
!MBB->hasAddressTaken()14.0k
&&
!MBB->isEHPad()14.0k
) {
1470
14.0k
      LLVM_DEBUG(dbgs() << "\nMerging into block: " << PrevBB
1471
14.0k
                        << "From MBB: " << *MBB);
1472
14.0k
      // Remove redundant DBG_VALUEs first.
1473
14.0k
      if (PrevBB.begin() != PrevBB.end()) {
1474
13.8k
        MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1475
13.8k
        --PrevBBIter;
1476
13.8k
        MachineBasicBlock::iterator MBBIter = MBB->begin();
1477
13.8k
        // Check if DBG_VALUE at the end of PrevBB is identical to the
1478
13.8k
        // DBG_VALUE at the beginning of MBB.
1479
13.8k
        while (PrevBBIter != PrevBB.begin() && 
MBBIter != MBB->end()5.11k
1480
13.8k
               && 
PrevBBIter->isDebugInstr()5.11k
&&
MBBIter->isDebugInstr()1
) {
1481
1
          if (!MBBIter->isIdenticalTo(*PrevBBIter))
1482
0
            break;
1483
1
          MachineInstr &DuplicateDbg = *MBBIter;
1484
1
          ++MBBIter; -- PrevBBIter;
1485
1
          DuplicateDbg.eraseFromParent();
1486
1
        }
1487
13.8k
      }
1488
14.0k
      PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
1489
14.0k
      PrevBB.removeSuccessor(PrevBB.succ_begin());
1490
14.0k
      assert(PrevBB.succ_empty());
1491
14.0k
      PrevBB.transferSuccessors(MBB);
1492
14.0k
      MadeChange = true;
1493
14.0k
      return MadeChange;
1494
14.0k
    }
1495
6.59M
1496
6.59M
    // If the previous branch *only* branches to *this* block (conditional or
1497
6.59M
    // not) remove the branch.
1498
6.59M
    if (PriorTBB == MBB && 
!PriorFBB275k
) {
1499
130k
      TII->removeBranch(PrevBB);
1500
130k
      MadeChange = true;
1501
130k
      ++NumBranchOpts;
1502
130k
      goto ReoptimizeBlock;
1503
130k
    }
1504
6.45M
1505
6.45M
    // If the prior block branches somewhere else on the condition and here if
1506
6.45M
    // the condition is false, remove the uncond second branch.
1507
6.45M
    if (PriorFBB == MBB) {
1508
234k
      DebugLoc dl = getBranchDebugLoc(PrevBB);
1509
234k
      TII->removeBranch(PrevBB);
1510
234k
      TII->insertBranch(PrevBB, PriorTBB, nullptr, PriorCond, dl);
1511
234k
      MadeChange = true;
1512
234k
      ++NumBranchOpts;
1513
234k
      goto ReoptimizeBlock;
1514
234k
    }
1515
6.22M
1516
6.22M
    // If the prior block branches here on true and somewhere else on false, and
1517
6.22M
    // if the branch condition is reversible, reverse the branch to create a
1518
6.22M
    // fall-through.
1519
6.22M
    if (PriorTBB == MBB) {
1520
145k
      SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1521
145k
      if (!TII->reverseBranchCondition(NewPriorCond)) {
1522
145k
        DebugLoc dl = getBranchDebugLoc(PrevBB);
1523
145k
        TII->removeBranch(PrevBB);
1524
145k
        TII->insertBranch(PrevBB, PriorFBB, nullptr, NewPriorCond, dl);
1525
145k
        MadeChange = true;
1526
145k
        ++NumBranchOpts;
1527
145k
        goto ReoptimizeBlock;
1528
145k
      }
1529
6.08M
    }
1530
6.08M
1531
6.08M
    // If this block has no successors (e.g. it is a return block or ends with
1532
6.08M
    // a call to a no-return function like abort or __cxa_throw) and if the pred
1533
6.08M
    // falls through into this block, and if it would otherwise fall through
1534
6.08M
    // into the block after this, move this block to the end of the function.
1535
6.08M
    //
1536
6.08M
    // We consider it more likely that execution will stay in the function (e.g.
1537
6.08M
    // due to loops) than it is to exit it.  This asserts in loops etc, moving
1538
6.08M
    // the assert condition out of the loop body.
1539
6.08M
    if (MBB->succ_empty() && 
!PriorCond.empty()450k
&&
!PriorFBB197k
&&
1540
6.08M
        
MachineFunction::iterator(PriorTBB) == FallThrough189k
&&
1541
6.08M
        
!MBB->canFallThrough()84.1k
) {
1542
84.1k
      bool DoTransform = true;
1543
84.1k
1544
84.1k
      // We have to be careful that the succs of PredBB aren't both no-successor
1545
84.1k
      // blocks.  If neither have successors and if PredBB is the second from
1546
84.1k
      // last block in the function, we'd just keep swapping the two blocks for
1547
84.1k
      // last.  Only do the swap if one is clearly better to fall through than
1548
84.1k
      // the other.
1549
84.1k
      if (FallThrough == --MF.end() &&
1550
84.1k
          
!IsBetterFallthrough(PriorTBB, MBB)20.3k
)
1551
17.0k
        DoTransform = false;
1552
84.1k
1553
84.1k
      if (DoTransform) {
1554
67.0k
        // Reverse the branch so we will fall through on the previous true cond.
1555
67.0k
        SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
1556
67.0k
        if (!TII->reverseBranchCondition(NewPriorCond)) {
1557
67.0k
          LLVM_DEBUG(dbgs() << "\nMoving MBB: " << *MBB
1558
67.0k
                            << "To make fallthrough to: " << *PriorTBB << "\n");
1559
67.0k
1560
67.0k
          DebugLoc dl = getBranchDebugLoc(PrevBB);
1561
67.0k
          TII->removeBranch(PrevBB);
1562
67.0k
          TII->insertBranch(PrevBB, MBB, nullptr, NewPriorCond, dl);
1563
67.0k
1564
67.0k
          // Move this block to the end of the function.
1565
67.0k
          MBB->moveAfter(&MF.back());
1566
67.0k
          MadeChange = true;
1567
67.0k
          ++NumBranchOpts;
1568
67.0k
          return MadeChange;
1569
67.0k
        }
1570
6.22M
      }
1571
84.1k
    }
1572
6.08M
  }
1573
6.22M
1574
6.22M
  if (!IsEmptyBlock(MBB) && 
MBB->pred_size() == 16.22M
&&
1575
6.22M
      
MF.getFunction().hasOptSize()4.06M
) {
1576
29.1k
    // Changing "Jcc foo; foo: jmp bar;" into "Jcc bar;" might change the branch
1577
29.1k
    // direction, thereby defeating careful block placement and regressing
1578
29.1k
    // performance. Therefore, only consider this for optsize functions.
1579
29.1k
    MachineInstr &TailCall = *MBB->getFirstNonDebugInstr();
1580
29.1k
    if (TII->isUnconditionalTailCall(TailCall)) {
1581
45
      MachineBasicBlock *Pred = *MBB->pred_begin();
1582
45
      MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1583
45
      SmallVector<MachineOperand, 4> PredCond;
1584
45
      bool PredAnalyzable =
1585
45
          !TII->analyzeBranch(*Pred, PredTBB, PredFBB, PredCond, true);
1586
45
1587
45
      if (PredAnalyzable && 
!PredCond.empty()39
&&
PredTBB == MBB39
&&
1588
45
          
PredTBB != PredFBB31
) {
1589
30
        // The predecessor has a conditional branch to this block which consists
1590
30
        // of only a tail call. Try to fold the tail call into the conditional
1591
30
        // branch.
1592
30
        if (TII->canMakeTailCallConditional(PredCond, TailCall)) {
1593
30
          // TODO: It would be nice if analyzeBranch() could provide a pointer
1594
30
          // to the branch instruction so replaceBranchWithTailCall() doesn't
1595
30
          // have to search for it.
1596
30
          TII->replaceBranchWithTailCall(*Pred, PredCond, TailCall);
1597
30
          ++NumTailCalls;
1598
30
          Pred->removeSuccessor(MBB);
1599
30
          MadeChange = true;
1600
30
          return MadeChange;
1601
30
        }
1602
6.22M
      }
1603
45
      // If the predecessor is falling through to this block, we could reverse
1604
45
      // the branch condition and fold the tail call into that. However, after
1605
45
      // that we might have to re-arrange the CFG to fall through to the other
1606
45
      // block and there is a high risk of regressing code size rather than
1607
45
      // improving it.
1608
45
    }
1609
29.1k
  }
1610
6.22M
1611
6.22M
  // Analyze the branch in the current block.
1612
6.22M
  MachineBasicBlock *CurTBB = nullptr, *CurFBB = nullptr;
1613
6.22M
  SmallVector<MachineOperand, 4> CurCond;
1614
6.22M
  bool CurUnAnalyzable =
1615
6.22M
      TII->analyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
1616
6.22M
  if (!CurUnAnalyzable) {
1617
5.76M
    // If the CFG for the prior block has extra edges, remove them.
1618
5.76M
    MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1619
5.76M
1620
5.76M
    // If this is a two-way branch, and the FBB branches to this block, reverse
1621
5.76M
    // the condition so the single-basic-block loop is faster.  Instead of:
1622
5.76M
    //    Loop: xxx; jcc Out; jmp Loop
1623
5.76M
    // we want:
1624
5.76M
    //    Loop: xxx; jncc Loop; jmp Out
1625
5.76M
    if (CurTBB && 
CurFBB4.29M
&&
CurFBB == MBB422k
&&
CurTBB != MBB3.74k
) {
1626
3.74k
      SmallVector<MachineOperand, 4> NewCond(CurCond);
1627
3.74k
      if (!TII->reverseBranchCondition(NewCond)) {
1628
3.74k
        DebugLoc dl = getBranchDebugLoc(*MBB);
1629
3.74k
        TII->removeBranch(*MBB);
1630
3.74k
        TII->insertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
1631
3.74k
        MadeChange = true;
1632
3.74k
        ++NumBranchOpts;
1633
3.74k
        goto ReoptimizeBlock;
1634
3.74k
      }
1635
5.76M
    }
1636
5.76M
1637
5.76M
    // If this branch is the only thing in its block, see if we can forward
1638
5.76M
    // other blocks across it.
1639
5.76M
    if (CurTBB && 
CurCond.empty()4.28M
&&
!CurFBB1.21M
&&
1640
5.76M
        
IsBranchOnlyBlock(MBB)1.21M
&&
CurTBB != MBB146k
&&
1641
5.76M
        
!MBB->hasAddressTaken()146k
&&
!MBB->isEHPad()146k
) {
1642
146k
      DebugLoc dl = getBranchDebugLoc(*MBB);
1643
146k
      // This block may contain just an unconditional branch.  Because there can
1644
146k
      // be 'non-branch terminators' in the block, try removing the branch and
1645
146k
      // then seeing if the block is empty.
1646
146k
      TII->removeBranch(*MBB);
1647
146k
      // If the only things remaining in the block are debug info, remove these
1648
146k
      // as well, so this will behave the same as an empty block in non-debug
1649
146k
      // mode.
1650
146k
      if (IsEmptyBlock(MBB)) {
1651
146k
        // Make the block empty, losing the debug info (we could probably
1652
146k
        // improve this in some cases.)
1653
146k
        MBB->erase(MBB->begin(), MBB->end());
1654
146k
      }
1655
146k
      // If this block is just an unconditional branch to CurTBB, we can
1656
146k
      // usually completely eliminate the block.  The only case we cannot
1657
146k
      // completely eliminate the block is when the block before this one
1658
146k
      // falls through into MBB and we can't understand the prior block's branch
1659
146k
      // condition.
1660
146k
      if (MBB->empty()) {
1661
146k
        bool PredHasNoFallThrough = !PrevBB.canFallThrough();
1662
146k
        if (PredHasNoFallThrough || 
!PriorUnAnalyzable128k
||
1663
146k
            
!PrevBB.isSuccessor(MBB)3
) {
1664
146k
          // If the prior block falls through into us, turn it into an
1665
146k
          // explicit branch to us to make updates simpler.
1666
146k
          if (!PredHasNoFallThrough && 
PrevBB.isSuccessor(MBB)128k
&&
1667
146k
              
PriorTBB != MBB128k
&&
PriorFBB != MBB128k
) {
1668
128k
            if (!PriorTBB) {
1669
3.13k
              assert(PriorCond.empty() && !PriorFBB &&
1670
3.13k
                     "Bad branch analysis");
1671
3.13k
              PriorTBB = MBB;
1672
125k
            } else {
1673
125k
              assert(!PriorFBB && "Machine CFG out of date!");
1674
125k
              PriorFBB = MBB;
1675
125k
            }
1676
128k
            DebugLoc pdl = getBranchDebugLoc(PrevBB);
1677
128k
            TII->removeBranch(PrevBB);
1678
128k
            TII->insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1679
128k
          }
1680
146k
1681
146k
          // Iterate through all the predecessors, revectoring each in-turn.
1682
146k
          size_t PI = 0;
1683
146k
          bool DidChange = false;
1684
146k
          bool HasBranchToSelf = false;
1685
302k
          while(PI != MBB->pred_size()) {
1686
155k
            MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1687
155k
            if (PMBB == MBB) {
1688
0
              // If this block has an uncond branch to itself, leave it.
1689
0
              ++PI;
1690
0
              HasBranchToSelf = true;
1691
155k
            } else {
1692
155k
              DidChange = true;
1693
155k
              PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1694
155k
              // If this change resulted in PMBB ending in a conditional
1695
155k
              // branch where both conditions go to the same destination,
1696
155k
              // change this to an unconditional branch (and fix the CFG).
1697
155k
              MachineBasicBlock *NewCurTBB = nullptr, *NewCurFBB = nullptr;
1698
155k
              SmallVector<MachineOperand, 4> NewCurCond;
1699
155k
              bool NewCurUnAnalyzable = TII->analyzeBranch(
1700
155k
                  *PMBB, NewCurTBB, NewCurFBB, NewCurCond, true);
1701
155k
              if (!NewCurUnAnalyzable && 
NewCurTBB155k
&&
NewCurTBB == NewCurFBB155k
) {
1702
34
                DebugLoc pdl = getBranchDebugLoc(*PMBB);
1703
34
                TII->removeBranch(*PMBB);
1704
34
                NewCurCond.clear();
1705
34
                TII->insertBranch(*PMBB, NewCurTBB, nullptr, NewCurCond, pdl);
1706
34
                MadeChange = true;
1707
34
                ++NumBranchOpts;
1708
34
                PMBB->CorrectExtraCFGEdges(NewCurTBB, nullptr, false);
1709
34
              }
1710
155k
            }
1711
155k
          }
1712
146k
1713
146k
          // Change any jumptables to go to the new MBB.
1714
146k
          if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1715
27.0k
            MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1716
146k
          if (DidChange) {
1717
146k
            ++NumBranchOpts;
1718
146k
            MadeChange = true;
1719
146k
            if (!HasBranchToSelf) return MadeChange;
1720
3
          }
1721
146k
        }
1722
146k
      }
1723
3
1724
3
      // Add the branch back if the block is more than just an uncond branch.
1725
3
      TII->insertBranch(*MBB, CurTBB, nullptr, CurCond, dl);
1726
3
    }
1727
5.76M
  }
1728
6.22M
1729
6.22M
  // If the prior block doesn't fall through into this block, and if this
1730
6.22M
  // block doesn't fall through into some other block, see if we can find a
1731
6.22M
  // place to move this block where a fall-through will happen.
1732
6.22M
  
if (6.07M
!PrevBB.canFallThrough()6.07M
) {
1733
1.47M
    // Now we know that there was no fall-through into this block, check to
1734
1.47M
    // see if it has a fall-through into its successor.
1735
1.47M
    bool CurFallsThru = MBB->canFallThrough();
1736
1.47M
1737
1.47M
    if (!MBB->isEHPad()) {
1738
1.41M
      // Check all the predecessors of this block.  If one of them has no fall
1739
1.41M
      // throughs, move this block right after it.
1740
1.63M
      for (MachineBasicBlock *PredBB : MBB->predecessors()) {
1741
1.63M
        // Analyze the branch at the end of the pred.
1742
1.63M
        MachineBasicBlock *PredTBB = nullptr, *PredFBB = nullptr;
1743
1.63M
        SmallVector<MachineOperand, 4> PredCond;
1744
1.63M
        if (PredBB != MBB && 
!PredBB->canFallThrough()1.61M
&&
1745
1.63M
            
!TII->analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)316k
&&
1746
1.63M
            
(245k
!CurFallsThru245k
||
!CurTBB174k
||
!CurFBB128k
) &&
1747
1.63M
            
(240k
!CurFallsThru240k
||
MBB->getNumber() >= PredBB->getNumber()169k
)) {
1748
197k
          // If the current block doesn't fall through, just move it.
1749
197k
          // If the current block can fall through and does not end with a
1750
197k
          // conditional branch, we need to append an unconditional jump to
1751
197k
          // the (current) next block.  To avoid a possible compile-time
1752
197k
          // infinite loop, move blocks only backward in this case.
1753
197k
          // Also, if there are already 2 branches here, we cannot add a third;
1754
197k
          // this means we have the case
1755
197k
          // Bcc next
1756
197k
          // B elsewhere
1757
197k
          // next:
1758
197k
          if (CurFallsThru) {
1759
126k
            MachineBasicBlock *NextBB = &*std::next(MBB->getIterator());
1760
126k
            CurCond.clear();
1761
126k
            TII->insertBranch(*MBB, NextBB, nullptr, CurCond, DebugLoc());
1762
126k
          }
1763
197k
          MBB->moveAfter(PredBB);
1764
197k
          MadeChange = true;
1765
197k
          goto ReoptimizeBlock;
1766
197k
        }
1767
1.63M
      }
1768
1.41M
    }
1769
1.47M
1770
1.47M
    
if (1.27M
!CurFallsThru1.27M
) {
1771
359k
      // Check all successors to see if we can move this block before it.
1772
359k
      for (MachineBasicBlock *SuccBB : MBB->successors()) {
1773
192k
        // Analyze the branch at the end of the block before the succ.
1774
192k
        MachineFunction::iterator SuccPrev = --SuccBB->getIterator();
1775
192k
1776
192k
        // If this block doesn't already fall-through to that successor, and if
1777
192k
        // the succ doesn't already have a block that can fall through into it,
1778
192k
        // and if the successor isn't an EH destination, we can arrange for the
1779
192k
        // fallthrough to happen.
1780
192k
        if (SuccBB != MBB && 
&*SuccPrev != MBB186k
&&
1781
192k
            
!SuccPrev->canFallThrough()185k
&&
!CurUnAnalyzable26.3k
&&
1782
192k
            
!SuccBB->isEHPad()15.9k
) {
1783
15.3k
          MBB->moveBefore(SuccBB);
1784
15.3k
          MadeChange = true;
1785
15.3k
          goto ReoptimizeBlock;
1786
15.3k
        }
1787
192k
      }
1788
359k
1789
359k
      // Okay, there is no really great place to put this block.  If, however,
1790
359k
      // the block before this one would be a fall-through if this block were
1791
359k
      // removed, move this block to the end of the function. There is no real
1792
359k
      // advantage in "falling through" to an EH block, so we don't want to
1793
359k
      // perform this transformation for that case.
1794
359k
      //
1795
359k
      // Also, Windows EH introduced the possibility of an arbitrary number of
1796
359k
      // successors to a given block.  The analyzeBranch call does not consider
1797
359k
      // exception handling and so we can get in a state where a block
1798
359k
      // containing a call is followed by multiple EH blocks that would be
1799
359k
      // rotated infinitely at the end of the function if the transformation
1800
359k
      // below were performed for EH "FallThrough" blocks.  Therefore, even if
1801
359k
      // that appears not to be happening anymore, we should assume that it is
1802
359k
      // possible and not remove the "!FallThrough()->isEHPad" condition below.
1803
359k
      MachineBasicBlock *PrevTBB = nullptr, *PrevFBB = nullptr;
1804
344k
      SmallVector<MachineOperand, 4> PrevCond;
1805
344k
      if (FallThrough != MF.end() &&
1806
344k
          
!FallThrough->isEHPad()258k
&&
1807
344k
          
!TII->analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true)228k
&&
1808
344k
          
PrevBB.isSuccessor(&*FallThrough)123k
) {
1809
11.0k
        MBB->moveAfter(&MF.back());
1810
11.0k
        MadeChange = true;
1811
11.0k
        return MadeChange;
1812
11.0k
      }
1813
5.85M
    }
1814
1.27M
  }
1815
5.85M
1816
5.85M
  return MadeChange;
1817
5.85M
}
1818
1819
//===----------------------------------------------------------------------===//
1820
//  Hoist Common Code
1821
//===----------------------------------------------------------------------===//
1822
1823
606k
bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1824
606k
  bool MadeChange = false;
1825
6.37M
  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1826
5.76M
    MachineBasicBlock *MBB = &*I++;
1827
5.76M
    MadeChange |= HoistCommonCodeInSuccs(MBB);
1828
5.76M
  }
1829
606k
1830
606k
  return MadeChange;
1831
606k
}
1832
1833
/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1834
/// its 'true' successor.
1835
static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1836
2.71M
                                         MachineBasicBlock *TrueBB) {
1837
2.71M
  for (MachineBasicBlock *SuccBB : BB->successors())
1838
3.90M
    if (SuccBB != TrueBB)
1839
2.71M
      return SuccBB;
1840
2.71M
  
return nullptr26
;
1841
2.71M
}
1842
1843
template <class Container>
1844
static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI,
1845
2.00M
                                Container &Set) {
1846
2.00M
  if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1847
8.77M
    for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); 
++AI6.76M
)
1848
6.76M
      Set.insert(*AI);
1849
2.00M
  } else {
1850
316
    Set.insert(Reg);
1851
316
  }
1852
2.00M
}
1853
1854
/// findHoistingInsertPosAndDeps - Find the location to move common instructions
1855
/// in successors to. The location is usually just before the terminator,
1856
/// however if the terminator is a conditional branch and its previous
1857
/// instruction is the flag setting instruction, the previous instruction is
1858
/// the preferred location. This function also gathers uses and defs of the
1859
/// instructions from the insertion point to the end of the block. The data is
1860
/// used by HoistCommonCodeInSuccs to ensure safety.
1861
static
1862
MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1863
                                                  const TargetInstrInfo *TII,
1864
                                                  const TargetRegisterInfo *TRI,
1865
                                                  SmallSet<unsigned,4> &Uses,
1866
815k
                                                  SmallSet<unsigned,4> &Defs) {
1867
815k
  MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1868
815k
  if (!TII->isUnpredicatedTerminator(*Loc))
1869
0
    return MBB->end();
1870
815k
1871
2.03M
  
for (const MachineOperand &MO : Loc->operands())815k
{
1872
2.03M
    if (!MO.isReg())
1873
1.20M
      continue;
1874
833k
    unsigned Reg = MO.getReg();
1875
833k
    if (!Reg)
1876
0
      continue;
1877
833k
    if (MO.isUse()) {
1878
832k
      addRegAndItsAliases(Reg, TRI, Uses);
1879
832k
    } else {
1880
767
      if (!MO.isDead())
1881
576
        // Don't try to hoist code in the rare case the terminator defines a
1882
576
        // register that is later used.
1883
576
        return MBB->end();
1884
191
1885
191
      // If the terminator defines a register, make sure we don't hoist
1886
191
      // the instruction whose def might be clobbered by the terminator.
1887
191
      addRegAndItsAliases(Reg, TRI, Defs);
1888
191
    }
1889
833k
  }
1890
815k
1891
815k
  
if (814k
Uses.empty()814k
)
1892
0
    return Loc;
1893
814k
  // If the terminator is the only instruction in the block and Uses is not
1894
814k
  // empty (or we would have returned above), we can still safely hoist
1895
814k
  // instructions just before the terminator as long as the Defs/Uses are not
1896
814k
  // violated (which is checked in HoistCommonCodeInSuccs).
1897
814k
  if (Loc == MBB->begin())
1898
127k
    return Loc;
1899
687k
1900
687k
  // The terminator is probably a conditional branch, try not to separate the
1901
687k
  // branch from condition setting instruction.
1902
687k
  MachineBasicBlock::iterator PI =
1903
687k
    skipDebugInstructionsBackward(std::prev(Loc), MBB->begin());
1904
687k
1905
687k
  bool IsDef = false;
1906
2.31M
  for (const MachineOperand &MO : PI->operands()) {
1907
2.31M
    // If PI has a regmask operand, it is probably a call. Separate away.
1908
2.31M
    if (MO.isRegMask())
1909
46.2k
      return Loc;
1910
2.26M
    if (!MO.isReg() || 
MO.isUse()1.63M
)
1911
1.54M
      continue;
1912
716k
    unsigned Reg = MO.getReg();
1913
716k
    if (!Reg)
1914
0
      continue;
1915
716k
    if (Uses.count(Reg)) {
1916
445k
      IsDef = true;
1917
445k
      break;
1918
445k
    }
1919
716k
  }
1920
687k
  
if (641k
!IsDef641k
)
1921
195k
    // The condition setting instruction is not just before the conditional
1922
195k
    // branch.
1923
195k
    return Loc;
1924
445k
1925
445k
  // Be conservative, don't insert instruction above something that may have
1926
445k
  // side-effects. And since it's potentially bad to separate flag setting
1927
445k
  // instruction from the conditional branch, just abort the optimization
1928
445k
  // completely.
1929
445k
  // Also avoid moving code above predicated instruction since it's hard to
1930
445k
  // reason about register liveness with predicated instruction.
1931
445k
  bool DontMoveAcrossStore = true;
1932
445k
  if (!PI->isSafeToMove(nullptr, DontMoveAcrossStore) || 
TII->isPredicated(*PI)377k
)
1933
68.1k
    return MBB->end();
1934
377k
1935
377k
  // Find out what registers are live. Note this routine is ignoring other live
1936
377k
  // registers which are only used by instructions in successor blocks.
1937
1.58M
  
for (const MachineOperand &MO : PI->operands())377k
{
1938
1.58M
    if (!MO.isReg())
1939
392k
      continue;
1940
1.19M
    unsigned Reg = MO.getReg();
1941
1.19M
    if (!Reg)
1942
33.4k
      continue;
1943
1.15M
    if (MO.isUse()) {
1944
548k
      addRegAndItsAliases(Reg, TRI, Uses);
1945
611k
    } else {
1946
611k
      if (Uses.erase(Reg)) {
1947
377k
        if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1948
401k
          for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); 
++SubRegs24.0k
)
1949
24.0k
            Uses.erase(*SubRegs); // Use sub-registers to be conservative
1950
377k
        }
1951
377k
      }
1952
611k
      addRegAndItsAliases(Reg, TRI, Defs);
1953
611k
    }
1954
1.15M
  }
1955
377k
1956
377k
  return PI;
1957
377k
}
1958
1959
5.76M
bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1960
5.76M
  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
1961
5.76M
  SmallVector<MachineOperand, 4> Cond;
1962
5.76M
  if (TII->analyzeBranch(*MBB, TBB, FBB, Cond, true) || 
!TBB5.04M
||
Cond.empty()3.60M
)
1963
2.93M
    return false;
1964
2.82M
1965
2.82M
  if (!FBB) 
FBB = findFalseBlock(MBB, TBB)2.71M
;
1966
2.82M
  if (!FBB)
1967
26
    // Malformed bcc? True and false blocks are the same?
1968
26
    return false;
1969
2.82M
1970
2.82M
  // Restrict the optimization to cases where MBB is the only predecessor,
1971
2.82M
  // it is an obvious win.
1972
2.82M
  if (TBB->pred_size() > 1 || 
FBB->pred_size() > 1883k
)
1973
2.01M
    return false;
1974
815k
1975
815k
  // Find a suitable position to hoist the common instructions to. Also figure
1976
815k
  // out which registers are used or defined by instructions from the insertion
1977
815k
  // point to the end of the block.
1978
815k
  SmallSet<unsigned, 4> Uses, Defs;
1979
815k
  MachineBasicBlock::iterator Loc =
1980
815k
    findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1981
815k
  if (Loc == MBB->end())
1982
68.6k
    return false;
1983
746k
1984
746k
  bool HasDups = false;
1985
746k
  SmallSet<unsigned, 4> ActiveDefsSet, AllDefsSet;
1986
746k
  MachineBasicBlock::iterator TIB = TBB->begin();
1987
746k
  MachineBasicBlock::iterator FIB = FBB->begin();
1988
746k
  MachineBasicBlock::iterator TIE = TBB->end();
1989
746k
  MachineBasicBlock::iterator FIE = FBB->end();
1990
753k
  while (TIB != TIE && 
FIB != FIE751k
) {
1991
751k
    // Skip dbg_value instructions. These do not count.
1992
751k
    TIB = skipDebugInstructionsForward(TIB, TIE);
1993
751k
    FIB = skipDebugInstructionsForward(FIB, FIE);
1994
751k
    if (TIB == TIE || FIB == FIE)
1995
0
      break;
1996
751k
1997
751k
    if (!TIB->isIdenticalTo(*FIB, MachineInstr::CheckKillDead))
1998
722k
      break;
1999
28.7k
2000
28.7k
    if (TII->isPredicated(*TIB))
2001
1
      // Hard to reason about register liveness with predicated instruction.
2002
1
      break;
2003
28.7k
2004
28.7k
    bool IsSafe = true;
2005
75.7k
    for (MachineOperand &MO : TIB->operands()) {
2006
75.7k
      // Don't attempt to hoist instructions with register masks.
2007
75.7k
      if (MO.isRegMask()) {
2008
74
        IsSafe = false;
2009
74
        break;
2010
74
      }
2011
75.7k
      if (!MO.isReg())
2012
20.1k
        continue;
2013
55.5k
      unsigned Reg = MO.getReg();
2014
55.5k
      if (!Reg)
2015
1.43k
        continue;
2016
54.1k
      if (MO.isDef()) {
2017
29.6k
        if (Uses.count(Reg)) {
2018
4.13k
          // Avoid clobbering a register that's used by the instruction at
2019
4.13k
          // the point of insertion.
2020
4.13k
          IsSafe = false;
2021
4.13k
          break;
2022
4.13k
        }
2023
25.5k
2024
25.5k
        if (Defs.count(Reg) && 
!MO.isDead()2.01k
) {
2025
1.69k
          // Don't hoist the instruction if the def would be clobber by the
2026
1.69k
          // instruction at the point insertion. FIXME: This is overly
2027
1.69k
          // conservative. It should be possible to hoist the instructions
2028
1.69k
          // in BB2 in the following example:
2029
1.69k
          // BB1:
2030
1.69k
          // r1, eflag = op1 r2, r3
2031
1.69k
          // brcc eflag
2032
1.69k
          //
2033
1.69k
          // BB2:
2034
1.69k
          // r1 = op2, ...
2035
1.69k
          //    = op3, killed r1
2036
1.69k
          IsSafe = false;
2037
1.69k
          break;
2038
1.69k
        }
2039
24.4k
      } else if (!ActiveDefsSet.count(Reg)) {
2040
24.1k
        if (Defs.count(Reg)) {
2041
757
          // Use is defined by the instruction at the point of insertion.
2042
757
          IsSafe = false;
2043
757
          break;
2044
757
        }
2045
23.3k
2046
23.3k
        if (MO.isKill() && 
Uses.count(Reg)3.48k
)
2047
81
          // Kills a register that's read by the instruction at the point of
2048
81
          // insertion. Remove the kill marker.
2049
81
          MO.setIsKill(false);
2050
23.3k
      }
2051
54.1k
    }
2052
28.7k
    if (!IsSafe)
2053
6.66k
      break;
2054
22.1k
2055
22.1k
    bool DontMoveAcrossStore = true;
2056
22.1k
    if (!TIB->isSafeToMove(nullptr, DontMoveAcrossStore))
2057
15.4k
      break;
2058
6.70k
2059
6.70k
    // Remove kills from ActiveDefsSet, these registers had short live ranges.
2060
17.1k
    
for (const MachineOperand &MO : TIB->operands())6.70k
{
2061
17.1k
      if (!MO.isReg() || 
!MO.isUse()13.7k
||
!MO.isKill()4.95k
)
2062
16.3k
        continue;
2063
823
      unsigned Reg = MO.getReg();
2064
823
      if (!Reg)
2065
0
        continue;
2066
823
      if (!AllDefsSet.count(Reg)) {
2067
753
        continue;
2068
753
      }
2069
70
      if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2070
393
        for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); 
++AI323
)
2071
323
          ActiveDefsSet.erase(*AI);
2072
70
      } else {
2073
0
        ActiveDefsSet.erase(Reg);
2074
0
      }
2075
70
    }
2076
6.70k
2077
6.70k
    // Track local defs so we can update liveins.
2078
17.1k
    for (const MachineOperand &MO : TIB->operands()) {
2079
17.1k
      if (!MO.isReg() || 
!MO.isDef()13.7k
||
MO.isDead()8.78k
)
2080
8.76k
        continue;
2081
8.39k
      unsigned Reg = MO.getReg();
2082
8.39k
      if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg))
2083
0
        continue;
2084
8.39k
      addRegAndItsAliases(Reg, TRI, ActiveDefsSet);
2085
8.39k
      addRegAndItsAliases(Reg, TRI, AllDefsSet);
2086
8.39k
    }
2087
6.70k
2088
6.70k
    HasDups = true;
2089
6.70k
    ++TIB;
2090
6.70k
    ++FIB;
2091
6.70k
  }
2092
746k
2093
746k
  if (!HasDups)
2094
740k
    return false;
2095
6.07k
2096
6.07k
  MBB->splice(Loc, TBB, TBB->begin(), TIB);
2097
6.07k
  FBB->erase(FBB->begin(), FIB);
2098
6.07k
2099
6.07k
  if (UpdateLiveIns) {
2100
6.07k
    recomputeLiveIns(*TBB);
2101
6.07k
    recomputeLiveIns(*FBB);
2102
6.07k
  }
2103
6.07k
2104
6.07k
  ++NumHoist;
2105
6.07k
  return true;
2106
6.07k
}