1 //===-- PPCBranchSelector.cpp - Emit long conditional branches ------------===// 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 file contains a pass that scans a machine function to determine which 10 // conditional branches need more than 16 bits of displacement to reach their 11 // target basic block. It does this in two passes; a calculation of basic block 12 // positions pass, and a branch pseudo op to machine branch opcode pass. This 13 // pass should be run last, just before the assembly printer. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "MCTargetDesc/PPCPredicates.h" 18 #include "PPC.h" 19 #include "PPCInstrBuilder.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCSubtarget.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/MachineFunctionPass.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/TargetSubtargetInfo.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Target/TargetMachine.h" 28 #include <algorithm> 29 using namespace llvm; 30 31 #define DEBUG_TYPE "ppc-branch-select" 32 33 STATISTIC(NumExpanded, "Number of branches expanded to long format"); 34 35 namespace llvm { 36 void initializePPCBSelPass(PassRegistry&); 37 } 38 39 namespace { 40 struct PPCBSel : public MachineFunctionPass { 41 static char ID; 42 PPCBSel() : MachineFunctionPass(ID) { 43 initializePPCBSelPass(*PassRegistry::getPassRegistry()); 44 } 45 46 // The sizes of the basic blocks in the function (the first 47 // element of the pair); the second element of the pair is the amount of the 48 // size that is due to potential padding. 49 std::vector<std::pair<unsigned, unsigned>> BlockSizes; 50 51 bool runOnMachineFunction(MachineFunction &Fn) override; 52 53 MachineFunctionProperties getRequiredProperties() const override { 54 return MachineFunctionProperties().set( 55 MachineFunctionProperties::Property::NoVRegs); 56 } 57 58 StringRef getPassName() const override { return "PowerPC Branch Selector"; } 59 }; 60 char PPCBSel::ID = 0; 61 } 62 63 INITIALIZE_PASS(PPCBSel, "ppc-branch-select", "PowerPC Branch Selector", 64 false, false) 65 66 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection 67 /// Pass 68 /// 69 FunctionPass *llvm::createPPCBranchSelectionPass() { 70 return new PPCBSel(); 71 } 72 73 bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) { 74 const PPCInstrInfo *TII = 75 static_cast<const PPCInstrInfo *>(Fn.getSubtarget().getInstrInfo()); 76 // Give the blocks of the function a dense, in-order, numbering. 77 Fn.RenumberBlocks(); 78 BlockSizes.resize(Fn.getNumBlockIDs()); 79 // The first block number which has imprecise instruction address. 80 int FirstImpreciseBlock = -1; 81 82 auto GetAlignmentAdjustment = [&FirstImpreciseBlock] 83 (MachineBasicBlock &MBB, unsigned Offset) -> unsigned { 84 unsigned Align = MBB.getAlignment(); 85 if (!Align) 86 return 0; 87 88 unsigned AlignAmt = 1 << Align; 89 unsigned ParentAlign = MBB.getParent()->getAlignment(); 90 91 if (Align <= ParentAlign) 92 return OffsetToAlignment(Offset, AlignAmt); 93 94 // The alignment of this MBB is larger than the function's alignment, so we 95 // can't tell whether or not it will insert nops. Assume that it will. 96 if (FirstImpreciseBlock < 0) 97 FirstImpreciseBlock = MBB.getNumber(); 98 return AlignAmt + OffsetToAlignment(Offset, AlignAmt); 99 }; 100 101 // We need to be careful about the offset of the first block in the function 102 // because it might not have the function's alignment. This happens because, 103 // under the ELFv2 ABI, for functions which require a TOC pointer, we add a 104 // two-instruction sequence to the start of the function. 105 // Note: This needs to be synchronized with the check in 106 // PPCLinuxAsmPrinter::EmitFunctionBodyStart. 107 unsigned InitialOffset = 0; 108 if (Fn.getSubtarget<PPCSubtarget>().isELFv2ABI() && 109 !Fn.getRegInfo().use_empty(PPC::X2)) 110 InitialOffset = 8; 111 112 // Measure each MBB and compute a size for the entire function. 113 unsigned FuncSize = InitialOffset; 114 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E; 115 ++MFI) { 116 MachineBasicBlock *MBB = &*MFI; 117 118 // The end of the previous block may have extra nops if this block has an 119 // alignment requirement. 120 if (MBB->getNumber() > 0) { 121 unsigned AlignExtra = GetAlignmentAdjustment(*MBB, FuncSize); 122 123 auto &BS = BlockSizes[MBB->getNumber()-1]; 124 BS.first += AlignExtra; 125 BS.second = AlignExtra; 126 127 FuncSize += AlignExtra; 128 } 129 130 unsigned BlockSize = 0; 131 for (MachineInstr &MI : *MBB) { 132 BlockSize += TII->getInstSizeInBytes(MI); 133 if (MI.isInlineAsm() && (FirstImpreciseBlock < 0)) 134 FirstImpreciseBlock = MBB->getNumber(); 135 } 136 137 BlockSizes[MBB->getNumber()].first = BlockSize; 138 FuncSize += BlockSize; 139 } 140 141 // If the entire function is smaller than the displacement of a branch field, 142 // we know we don't need to shrink any branches in this function. This is a 143 // common case. 144 if (FuncSize < (1 << 15)) { 145 BlockSizes.clear(); 146 return false; 147 } 148 149 // For each conditional branch, if the offset to its destination is larger 150 // than the offset field allows, transform it into a long branch sequence 151 // like this: 152 // short branch: 153 // bCC MBB 154 // long branch: 155 // b!CC $PC+8 156 // b MBB 157 // 158 bool MadeChange = true; 159 bool EverMadeChange = false; 160 while (MadeChange) { 161 // Iteratively expand branches until we reach a fixed point. 162 MadeChange = false; 163 164 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E; 165 ++MFI) { 166 MachineBasicBlock &MBB = *MFI; 167 unsigned MBBStartOffset = 0; 168 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); 169 I != E; ++I) { 170 MachineBasicBlock *Dest = nullptr; 171 if (I->getOpcode() == PPC::BCC && !I->getOperand(2).isImm()) 172 Dest = I->getOperand(2).getMBB(); 173 else if ((I->getOpcode() == PPC::BC || I->getOpcode() == PPC::BCn) && 174 !I->getOperand(1).isImm()) 175 Dest = I->getOperand(1).getMBB(); 176 else if ((I->getOpcode() == PPC::BDNZ8 || I->getOpcode() == PPC::BDNZ || 177 I->getOpcode() == PPC::BDZ8 || I->getOpcode() == PPC::BDZ) && 178 !I->getOperand(0).isImm()) 179 Dest = I->getOperand(0).getMBB(); 180 181 if (!Dest) { 182 MBBStartOffset += TII->getInstSizeInBytes(*I); 183 continue; 184 } 185 186 // Determine the offset from the current branch to the destination 187 // block. 188 int BranchSize; 189 unsigned MaxAlign = 2; 190 bool NeedExtraAdjustment = false; 191 if (Dest->getNumber() <= MBB.getNumber()) { 192 // If this is a backwards branch, the delta is the offset from the 193 // start of this block to this branch, plus the sizes of all blocks 194 // from this block to the dest. 195 BranchSize = MBBStartOffset; 196 MaxAlign = std::max(MaxAlign, MBB.getAlignment()); 197 198 int DestBlock = Dest->getNumber(); 199 BranchSize += BlockSizes[DestBlock].first; 200 for (unsigned i = DestBlock+1, e = MBB.getNumber(); i < e; ++i) { 201 BranchSize += BlockSizes[i].first; 202 MaxAlign = std::max(MaxAlign, 203 Fn.getBlockNumbered(i)->getAlignment()); 204 } 205 206 NeedExtraAdjustment = (FirstImpreciseBlock >= 0) && 207 (DestBlock >= FirstImpreciseBlock); 208 } else { 209 // Otherwise, add the size of the blocks between this block and the 210 // dest to the number of bytes left in this block. 211 unsigned StartBlock = MBB.getNumber(); 212 BranchSize = BlockSizes[StartBlock].first - MBBStartOffset; 213 214 MaxAlign = std::max(MaxAlign, Dest->getAlignment()); 215 for (unsigned i = StartBlock+1, e = Dest->getNumber(); i != e; ++i) { 216 BranchSize += BlockSizes[i].first; 217 MaxAlign = std::max(MaxAlign, 218 Fn.getBlockNumbered(i)->getAlignment()); 219 } 220 221 NeedExtraAdjustment = (FirstImpreciseBlock >= 0) && 222 (MBB.getNumber() >= FirstImpreciseBlock); 223 } 224 225 // We tend to over estimate code size due to large alignment and 226 // inline assembly. Usually it causes larger computed branch offset. 227 // But sometimes it may also causes smaller computed branch offset 228 // than actual branch offset. If the offset is close to the limit of 229 // encoding, it may cause problem at run time. 230 // Following is a simplified example. 231 // 232 // actual estimated 233 // address address 234 // ... 235 // bne Far 100 10c 236 // .p2align 4 237 // Near: 110 110 238 // ... 239 // Far: 8108 8108 240 // 241 // Actual offset: 0x8108 - 0x100 = 0x8008 242 // Computed offset: 0x8108 - 0x10c = 0x7ffc 243 // 244 // This example also shows when we can get the largest gap between 245 // estimated offset and actual offset. If there is an aligned block 246 // ABB between branch and target, assume its alignment is <align> 247 // bits. Now consider the accumulated function size FSIZE till the end 248 // of previous block PBB. If the estimated FSIZE is multiple of 249 // 2^<align>, we don't need any padding for the estimated address of 250 // ABB. If actual FSIZE at the end of PBB is 4 bytes more than 251 // multiple of 2^<align>, then we need (2^<align> - 4) bytes of 252 // padding. It also means the actual branch offset is (2^<align> - 4) 253 // larger than computed offset. Other actual FSIZE needs less padding 254 // bytes, so causes smaller gap between actual and computed offset. 255 // 256 // On the other hand, if the inline asm or large alignment occurs 257 // between the branch block and destination block, the estimated address 258 // can be <delta> larger than actual address. If padding bytes are 259 // needed for a later aligned block, the actual number of padding bytes 260 // is at most <delta> more than estimated padding bytes. So the actual 261 // aligned block address is less than or equal to the estimated aligned 262 // block address. So the actual branch offset is less than or equal to 263 // computed branch offset. 264 // 265 // The computed offset is at most ((1 << alignment) - 4) bytes smaller 266 // than actual offset. So we add this number to the offset for safety. 267 if (NeedExtraAdjustment) 268 BranchSize += (1 << MaxAlign) - 4; 269 270 // If this branch is in range, ignore it. 271 if (isInt<16>(BranchSize)) { 272 MBBStartOffset += 4; 273 continue; 274 } 275 276 // Otherwise, we have to expand it to a long branch. 277 MachineInstr &OldBranch = *I; 278 DebugLoc dl = OldBranch.getDebugLoc(); 279 280 if (I->getOpcode() == PPC::BCC) { 281 // The BCC operands are: 282 // 0. PPC branch predicate 283 // 1. CR register 284 // 2. Target MBB 285 PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm(); 286 unsigned CRReg = I->getOperand(1).getReg(); 287 288 // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition. 289 BuildMI(MBB, I, dl, TII->get(PPC::BCC)) 290 .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2); 291 } else if (I->getOpcode() == PPC::BC) { 292 unsigned CRBit = I->getOperand(0).getReg(); 293 BuildMI(MBB, I, dl, TII->get(PPC::BCn)).addReg(CRBit).addImm(2); 294 } else if (I->getOpcode() == PPC::BCn) { 295 unsigned CRBit = I->getOperand(0).getReg(); 296 BuildMI(MBB, I, dl, TII->get(PPC::BC)).addReg(CRBit).addImm(2); 297 } else if (I->getOpcode() == PPC::BDNZ) { 298 BuildMI(MBB, I, dl, TII->get(PPC::BDZ)).addImm(2); 299 } else if (I->getOpcode() == PPC::BDNZ8) { 300 BuildMI(MBB, I, dl, TII->get(PPC::BDZ8)).addImm(2); 301 } else if (I->getOpcode() == PPC::BDZ) { 302 BuildMI(MBB, I, dl, TII->get(PPC::BDNZ)).addImm(2); 303 } else if (I->getOpcode() == PPC::BDZ8) { 304 BuildMI(MBB, I, dl, TII->get(PPC::BDNZ8)).addImm(2); 305 } else { 306 llvm_unreachable("Unhandled branch type!"); 307 } 308 309 // Uncond branch to the real destination. 310 I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest); 311 312 // Remove the old branch from the function. 313 OldBranch.eraseFromParent(); 314 315 // Remember that this instruction is 8-bytes, increase the size of the 316 // block by 4, remember to iterate. 317 BlockSizes[MBB.getNumber()].first += 4; 318 MBBStartOffset += 8; 319 ++NumExpanded; 320 MadeChange = true; 321 } 322 } 323 324 if (MadeChange) { 325 // If we're going to iterate again, make sure we've updated our 326 // padding-based contributions to the block sizes. 327 unsigned Offset = InitialOffset; 328 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E; 329 ++MFI) { 330 MachineBasicBlock *MBB = &*MFI; 331 332 if (MBB->getNumber() > 0) { 333 auto &BS = BlockSizes[MBB->getNumber()-1]; 334 BS.first -= BS.second; 335 Offset -= BS.second; 336 337 unsigned AlignExtra = GetAlignmentAdjustment(*MBB, Offset); 338 339 BS.first += AlignExtra; 340 BS.second = AlignExtra; 341 342 Offset += AlignExtra; 343 } 344 345 Offset += BlockSizes[MBB->getNumber()].first; 346 } 347 } 348 349 EverMadeChange |= MadeChange; 350 } 351 352 BlockSizes.clear(); 353 return true; 354 } 355