1 //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===// 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 the Base ARM implementation of the TargetInstrInfo class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ARMBaseInstrInfo.h" 14 #include "ARMBaseRegisterInfo.h" 15 #include "ARMConstantPoolValue.h" 16 #include "ARMFeatures.h" 17 #include "ARMHazardRecognizer.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMSubtarget.h" 20 #include "MCTargetDesc/ARMAddressingModes.h" 21 #include "MCTargetDesc/ARMBaseInfo.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Triple.h" 27 #include "llvm/CodeGen/LiveVariables.h" 28 #include "llvm/CodeGen/MachineBasicBlock.h" 29 #include "llvm/CodeGen/MachineConstantPool.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstr.h" 33 #include "llvm/CodeGen/MachineInstrBuilder.h" 34 #include "llvm/CodeGen/MachineMemOperand.h" 35 #include "llvm/CodeGen/MachineModuleInfo.h" 36 #include "llvm/CodeGen/MachineOperand.h" 37 #include "llvm/CodeGen/MachineRegisterInfo.h" 38 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h" 39 #include "llvm/CodeGen/SelectionDAGNodes.h" 40 #include "llvm/CodeGen/TargetInstrInfo.h" 41 #include "llvm/CodeGen/TargetRegisterInfo.h" 42 #include "llvm/CodeGen/TargetSchedule.h" 43 #include "llvm/IR/Attributes.h" 44 #include "llvm/IR/Constants.h" 45 #include "llvm/IR/DebugLoc.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/IR/GlobalValue.h" 48 #include "llvm/MC/MCAsmInfo.h" 49 #include "llvm/MC/MCInstrDesc.h" 50 #include "llvm/MC/MCInstrItineraries.h" 51 #include "llvm/Support/BranchProbability.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/Compiler.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 <algorithm> 60 #include <cassert> 61 #include <cstdint> 62 #include <iterator> 63 #include <new> 64 #include <utility> 65 #include <vector> 66 67 using namespace llvm; 68 69 #define DEBUG_TYPE "arm-instrinfo" 70 71 #define GET_INSTRINFO_CTOR_DTOR 72 #include "ARMGenInstrInfo.inc" 73 74 static cl::opt<bool> 75 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden, 76 cl::desc("Enable ARM 2-addr to 3-addr conv")); 77 78 /// ARM_MLxEntry - Record information about MLA / MLS instructions. 79 struct ARM_MLxEntry { 80 uint16_t MLxOpc; // MLA / MLS opcode 81 uint16_t MulOpc; // Expanded multiplication opcode 82 uint16_t AddSubOpc; // Expanded add / sub opcode 83 bool NegAcc; // True if the acc is negated before the add / sub. 84 bool HasLane; // True if instruction has an extra "lane" operand. 85 }; 86 87 static const ARM_MLxEntry ARM_MLxTable[] = { 88 // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane 89 // fp scalar ops 90 { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false }, 91 { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false }, 92 { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false }, 93 { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false }, 94 { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false }, 95 { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false }, 96 { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false }, 97 { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false }, 98 99 // fp SIMD ops 100 { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false }, 101 { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false }, 102 { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false }, 103 { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false }, 104 { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true }, 105 { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true }, 106 { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true }, 107 { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true }, 108 }; 109 110 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI) 111 : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP), 112 Subtarget(STI) { 113 for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) { 114 if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second) 115 llvm_unreachable("Duplicated entries?"); 116 MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc); 117 MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc); 118 } 119 } 120 121 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl 122 // currently defaults to no prepass hazard recognizer. 123 ScheduleHazardRecognizer * 124 ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, 125 const ScheduleDAG *DAG) const { 126 if (usePreRAHazardRecognizer()) { 127 const InstrItineraryData *II = 128 static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData(); 129 return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched"); 130 } 131 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG); 132 } 133 134 ScheduleHazardRecognizer *ARMBaseInstrInfo:: 135 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, 136 const ScheduleDAG *DAG) const { 137 if (Subtarget.isThumb2() || Subtarget.hasVFP2Base()) 138 return new ARMHazardRecognizer(II, DAG); 139 return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG); 140 } 141 142 MachineInstr *ARMBaseInstrInfo::convertToThreeAddress( 143 MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const { 144 // FIXME: Thumb2 support. 145 146 if (!EnableARM3Addr) 147 return nullptr; 148 149 MachineFunction &MF = *MI.getParent()->getParent(); 150 uint64_t TSFlags = MI.getDesc().TSFlags; 151 bool isPre = false; 152 switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) { 153 default: return nullptr; 154 case ARMII::IndexModePre: 155 isPre = true; 156 break; 157 case ARMII::IndexModePost: 158 break; 159 } 160 161 // Try splitting an indexed load/store to an un-indexed one plus an add/sub 162 // operation. 163 unsigned MemOpc = getUnindexedOpcode(MI.getOpcode()); 164 if (MemOpc == 0) 165 return nullptr; 166 167 MachineInstr *UpdateMI = nullptr; 168 MachineInstr *MemMI = nullptr; 169 unsigned AddrMode = (TSFlags & ARMII::AddrModeMask); 170 const MCInstrDesc &MCID = MI.getDesc(); 171 unsigned NumOps = MCID.getNumOperands(); 172 bool isLoad = !MI.mayStore(); 173 const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0); 174 const MachineOperand &Base = MI.getOperand(2); 175 const MachineOperand &Offset = MI.getOperand(NumOps - 3); 176 Register WBReg = WB.getReg(); 177 Register BaseReg = Base.getReg(); 178 Register OffReg = Offset.getReg(); 179 unsigned OffImm = MI.getOperand(NumOps - 2).getImm(); 180 ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm(); 181 switch (AddrMode) { 182 default: llvm_unreachable("Unknown indexed op!"); 183 case ARMII::AddrMode2: { 184 bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub; 185 unsigned Amt = ARM_AM::getAM2Offset(OffImm); 186 if (OffReg == 0) { 187 if (ARM_AM::getSOImmVal(Amt) == -1) 188 // Can't encode it in a so_imm operand. This transformation will 189 // add more than 1 instruction. Abandon! 190 return nullptr; 191 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 192 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg) 193 .addReg(BaseReg) 194 .addImm(Amt) 195 .add(predOps(Pred)) 196 .add(condCodeOp()); 197 } else if (Amt != 0) { 198 ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm); 199 unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt); 200 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 201 get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg) 202 .addReg(BaseReg) 203 .addReg(OffReg) 204 .addReg(0) 205 .addImm(SOOpc) 206 .add(predOps(Pred)) 207 .add(condCodeOp()); 208 } else 209 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 210 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg) 211 .addReg(BaseReg) 212 .addReg(OffReg) 213 .add(predOps(Pred)) 214 .add(condCodeOp()); 215 break; 216 } 217 case ARMII::AddrMode3 : { 218 bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub; 219 unsigned Amt = ARM_AM::getAM3Offset(OffImm); 220 if (OffReg == 0) 221 // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand. 222 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 223 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg) 224 .addReg(BaseReg) 225 .addImm(Amt) 226 .add(predOps(Pred)) 227 .add(condCodeOp()); 228 else 229 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 230 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg) 231 .addReg(BaseReg) 232 .addReg(OffReg) 233 .add(predOps(Pred)) 234 .add(condCodeOp()); 235 break; 236 } 237 } 238 239 std::vector<MachineInstr*> NewMIs; 240 if (isPre) { 241 if (isLoad) 242 MemMI = 243 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg()) 244 .addReg(WBReg) 245 .addImm(0) 246 .addImm(Pred); 247 else 248 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc)) 249 .addReg(MI.getOperand(1).getReg()) 250 .addReg(WBReg) 251 .addReg(0) 252 .addImm(0) 253 .addImm(Pred); 254 NewMIs.push_back(MemMI); 255 NewMIs.push_back(UpdateMI); 256 } else { 257 if (isLoad) 258 MemMI = 259 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg()) 260 .addReg(BaseReg) 261 .addImm(0) 262 .addImm(Pred); 263 else 264 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc)) 265 .addReg(MI.getOperand(1).getReg()) 266 .addReg(BaseReg) 267 .addReg(0) 268 .addImm(0) 269 .addImm(Pred); 270 if (WB.isDead()) 271 UpdateMI->getOperand(0).setIsDead(); 272 NewMIs.push_back(UpdateMI); 273 NewMIs.push_back(MemMI); 274 } 275 276 // Transfer LiveVariables states, kill / dead info. 277 if (LV) { 278 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 279 MachineOperand &MO = MI.getOperand(i); 280 if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) { 281 Register Reg = MO.getReg(); 282 283 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg); 284 if (MO.isDef()) { 285 MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI; 286 if (MO.isDead()) 287 LV->addVirtualRegisterDead(Reg, *NewMI); 288 } 289 if (MO.isUse() && MO.isKill()) { 290 for (unsigned j = 0; j < 2; ++j) { 291 // Look at the two new MI's in reverse order. 292 MachineInstr *NewMI = NewMIs[j]; 293 if (!NewMI->readsRegister(Reg)) 294 continue; 295 LV->addVirtualRegisterKilled(Reg, *NewMI); 296 if (VI.removeKill(MI)) 297 VI.Kills.push_back(NewMI); 298 break; 299 } 300 } 301 } 302 } 303 } 304 305 MachineBasicBlock::iterator MBBI = MI.getIterator(); 306 MFI->insert(MBBI, NewMIs[1]); 307 MFI->insert(MBBI, NewMIs[0]); 308 return NewMIs[0]; 309 } 310 311 // Branch analysis. 312 bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB, 313 MachineBasicBlock *&TBB, 314 MachineBasicBlock *&FBB, 315 SmallVectorImpl<MachineOperand> &Cond, 316 bool AllowModify) const { 317 TBB = nullptr; 318 FBB = nullptr; 319 320 MachineBasicBlock::instr_iterator I = MBB.instr_end(); 321 if (I == MBB.instr_begin()) 322 return false; // Empty blocks are easy. 323 --I; 324 325 // Walk backwards from the end of the basic block until the branch is 326 // analyzed or we give up. 327 while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) { 328 // Flag to be raised on unanalyzeable instructions. This is useful in cases 329 // where we want to clean up on the end of the basic block before we bail 330 // out. 331 bool CantAnalyze = false; 332 333 // Skip over DEBUG values and predicated nonterminators. 334 while (I->isDebugInstr() || !I->isTerminator()) { 335 if (I == MBB.instr_begin()) 336 return false; 337 --I; 338 } 339 340 if (isIndirectBranchOpcode(I->getOpcode()) || 341 isJumpTableBranchOpcode(I->getOpcode())) { 342 // Indirect branches and jump tables can't be analyzed, but we still want 343 // to clean up any instructions at the tail of the basic block. 344 CantAnalyze = true; 345 } else if (isUncondBranchOpcode(I->getOpcode())) { 346 TBB = I->getOperand(0).getMBB(); 347 } else if (isCondBranchOpcode(I->getOpcode())) { 348 // Bail out if we encounter multiple conditional branches. 349 if (!Cond.empty()) 350 return true; 351 352 assert(!FBB && "FBB should have been null."); 353 FBB = TBB; 354 TBB = I->getOperand(0).getMBB(); 355 Cond.push_back(I->getOperand(1)); 356 Cond.push_back(I->getOperand(2)); 357 } else if (I->isReturn()) { 358 // Returns can't be analyzed, but we should run cleanup. 359 CantAnalyze = true; 360 } else { 361 // We encountered other unrecognized terminator. Bail out immediately. 362 return true; 363 } 364 365 // Cleanup code - to be run for unpredicated unconditional branches and 366 // returns. 367 if (!isPredicated(*I) && 368 (isUncondBranchOpcode(I->getOpcode()) || 369 isIndirectBranchOpcode(I->getOpcode()) || 370 isJumpTableBranchOpcode(I->getOpcode()) || 371 I->isReturn())) { 372 // Forget any previous condition branch information - it no longer applies. 373 Cond.clear(); 374 FBB = nullptr; 375 376 // If we can modify the function, delete everything below this 377 // unconditional branch. 378 if (AllowModify) { 379 MachineBasicBlock::iterator DI = std::next(I); 380 while (DI != MBB.instr_end()) { 381 MachineInstr &InstToDelete = *DI; 382 ++DI; 383 InstToDelete.eraseFromParent(); 384 } 385 } 386 } 387 388 if (CantAnalyze) { 389 // We may not be able to analyze the block, but we could still have 390 // an unconditional branch as the last instruction in the block, which 391 // just branches to layout successor. If this is the case, then just 392 // remove it if we're allowed to make modifications. 393 if (AllowModify && !isPredicated(MBB.back()) && 394 isUncondBranchOpcode(MBB.back().getOpcode()) && 395 TBB && MBB.isLayoutSuccessor(TBB)) 396 removeBranch(MBB); 397 return true; 398 } 399 400 if (I == MBB.instr_begin()) 401 return false; 402 403 --I; 404 } 405 406 // We made it past the terminators without bailing out - we must have 407 // analyzed this branch successfully. 408 return false; 409 } 410 411 unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB, 412 int *BytesRemoved) const { 413 assert(!BytesRemoved && "code size not handled"); 414 415 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 416 if (I == MBB.end()) 417 return 0; 418 419 if (!isUncondBranchOpcode(I->getOpcode()) && 420 !isCondBranchOpcode(I->getOpcode())) 421 return 0; 422 423 // Remove the branch. 424 I->eraseFromParent(); 425 426 I = MBB.end(); 427 428 if (I == MBB.begin()) return 1; 429 --I; 430 if (!isCondBranchOpcode(I->getOpcode())) 431 return 1; 432 433 // Remove the branch. 434 I->eraseFromParent(); 435 return 2; 436 } 437 438 unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB, 439 MachineBasicBlock *TBB, 440 MachineBasicBlock *FBB, 441 ArrayRef<MachineOperand> Cond, 442 const DebugLoc &DL, 443 int *BytesAdded) const { 444 assert(!BytesAdded && "code size not handled"); 445 ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>(); 446 int BOpc = !AFI->isThumbFunction() 447 ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB); 448 int BccOpc = !AFI->isThumbFunction() 449 ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc); 450 bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function(); 451 452 // Shouldn't be a fall through. 453 assert(TBB && "insertBranch must not be told to insert a fallthrough"); 454 assert((Cond.size() == 2 || Cond.size() == 0) && 455 "ARM branch conditions have two components!"); 456 457 // For conditional branches, we use addOperand to preserve CPSR flags. 458 459 if (!FBB) { 460 if (Cond.empty()) { // Unconditional branch? 461 if (isThumb) 462 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL)); 463 else 464 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB); 465 } else 466 BuildMI(&MBB, DL, get(BccOpc)) 467 .addMBB(TBB) 468 .addImm(Cond[0].getImm()) 469 .add(Cond[1]); 470 return 1; 471 } 472 473 // Two-way conditional branch. 474 BuildMI(&MBB, DL, get(BccOpc)) 475 .addMBB(TBB) 476 .addImm(Cond[0].getImm()) 477 .add(Cond[1]); 478 if (isThumb) 479 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL)); 480 else 481 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB); 482 return 2; 483 } 484 485 bool ARMBaseInstrInfo:: 486 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const { 487 ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm(); 488 Cond[0].setImm(ARMCC::getOppositeCondition(CC)); 489 return false; 490 } 491 492 bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const { 493 if (MI.isBundle()) { 494 MachineBasicBlock::const_instr_iterator I = MI.getIterator(); 495 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 496 while (++I != E && I->isInsideBundle()) { 497 int PIdx = I->findFirstPredOperandIdx(); 498 if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL) 499 return true; 500 } 501 return false; 502 } 503 504 int PIdx = MI.findFirstPredOperandIdx(); 505 return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL; 506 } 507 508 std::string ARMBaseInstrInfo::createMIROperandComment( 509 const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx, 510 const TargetRegisterInfo *TRI) const { 511 512 // First, let's see if there is a generic comment for this operand 513 std::string GenericComment = 514 TargetInstrInfo::createMIROperandComment(MI, Op, OpIdx, TRI); 515 if (!GenericComment.empty()) 516 return GenericComment; 517 518 // If not, check if we have an immediate operand. 519 if (Op.getType() != MachineOperand::MO_Immediate) 520 return std::string(); 521 522 // And print its corresponding condition code if the immediate is a 523 // predicate. 524 int FirstPredOp = MI.findFirstPredOperandIdx(); 525 if (FirstPredOp != (int) OpIdx) 526 return std::string(); 527 528 std::string CC = "CC::"; 529 CC += ARMCondCodeToString((ARMCC::CondCodes)Op.getImm()); 530 return CC; 531 } 532 533 bool ARMBaseInstrInfo::PredicateInstruction( 534 MachineInstr &MI, ArrayRef<MachineOperand> Pred) const { 535 unsigned Opc = MI.getOpcode(); 536 if (isUncondBranchOpcode(Opc)) { 537 MI.setDesc(get(getMatchingCondBranchOpcode(Opc))); 538 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 539 .addImm(Pred[0].getImm()) 540 .addReg(Pred[1].getReg()); 541 return true; 542 } 543 544 int PIdx = MI.findFirstPredOperandIdx(); 545 if (PIdx != -1) { 546 MachineOperand &PMO = MI.getOperand(PIdx); 547 PMO.setImm(Pred[0].getImm()); 548 MI.getOperand(PIdx+1).setReg(Pred[1].getReg()); 549 550 // Thumb 1 arithmetic instructions do not set CPSR when executed inside an 551 // IT block. This affects how they are printed. 552 const MCInstrDesc &MCID = MI.getDesc(); 553 if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) { 554 assert(MCID.OpInfo[1].isOptionalDef() && "CPSR def isn't expected operand"); 555 assert((MI.getOperand(1).isDead() || 556 MI.getOperand(1).getReg() != ARM::CPSR) && 557 "if conversion tried to stop defining used CPSR"); 558 MI.getOperand(1).setReg(ARM::NoRegister); 559 } 560 561 return true; 562 } 563 return false; 564 } 565 566 bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1, 567 ArrayRef<MachineOperand> Pred2) const { 568 if (Pred1.size() > 2 || Pred2.size() > 2) 569 return false; 570 571 ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm(); 572 ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm(); 573 if (CC1 == CC2) 574 return true; 575 576 switch (CC1) { 577 default: 578 return false; 579 case ARMCC::AL: 580 return true; 581 case ARMCC::HS: 582 return CC2 == ARMCC::HI; 583 case ARMCC::LS: 584 return CC2 == ARMCC::LO || CC2 == ARMCC::EQ; 585 case ARMCC::GE: 586 return CC2 == ARMCC::GT; 587 case ARMCC::LE: 588 return CC2 == ARMCC::LT; 589 } 590 } 591 592 bool ARMBaseInstrInfo::DefinesPredicate( 593 MachineInstr &MI, std::vector<MachineOperand> &Pred) const { 594 bool Found = false; 595 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 596 const MachineOperand &MO = MI.getOperand(i); 597 if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) || 598 (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) { 599 Pred.push_back(MO); 600 Found = true; 601 } 602 } 603 604 return Found; 605 } 606 607 bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) { 608 for (const auto &MO : MI.operands()) 609 if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead()) 610 return true; 611 return false; 612 } 613 614 bool ARMBaseInstrInfo::isAddrMode3OpImm(const MachineInstr &MI, 615 unsigned Op) const { 616 const MachineOperand &Offset = MI.getOperand(Op + 1); 617 return Offset.getReg() != 0; 618 } 619 620 // Load with negative register offset requires additional 1cyc and +I unit 621 // for Cortex A57 622 bool ARMBaseInstrInfo::isAddrMode3OpMinusReg(const MachineInstr &MI, 623 unsigned Op) const { 624 const MachineOperand &Offset = MI.getOperand(Op + 1); 625 const MachineOperand &Opc = MI.getOperand(Op + 2); 626 assert(Opc.isImm()); 627 assert(Offset.isReg()); 628 int64_t OpcImm = Opc.getImm(); 629 630 bool isSub = ARM_AM::getAM3Op(OpcImm) == ARM_AM::sub; 631 return (isSub && Offset.getReg() != 0); 632 } 633 634 bool ARMBaseInstrInfo::isLdstScaledReg(const MachineInstr &MI, 635 unsigned Op) const { 636 const MachineOperand &Opc = MI.getOperand(Op + 2); 637 unsigned OffImm = Opc.getImm(); 638 return ARM_AM::getAM2ShiftOpc(OffImm) != ARM_AM::no_shift; 639 } 640 641 // Load, scaled register offset, not plus LSL2 642 bool ARMBaseInstrInfo::isLdstScaledRegNotPlusLsl2(const MachineInstr &MI, 643 unsigned Op) const { 644 const MachineOperand &Opc = MI.getOperand(Op + 2); 645 unsigned OffImm = Opc.getImm(); 646 647 bool isAdd = ARM_AM::getAM2Op(OffImm) == ARM_AM::add; 648 unsigned Amt = ARM_AM::getAM2Offset(OffImm); 649 ARM_AM::ShiftOpc ShiftOpc = ARM_AM::getAM2ShiftOpc(OffImm); 650 if (ShiftOpc == ARM_AM::no_shift) return false; // not scaled 651 bool SimpleScaled = (isAdd && ShiftOpc == ARM_AM::lsl && Amt == 2); 652 return !SimpleScaled; 653 } 654 655 // Minus reg for ldstso addr mode 656 bool ARMBaseInstrInfo::isLdstSoMinusReg(const MachineInstr &MI, 657 unsigned Op) const { 658 unsigned OffImm = MI.getOperand(Op + 2).getImm(); 659 return ARM_AM::getAM2Op(OffImm) == ARM_AM::sub; 660 } 661 662 // Load, scaled register offset 663 bool ARMBaseInstrInfo::isAm2ScaledReg(const MachineInstr &MI, 664 unsigned Op) const { 665 unsigned OffImm = MI.getOperand(Op + 2).getImm(); 666 return ARM_AM::getAM2ShiftOpc(OffImm) != ARM_AM::no_shift; 667 } 668 669 static bool isEligibleForITBlock(const MachineInstr *MI) { 670 switch (MI->getOpcode()) { 671 default: return true; 672 case ARM::tADC: // ADC (register) T1 673 case ARM::tADDi3: // ADD (immediate) T1 674 case ARM::tADDi8: // ADD (immediate) T2 675 case ARM::tADDrr: // ADD (register) T1 676 case ARM::tAND: // AND (register) T1 677 case ARM::tASRri: // ASR (immediate) T1 678 case ARM::tASRrr: // ASR (register) T1 679 case ARM::tBIC: // BIC (register) T1 680 case ARM::tEOR: // EOR (register) T1 681 case ARM::tLSLri: // LSL (immediate) T1 682 case ARM::tLSLrr: // LSL (register) T1 683 case ARM::tLSRri: // LSR (immediate) T1 684 case ARM::tLSRrr: // LSR (register) T1 685 case ARM::tMUL: // MUL T1 686 case ARM::tMVN: // MVN (register) T1 687 case ARM::tORR: // ORR (register) T1 688 case ARM::tROR: // ROR (register) T1 689 case ARM::tRSB: // RSB (immediate) T1 690 case ARM::tSBC: // SBC (register) T1 691 case ARM::tSUBi3: // SUB (immediate) T1 692 case ARM::tSUBi8: // SUB (immediate) T2 693 case ARM::tSUBrr: // SUB (register) T1 694 return !ARMBaseInstrInfo::isCPSRDefined(*MI); 695 } 696 } 697 698 /// isPredicable - Return true if the specified instruction can be predicated. 699 /// By default, this returns true for every instruction with a 700 /// PredicateOperand. 701 bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const { 702 if (!MI.isPredicable()) 703 return false; 704 705 if (MI.isBundle()) 706 return false; 707 708 if (!isEligibleForITBlock(&MI)) 709 return false; 710 711 const ARMFunctionInfo *AFI = 712 MI.getParent()->getParent()->getInfo<ARMFunctionInfo>(); 713 714 // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM. 715 // In their ARM encoding, they can't be encoded in a conditional form. 716 if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) 717 return false; 718 719 if (AFI->isThumb2Function()) { 720 if (getSubtarget().restrictIT()) 721 return isV8EligibleForIT(&MI); 722 } 723 724 return true; 725 } 726 727 namespace llvm { 728 729 template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) { 730 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 731 const MachineOperand &MO = MI->getOperand(i); 732 if (!MO.isReg() || MO.isUndef() || MO.isUse()) 733 continue; 734 if (MO.getReg() != ARM::CPSR) 735 continue; 736 if (!MO.isDead()) 737 return false; 738 } 739 // all definitions of CPSR are dead 740 return true; 741 } 742 743 } // end namespace llvm 744 745 /// GetInstSize - Return the size of the specified MachineInstr. 746 /// 747 unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const { 748 const MachineBasicBlock &MBB = *MI.getParent(); 749 const MachineFunction *MF = MBB.getParent(); 750 const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo(); 751 752 const MCInstrDesc &MCID = MI.getDesc(); 753 if (MCID.getSize()) 754 return MCID.getSize(); 755 756 switch (MI.getOpcode()) { 757 default: 758 // pseudo-instruction sizes are zero. 759 return 0; 760 case TargetOpcode::BUNDLE: 761 return getInstBundleLength(MI); 762 case ARM::MOVi16_ga_pcrel: 763 case ARM::MOVTi16_ga_pcrel: 764 case ARM::t2MOVi16_ga_pcrel: 765 case ARM::t2MOVTi16_ga_pcrel: 766 return 4; 767 case ARM::MOVi32imm: 768 case ARM::t2MOVi32imm: 769 return 8; 770 case ARM::CONSTPOOL_ENTRY: 771 case ARM::JUMPTABLE_INSTS: 772 case ARM::JUMPTABLE_ADDRS: 773 case ARM::JUMPTABLE_TBB: 774 case ARM::JUMPTABLE_TBH: 775 // If this machine instr is a constant pool entry, its size is recorded as 776 // operand #2. 777 return MI.getOperand(2).getImm(); 778 case ARM::Int_eh_sjlj_longjmp: 779 return 16; 780 case ARM::tInt_eh_sjlj_longjmp: 781 return 10; 782 case ARM::tInt_WIN_eh_sjlj_longjmp: 783 return 12; 784 case ARM::Int_eh_sjlj_setjmp: 785 case ARM::Int_eh_sjlj_setjmp_nofp: 786 return 20; 787 case ARM::tInt_eh_sjlj_setjmp: 788 case ARM::t2Int_eh_sjlj_setjmp: 789 case ARM::t2Int_eh_sjlj_setjmp_nofp: 790 return 12; 791 case ARM::SPACE: 792 return MI.getOperand(1).getImm(); 793 case ARM::INLINEASM: 794 case ARM::INLINEASM_BR: { 795 // If this machine instr is an inline asm, measure it. 796 unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI); 797 if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction()) 798 Size = alignTo(Size, 4); 799 return Size; 800 } 801 } 802 } 803 804 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const { 805 unsigned Size = 0; 806 MachineBasicBlock::const_instr_iterator I = MI.getIterator(); 807 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 808 while (++I != E && I->isInsideBundle()) { 809 assert(!I->isBundle() && "No nested bundle!"); 810 Size += getInstSizeInBytes(*I); 811 } 812 return Size; 813 } 814 815 void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB, 816 MachineBasicBlock::iterator I, 817 unsigned DestReg, bool KillSrc, 818 const ARMSubtarget &Subtarget) const { 819 unsigned Opc = Subtarget.isThumb() 820 ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR) 821 : ARM::MRS; 822 823 MachineInstrBuilder MIB = 824 BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg); 825 826 // There is only 1 A/R class MRS instruction, and it always refers to 827 // APSR. However, there are lots of other possibilities on M-class cores. 828 if (Subtarget.isMClass()) 829 MIB.addImm(0x800); 830 831 MIB.add(predOps(ARMCC::AL)) 832 .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc)); 833 } 834 835 void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB, 836 MachineBasicBlock::iterator I, 837 unsigned SrcReg, bool KillSrc, 838 const ARMSubtarget &Subtarget) const { 839 unsigned Opc = Subtarget.isThumb() 840 ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR) 841 : ARM::MSR; 842 843 MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc)); 844 845 if (Subtarget.isMClass()) 846 MIB.addImm(0x800); 847 else 848 MIB.addImm(8); 849 850 MIB.addReg(SrcReg, getKillRegState(KillSrc)) 851 .add(predOps(ARMCC::AL)) 852 .addReg(ARM::CPSR, RegState::Implicit | RegState::Define); 853 } 854 855 void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) { 856 MIB.addImm(ARMVCC::None); 857 MIB.addReg(0); 858 } 859 860 void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB, 861 Register DestReg) { 862 addUnpredicatedMveVpredNOp(MIB); 863 MIB.addReg(DestReg, RegState::Undef); 864 } 865 866 void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) { 867 MIB.addImm(Cond); 868 MIB.addReg(ARM::VPR, RegState::Implicit); 869 } 870 871 void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB, 872 unsigned Cond, unsigned Inactive) { 873 addPredicatedMveVpredNOp(MIB, Cond); 874 MIB.addReg(Inactive); 875 } 876 877 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB, 878 MachineBasicBlock::iterator I, 879 const DebugLoc &DL, MCRegister DestReg, 880 MCRegister SrcReg, bool KillSrc) const { 881 bool GPRDest = ARM::GPRRegClass.contains(DestReg); 882 bool GPRSrc = ARM::GPRRegClass.contains(SrcReg); 883 884 if (GPRDest && GPRSrc) { 885 BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg) 886 .addReg(SrcReg, getKillRegState(KillSrc)) 887 .add(predOps(ARMCC::AL)) 888 .add(condCodeOp()); 889 return; 890 } 891 892 bool SPRDest = ARM::SPRRegClass.contains(DestReg); 893 bool SPRSrc = ARM::SPRRegClass.contains(SrcReg); 894 895 unsigned Opc = 0; 896 if (SPRDest && SPRSrc) 897 Opc = ARM::VMOVS; 898 else if (GPRDest && SPRSrc) 899 Opc = ARM::VMOVRS; 900 else if (SPRDest && GPRSrc) 901 Opc = ARM::VMOVSR; 902 else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64()) 903 Opc = ARM::VMOVD; 904 else if (ARM::QPRRegClass.contains(DestReg, SrcReg)) 905 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR; 906 907 if (Opc) { 908 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg); 909 MIB.addReg(SrcReg, getKillRegState(KillSrc)); 910 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) 911 MIB.addReg(SrcReg, getKillRegState(KillSrc)); 912 if (Opc == ARM::MVE_VORR) 913 addUnpredicatedMveVpredROp(MIB, DestReg); 914 else 915 MIB.add(predOps(ARMCC::AL)); 916 return; 917 } 918 919 // Handle register classes that require multiple instructions. 920 unsigned BeginIdx = 0; 921 unsigned SubRegs = 0; 922 int Spacing = 1; 923 924 // Use VORRq when possible. 925 if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) { 926 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR; 927 BeginIdx = ARM::qsub_0; 928 SubRegs = 2; 929 } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) { 930 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR; 931 BeginIdx = ARM::qsub_0; 932 SubRegs = 4; 933 // Fall back to VMOVD. 934 } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) { 935 Opc = ARM::VMOVD; 936 BeginIdx = ARM::dsub_0; 937 SubRegs = 2; 938 } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) { 939 Opc = ARM::VMOVD; 940 BeginIdx = ARM::dsub_0; 941 SubRegs = 3; 942 } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) { 943 Opc = ARM::VMOVD; 944 BeginIdx = ARM::dsub_0; 945 SubRegs = 4; 946 } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) { 947 Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr; 948 BeginIdx = ARM::gsub_0; 949 SubRegs = 2; 950 } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) { 951 Opc = ARM::VMOVD; 952 BeginIdx = ARM::dsub_0; 953 SubRegs = 2; 954 Spacing = 2; 955 } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) { 956 Opc = ARM::VMOVD; 957 BeginIdx = ARM::dsub_0; 958 SubRegs = 3; 959 Spacing = 2; 960 } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) { 961 Opc = ARM::VMOVD; 962 BeginIdx = ARM::dsub_0; 963 SubRegs = 4; 964 Spacing = 2; 965 } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && 966 !Subtarget.hasFP64()) { 967 Opc = ARM::VMOVS; 968 BeginIdx = ARM::ssub_0; 969 SubRegs = 2; 970 } else if (SrcReg == ARM::CPSR) { 971 copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget); 972 return; 973 } else if (DestReg == ARM::CPSR) { 974 copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget); 975 return; 976 } else if (DestReg == ARM::VPR) { 977 assert(ARM::GPRRegClass.contains(SrcReg)); 978 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg) 979 .addReg(SrcReg, getKillRegState(KillSrc)) 980 .add(predOps(ARMCC::AL)); 981 return; 982 } else if (SrcReg == ARM::VPR) { 983 assert(ARM::GPRRegClass.contains(DestReg)); 984 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg) 985 .addReg(SrcReg, getKillRegState(KillSrc)) 986 .add(predOps(ARMCC::AL)); 987 return; 988 } else if (DestReg == ARM::FPSCR_NZCV) { 989 assert(ARM::GPRRegClass.contains(SrcReg)); 990 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg) 991 .addReg(SrcReg, getKillRegState(KillSrc)) 992 .add(predOps(ARMCC::AL)); 993 return; 994 } else if (SrcReg == ARM::FPSCR_NZCV) { 995 assert(ARM::GPRRegClass.contains(DestReg)); 996 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg) 997 .addReg(SrcReg, getKillRegState(KillSrc)) 998 .add(predOps(ARMCC::AL)); 999 return; 1000 } 1001 1002 assert(Opc && "Impossible reg-to-reg copy"); 1003 1004 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1005 MachineInstrBuilder Mov; 1006 1007 // Copy register tuples backward when the first Dest reg overlaps with SrcReg. 1008 if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) { 1009 BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing); 1010 Spacing = -Spacing; 1011 } 1012 #ifndef NDEBUG 1013 SmallSet<unsigned, 4> DstRegs; 1014 #endif 1015 for (unsigned i = 0; i != SubRegs; ++i) { 1016 Register Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing); 1017 Register Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing); 1018 assert(Dst && Src && "Bad sub-register"); 1019 #ifndef NDEBUG 1020 assert(!DstRegs.count(Src) && "destructive vector copy"); 1021 DstRegs.insert(Dst); 1022 #endif 1023 Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src); 1024 // VORR (NEON or MVE) takes two source operands. 1025 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) { 1026 Mov.addReg(Src); 1027 } 1028 // MVE VORR takes predicate operands in place of an ordinary condition. 1029 if (Opc == ARM::MVE_VORR) 1030 addUnpredicatedMveVpredROp(Mov, Dst); 1031 else 1032 Mov = Mov.add(predOps(ARMCC::AL)); 1033 // MOVr can set CC. 1034 if (Opc == ARM::MOVr) 1035 Mov = Mov.add(condCodeOp()); 1036 } 1037 // Add implicit super-register defs and kills to the last instruction. 1038 Mov->addRegisterDefined(DestReg, TRI); 1039 if (KillSrc) 1040 Mov->addRegisterKilled(SrcReg, TRI); 1041 } 1042 1043 Optional<DestSourcePair> 1044 ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const { 1045 // VMOVRRD is also a copy instruction but it requires 1046 // special way of handling. It is more complex copy version 1047 // and since that we are not considering it. For recognition 1048 // of such instruction isExtractSubregLike MI interface fuction 1049 // could be used. 1050 // VORRq is considered as a move only if two inputs are 1051 // the same register. 1052 if (!MI.isMoveReg() || 1053 (MI.getOpcode() == ARM::VORRq && 1054 MI.getOperand(1).getReg() != MI.getOperand(2).getReg())) 1055 return None; 1056 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)}; 1057 } 1058 1059 Optional<ParamLoadedValue> 1060 ARMBaseInstrInfo::describeLoadedValue(const MachineInstr &MI, 1061 Register Reg) const { 1062 if (auto DstSrcPair = isCopyInstrImpl(MI)) { 1063 Register DstReg = DstSrcPair->Destination->getReg(); 1064 1065 // TODO: We don't handle cases where the forwarding reg is narrower/wider 1066 // than the copy registers. Consider for example: 1067 // 1068 // s16 = VMOVS s0 1069 // s17 = VMOVS s1 1070 // call @callee(d0) 1071 // 1072 // We'd like to describe the call site value of d0 as d8, but this requires 1073 // gathering and merging the descriptions for the two VMOVS instructions. 1074 // 1075 // We also don't handle the reverse situation, where the forwarding reg is 1076 // narrower than the copy destination: 1077 // 1078 // d8 = VMOVD d0 1079 // call @callee(s1) 1080 // 1081 // We need to produce a fragment description (the call site value of s1 is 1082 // /not/ just d8). 1083 if (DstReg != Reg) 1084 return None; 1085 } 1086 return TargetInstrInfo::describeLoadedValue(MI, Reg); 1087 } 1088 1089 const MachineInstrBuilder & 1090 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg, 1091 unsigned SubIdx, unsigned State, 1092 const TargetRegisterInfo *TRI) const { 1093 if (!SubIdx) 1094 return MIB.addReg(Reg, State); 1095 1096 if (Register::isPhysicalRegister(Reg)) 1097 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State); 1098 return MIB.addReg(Reg, State, SubIdx); 1099 } 1100 1101 void ARMBaseInstrInfo:: 1102 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, 1103 Register SrcReg, bool isKill, int FI, 1104 const TargetRegisterClass *RC, 1105 const TargetRegisterInfo *TRI) const { 1106 MachineFunction &MF = *MBB.getParent(); 1107 MachineFrameInfo &MFI = MF.getFrameInfo(); 1108 Align Alignment = MFI.getObjectAlign(FI); 1109 1110 MachineMemOperand *MMO = MF.getMachineMemOperand( 1111 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore, 1112 MFI.getObjectSize(FI), Alignment); 1113 1114 switch (TRI->getSpillSize(*RC)) { 1115 case 2: 1116 if (ARM::HPRRegClass.hasSubClassEq(RC)) { 1117 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH)) 1118 .addReg(SrcReg, getKillRegState(isKill)) 1119 .addFrameIndex(FI) 1120 .addImm(0) 1121 .addMemOperand(MMO) 1122 .add(predOps(ARMCC::AL)); 1123 } else 1124 llvm_unreachable("Unknown reg class!"); 1125 break; 1126 case 4: 1127 if (ARM::GPRRegClass.hasSubClassEq(RC)) { 1128 BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12)) 1129 .addReg(SrcReg, getKillRegState(isKill)) 1130 .addFrameIndex(FI) 1131 .addImm(0) 1132 .addMemOperand(MMO) 1133 .add(predOps(ARMCC::AL)); 1134 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) { 1135 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS)) 1136 .addReg(SrcReg, getKillRegState(isKill)) 1137 .addFrameIndex(FI) 1138 .addImm(0) 1139 .addMemOperand(MMO) 1140 .add(predOps(ARMCC::AL)); 1141 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) { 1142 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off)) 1143 .addReg(SrcReg, getKillRegState(isKill)) 1144 .addFrameIndex(FI) 1145 .addImm(0) 1146 .addMemOperand(MMO) 1147 .add(predOps(ARMCC::AL)); 1148 } else 1149 llvm_unreachable("Unknown reg class!"); 1150 break; 1151 case 8: 1152 if (ARM::DPRRegClass.hasSubClassEq(RC)) { 1153 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD)) 1154 .addReg(SrcReg, getKillRegState(isKill)) 1155 .addFrameIndex(FI) 1156 .addImm(0) 1157 .addMemOperand(MMO) 1158 .add(predOps(ARMCC::AL)); 1159 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) { 1160 if (Subtarget.hasV5TEOps()) { 1161 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD)); 1162 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI); 1163 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI); 1164 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO) 1165 .add(predOps(ARMCC::AL)); 1166 } else { 1167 // Fallback to STM instruction, which has existed since the dawn of 1168 // time. 1169 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA)) 1170 .addFrameIndex(FI) 1171 .addMemOperand(MMO) 1172 .add(predOps(ARMCC::AL)); 1173 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI); 1174 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI); 1175 } 1176 } else 1177 llvm_unreachable("Unknown reg class!"); 1178 break; 1179 case 16: 1180 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) { 1181 // Use aligned spills if the stack can be realigned. 1182 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) { 1183 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64)) 1184 .addFrameIndex(FI) 1185 .addImm(16) 1186 .addReg(SrcReg, getKillRegState(isKill)) 1187 .addMemOperand(MMO) 1188 .add(predOps(ARMCC::AL)); 1189 } else { 1190 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA)) 1191 .addReg(SrcReg, getKillRegState(isKill)) 1192 .addFrameIndex(FI) 1193 .addMemOperand(MMO) 1194 .add(predOps(ARMCC::AL)); 1195 } 1196 } else if (ARM::QPRRegClass.hasSubClassEq(RC) && 1197 Subtarget.hasMVEIntegerOps()) { 1198 auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32)); 1199 MIB.addReg(SrcReg, getKillRegState(isKill)) 1200 .addFrameIndex(FI) 1201 .addImm(0) 1202 .addMemOperand(MMO); 1203 addUnpredicatedMveVpredNOp(MIB); 1204 } else 1205 llvm_unreachable("Unknown reg class!"); 1206 break; 1207 case 24: 1208 if (ARM::DTripleRegClass.hasSubClassEq(RC)) { 1209 // Use aligned spills if the stack can be realigned. 1210 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1211 Subtarget.hasNEON()) { 1212 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo)) 1213 .addFrameIndex(FI) 1214 .addImm(16) 1215 .addReg(SrcReg, getKillRegState(isKill)) 1216 .addMemOperand(MMO) 1217 .add(predOps(ARMCC::AL)); 1218 } else { 1219 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), 1220 get(ARM::VSTMDIA)) 1221 .addFrameIndex(FI) 1222 .add(predOps(ARMCC::AL)) 1223 .addMemOperand(MMO); 1224 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); 1225 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); 1226 AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); 1227 } 1228 } else 1229 llvm_unreachable("Unknown reg class!"); 1230 break; 1231 case 32: 1232 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) { 1233 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1234 Subtarget.hasNEON()) { 1235 // FIXME: It's possible to only store part of the QQ register if the 1236 // spilled def has a sub-register index. 1237 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo)) 1238 .addFrameIndex(FI) 1239 .addImm(16) 1240 .addReg(SrcReg, getKillRegState(isKill)) 1241 .addMemOperand(MMO) 1242 .add(predOps(ARMCC::AL)); 1243 } else { 1244 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), 1245 get(ARM::VSTMDIA)) 1246 .addFrameIndex(FI) 1247 .add(predOps(ARMCC::AL)) 1248 .addMemOperand(MMO); 1249 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); 1250 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); 1251 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); 1252 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI); 1253 } 1254 } else 1255 llvm_unreachable("Unknown reg class!"); 1256 break; 1257 case 64: 1258 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) { 1259 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA)) 1260 .addFrameIndex(FI) 1261 .add(predOps(ARMCC::AL)) 1262 .addMemOperand(MMO); 1263 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); 1264 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); 1265 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); 1266 MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI); 1267 MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI); 1268 MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI); 1269 MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI); 1270 AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI); 1271 } else 1272 llvm_unreachable("Unknown reg class!"); 1273 break; 1274 default: 1275 llvm_unreachable("Unknown reg class!"); 1276 } 1277 } 1278 1279 unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI, 1280 int &FrameIndex) const { 1281 switch (MI.getOpcode()) { 1282 default: break; 1283 case ARM::STRrs: 1284 case ARM::t2STRs: // FIXME: don't use t2STRs to access frame. 1285 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() && 1286 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 && 1287 MI.getOperand(3).getImm() == 0) { 1288 FrameIndex = MI.getOperand(1).getIndex(); 1289 return MI.getOperand(0).getReg(); 1290 } 1291 break; 1292 case ARM::STRi12: 1293 case ARM::t2STRi12: 1294 case ARM::tSTRspi: 1295 case ARM::VSTRD: 1296 case ARM::VSTRS: 1297 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() && 1298 MI.getOperand(2).getImm() == 0) { 1299 FrameIndex = MI.getOperand(1).getIndex(); 1300 return MI.getOperand(0).getReg(); 1301 } 1302 break; 1303 case ARM::VSTR_P0_off: 1304 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() && 1305 MI.getOperand(1).getImm() == 0) { 1306 FrameIndex = MI.getOperand(0).getIndex(); 1307 return ARM::P0; 1308 } 1309 break; 1310 case ARM::VST1q64: 1311 case ARM::VST1d64TPseudo: 1312 case ARM::VST1d64QPseudo: 1313 if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) { 1314 FrameIndex = MI.getOperand(0).getIndex(); 1315 return MI.getOperand(2).getReg(); 1316 } 1317 break; 1318 case ARM::VSTMQIA: 1319 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) { 1320 FrameIndex = MI.getOperand(1).getIndex(); 1321 return MI.getOperand(0).getReg(); 1322 } 1323 break; 1324 } 1325 1326 return 0; 1327 } 1328 1329 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI, 1330 int &FrameIndex) const { 1331 SmallVector<const MachineMemOperand *, 1> Accesses; 1332 if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) && 1333 Accesses.size() == 1) { 1334 FrameIndex = 1335 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue()) 1336 ->getFrameIndex(); 1337 return true; 1338 } 1339 return false; 1340 } 1341 1342 void ARMBaseInstrInfo:: 1343 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, 1344 Register DestReg, int FI, 1345 const TargetRegisterClass *RC, 1346 const TargetRegisterInfo *TRI) const { 1347 DebugLoc DL; 1348 if (I != MBB.end()) DL = I->getDebugLoc(); 1349 MachineFunction &MF = *MBB.getParent(); 1350 MachineFrameInfo &MFI = MF.getFrameInfo(); 1351 const Align Alignment = MFI.getObjectAlign(FI); 1352 MachineMemOperand *MMO = MF.getMachineMemOperand( 1353 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad, 1354 MFI.getObjectSize(FI), Alignment); 1355 1356 switch (TRI->getSpillSize(*RC)) { 1357 case 2: 1358 if (ARM::HPRRegClass.hasSubClassEq(RC)) { 1359 BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg) 1360 .addFrameIndex(FI) 1361 .addImm(0) 1362 .addMemOperand(MMO) 1363 .add(predOps(ARMCC::AL)); 1364 } else 1365 llvm_unreachable("Unknown reg class!"); 1366 break; 1367 case 4: 1368 if (ARM::GPRRegClass.hasSubClassEq(RC)) { 1369 BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg) 1370 .addFrameIndex(FI) 1371 .addImm(0) 1372 .addMemOperand(MMO) 1373 .add(predOps(ARMCC::AL)); 1374 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) { 1375 BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg) 1376 .addFrameIndex(FI) 1377 .addImm(0) 1378 .addMemOperand(MMO) 1379 .add(predOps(ARMCC::AL)); 1380 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) { 1381 BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg) 1382 .addFrameIndex(FI) 1383 .addImm(0) 1384 .addMemOperand(MMO) 1385 .add(predOps(ARMCC::AL)); 1386 } else 1387 llvm_unreachable("Unknown reg class!"); 1388 break; 1389 case 8: 1390 if (ARM::DPRRegClass.hasSubClassEq(RC)) { 1391 BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg) 1392 .addFrameIndex(FI) 1393 .addImm(0) 1394 .addMemOperand(MMO) 1395 .add(predOps(ARMCC::AL)); 1396 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) { 1397 MachineInstrBuilder MIB; 1398 1399 if (Subtarget.hasV5TEOps()) { 1400 MIB = BuildMI(MBB, I, DL, get(ARM::LDRD)); 1401 AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI); 1402 AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI); 1403 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO) 1404 .add(predOps(ARMCC::AL)); 1405 } else { 1406 // Fallback to LDM instruction, which has existed since the dawn of 1407 // time. 1408 MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA)) 1409 .addFrameIndex(FI) 1410 .addMemOperand(MMO) 1411 .add(predOps(ARMCC::AL)); 1412 MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI); 1413 MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI); 1414 } 1415 1416 if (Register::isPhysicalRegister(DestReg)) 1417 MIB.addReg(DestReg, RegState::ImplicitDefine); 1418 } else 1419 llvm_unreachable("Unknown reg class!"); 1420 break; 1421 case 16: 1422 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) { 1423 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) { 1424 BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg) 1425 .addFrameIndex(FI) 1426 .addImm(16) 1427 .addMemOperand(MMO) 1428 .add(predOps(ARMCC::AL)); 1429 } else { 1430 BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg) 1431 .addFrameIndex(FI) 1432 .addMemOperand(MMO) 1433 .add(predOps(ARMCC::AL)); 1434 } 1435 } else if (ARM::QPRRegClass.hasSubClassEq(RC) && 1436 Subtarget.hasMVEIntegerOps()) { 1437 auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg); 1438 MIB.addFrameIndex(FI) 1439 .addImm(0) 1440 .addMemOperand(MMO); 1441 addUnpredicatedMveVpredNOp(MIB); 1442 } else 1443 llvm_unreachable("Unknown reg class!"); 1444 break; 1445 case 24: 1446 if (ARM::DTripleRegClass.hasSubClassEq(RC)) { 1447 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1448 Subtarget.hasNEON()) { 1449 BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg) 1450 .addFrameIndex(FI) 1451 .addImm(16) 1452 .addMemOperand(MMO) 1453 .add(predOps(ARMCC::AL)); 1454 } else { 1455 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) 1456 .addFrameIndex(FI) 1457 .addMemOperand(MMO) 1458 .add(predOps(ARMCC::AL)); 1459 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); 1460 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); 1461 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); 1462 if (Register::isPhysicalRegister(DestReg)) 1463 MIB.addReg(DestReg, RegState::ImplicitDefine); 1464 } 1465 } else 1466 llvm_unreachable("Unknown reg class!"); 1467 break; 1468 case 32: 1469 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) { 1470 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1471 Subtarget.hasNEON()) { 1472 BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg) 1473 .addFrameIndex(FI) 1474 .addImm(16) 1475 .addMemOperand(MMO) 1476 .add(predOps(ARMCC::AL)); 1477 } else { 1478 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) 1479 .addFrameIndex(FI) 1480 .add(predOps(ARMCC::AL)) 1481 .addMemOperand(MMO); 1482 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); 1483 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); 1484 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); 1485 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI); 1486 if (Register::isPhysicalRegister(DestReg)) 1487 MIB.addReg(DestReg, RegState::ImplicitDefine); 1488 } 1489 } else 1490 llvm_unreachable("Unknown reg class!"); 1491 break; 1492 case 64: 1493 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) { 1494 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) 1495 .addFrameIndex(FI) 1496 .add(predOps(ARMCC::AL)) 1497 .addMemOperand(MMO); 1498 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); 1499 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); 1500 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); 1501 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI); 1502 MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI); 1503 MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI); 1504 MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI); 1505 MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI); 1506 if (Register::isPhysicalRegister(DestReg)) 1507 MIB.addReg(DestReg, RegState::ImplicitDefine); 1508 } else 1509 llvm_unreachable("Unknown reg class!"); 1510 break; 1511 default: 1512 llvm_unreachable("Unknown regclass!"); 1513 } 1514 } 1515 1516 unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI, 1517 int &FrameIndex) const { 1518 switch (MI.getOpcode()) { 1519 default: break; 1520 case ARM::LDRrs: 1521 case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame. 1522 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() && 1523 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 && 1524 MI.getOperand(3).getImm() == 0) { 1525 FrameIndex = MI.getOperand(1).getIndex(); 1526 return MI.getOperand(0).getReg(); 1527 } 1528 break; 1529 case ARM::LDRi12: 1530 case ARM::t2LDRi12: 1531 case ARM::tLDRspi: 1532 case ARM::VLDRD: 1533 case ARM::VLDRS: 1534 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() && 1535 MI.getOperand(2).getImm() == 0) { 1536 FrameIndex = MI.getOperand(1).getIndex(); 1537 return MI.getOperand(0).getReg(); 1538 } 1539 break; 1540 case ARM::VLDR_P0_off: 1541 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() && 1542 MI.getOperand(1).getImm() == 0) { 1543 FrameIndex = MI.getOperand(0).getIndex(); 1544 return ARM::P0; 1545 } 1546 break; 1547 case ARM::VLD1q64: 1548 case ARM::VLD1d8TPseudo: 1549 case ARM::VLD1d16TPseudo: 1550 case ARM::VLD1d32TPseudo: 1551 case ARM::VLD1d64TPseudo: 1552 case ARM::VLD1d8QPseudo: 1553 case ARM::VLD1d16QPseudo: 1554 case ARM::VLD1d32QPseudo: 1555 case ARM::VLD1d64QPseudo: 1556 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) { 1557 FrameIndex = MI.getOperand(1).getIndex(); 1558 return MI.getOperand(0).getReg(); 1559 } 1560 break; 1561 case ARM::VLDMQIA: 1562 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) { 1563 FrameIndex = MI.getOperand(1).getIndex(); 1564 return MI.getOperand(0).getReg(); 1565 } 1566 break; 1567 } 1568 1569 return 0; 1570 } 1571 1572 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI, 1573 int &FrameIndex) const { 1574 SmallVector<const MachineMemOperand *, 1> Accesses; 1575 if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) && 1576 Accesses.size() == 1) { 1577 FrameIndex = 1578 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue()) 1579 ->getFrameIndex(); 1580 return true; 1581 } 1582 return false; 1583 } 1584 1585 /// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD 1586 /// depending on whether the result is used. 1587 void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const { 1588 bool isThumb1 = Subtarget.isThumb1Only(); 1589 bool isThumb2 = Subtarget.isThumb2(); 1590 const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo(); 1591 1592 DebugLoc dl = MI->getDebugLoc(); 1593 MachineBasicBlock *BB = MI->getParent(); 1594 1595 MachineInstrBuilder LDM, STM; 1596 if (isThumb1 || !MI->getOperand(1).isDead()) { 1597 MachineOperand LDWb(MI->getOperand(1)); 1598 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD 1599 : isThumb1 ? ARM::tLDMIA_UPD 1600 : ARM::LDMIA_UPD)) 1601 .add(LDWb); 1602 } else { 1603 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA)); 1604 } 1605 1606 if (isThumb1 || !MI->getOperand(0).isDead()) { 1607 MachineOperand STWb(MI->getOperand(0)); 1608 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD 1609 : isThumb1 ? ARM::tSTMIA_UPD 1610 : ARM::STMIA_UPD)) 1611 .add(STWb); 1612 } else { 1613 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA)); 1614 } 1615 1616 MachineOperand LDBase(MI->getOperand(3)); 1617 LDM.add(LDBase).add(predOps(ARMCC::AL)); 1618 1619 MachineOperand STBase(MI->getOperand(2)); 1620 STM.add(STBase).add(predOps(ARMCC::AL)); 1621 1622 // Sort the scratch registers into ascending order. 1623 const TargetRegisterInfo &TRI = getRegisterInfo(); 1624 SmallVector<unsigned, 6> ScratchRegs; 1625 for(unsigned I = 5; I < MI->getNumOperands(); ++I) 1626 ScratchRegs.push_back(MI->getOperand(I).getReg()); 1627 llvm::sort(ScratchRegs, 1628 [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool { 1629 return TRI.getEncodingValue(Reg1) < 1630 TRI.getEncodingValue(Reg2); 1631 }); 1632 1633 for (const auto &Reg : ScratchRegs) { 1634 LDM.addReg(Reg, RegState::Define); 1635 STM.addReg(Reg, RegState::Kill); 1636 } 1637 1638 BB->erase(MI); 1639 } 1640 1641 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const { 1642 if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) { 1643 assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() && 1644 "LOAD_STACK_GUARD currently supported only for MachO."); 1645 expandLoadStackGuard(MI); 1646 MI.getParent()->erase(MI); 1647 return true; 1648 } 1649 1650 if (MI.getOpcode() == ARM::MEMCPY) { 1651 expandMEMCPY(MI); 1652 return true; 1653 } 1654 1655 // This hook gets to expand COPY instructions before they become 1656 // copyPhysReg() calls. Look for VMOVS instructions that can legally be 1657 // widened to VMOVD. We prefer the VMOVD when possible because it may be 1658 // changed into a VORR that can go down the NEON pipeline. 1659 if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64()) 1660 return false; 1661 1662 // Look for a copy between even S-registers. That is where we keep floats 1663 // when using NEON v2f32 instructions for f32 arithmetic. 1664 Register DstRegS = MI.getOperand(0).getReg(); 1665 Register SrcRegS = MI.getOperand(1).getReg(); 1666 if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS)) 1667 return false; 1668 1669 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1670 unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0, 1671 &ARM::DPRRegClass); 1672 unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0, 1673 &ARM::DPRRegClass); 1674 if (!DstRegD || !SrcRegD) 1675 return false; 1676 1677 // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only 1678 // legal if the COPY already defines the full DstRegD, and it isn't a 1679 // sub-register insertion. 1680 if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI)) 1681 return false; 1682 1683 // A dead copy shouldn't show up here, but reject it just in case. 1684 if (MI.getOperand(0).isDead()) 1685 return false; 1686 1687 // All clear, widen the COPY. 1688 LLVM_DEBUG(dbgs() << "widening: " << MI); 1689 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI); 1690 1691 // Get rid of the old implicit-def of DstRegD. Leave it if it defines a Q-reg 1692 // or some other super-register. 1693 int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD); 1694 if (ImpDefIdx != -1) 1695 MI.RemoveOperand(ImpDefIdx); 1696 1697 // Change the opcode and operands. 1698 MI.setDesc(get(ARM::VMOVD)); 1699 MI.getOperand(0).setReg(DstRegD); 1700 MI.getOperand(1).setReg(SrcRegD); 1701 MIB.add(predOps(ARMCC::AL)); 1702 1703 // We are now reading SrcRegD instead of SrcRegS. This may upset the 1704 // register scavenger and machine verifier, so we need to indicate that we 1705 // are reading an undefined value from SrcRegD, but a proper value from 1706 // SrcRegS. 1707 MI.getOperand(1).setIsUndef(); 1708 MIB.addReg(SrcRegS, RegState::Implicit); 1709 1710 // SrcRegD may actually contain an unrelated value in the ssub_1 1711 // sub-register. Don't kill it. Only kill the ssub_0 sub-register. 1712 if (MI.getOperand(1).isKill()) { 1713 MI.getOperand(1).setIsKill(false); 1714 MI.addRegisterKilled(SrcRegS, TRI, true); 1715 } 1716 1717 LLVM_DEBUG(dbgs() << "replaced by: " << MI); 1718 return true; 1719 } 1720 1721 /// Create a copy of a const pool value. Update CPI to the new index and return 1722 /// the label UID. 1723 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) { 1724 MachineConstantPool *MCP = MF.getConstantPool(); 1725 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1726 1727 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI]; 1728 assert(MCPE.isMachineConstantPoolEntry() && 1729 "Expecting a machine constantpool entry!"); 1730 ARMConstantPoolValue *ACPV = 1731 static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal); 1732 1733 unsigned PCLabelId = AFI->createPICLabelUId(); 1734 ARMConstantPoolValue *NewCPV = nullptr; 1735 1736 // FIXME: The below assumes PIC relocation model and that the function 1737 // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and 1738 // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR 1739 // instructions, so that's probably OK, but is PIC always correct when 1740 // we get here? 1741 if (ACPV->isGlobalValue()) 1742 NewCPV = ARMConstantPoolConstant::Create( 1743 cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue, 1744 4, ACPV->getModifier(), ACPV->mustAddCurrentAddress()); 1745 else if (ACPV->isExtSymbol()) 1746 NewCPV = ARMConstantPoolSymbol:: 1747 Create(MF.getFunction().getContext(), 1748 cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4); 1749 else if (ACPV->isBlockAddress()) 1750 NewCPV = ARMConstantPoolConstant:: 1751 Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId, 1752 ARMCP::CPBlockAddress, 4); 1753 else if (ACPV->isLSDA()) 1754 NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId, 1755 ARMCP::CPLSDA, 4); 1756 else if (ACPV->isMachineBasicBlock()) 1757 NewCPV = ARMConstantPoolMBB:: 1758 Create(MF.getFunction().getContext(), 1759 cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4); 1760 else 1761 llvm_unreachable("Unexpected ARM constantpool value type!!"); 1762 CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlign()); 1763 return PCLabelId; 1764 } 1765 1766 void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB, 1767 MachineBasicBlock::iterator I, 1768 Register DestReg, unsigned SubIdx, 1769 const MachineInstr &Orig, 1770 const TargetRegisterInfo &TRI) const { 1771 unsigned Opcode = Orig.getOpcode(); 1772 switch (Opcode) { 1773 default: { 1774 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig); 1775 MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI); 1776 MBB.insert(I, MI); 1777 break; 1778 } 1779 case ARM::tLDRpci_pic: 1780 case ARM::t2LDRpci_pic: { 1781 MachineFunction &MF = *MBB.getParent(); 1782 unsigned CPI = Orig.getOperand(1).getIndex(); 1783 unsigned PCLabelId = duplicateCPV(MF, CPI); 1784 BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg) 1785 .addConstantPoolIndex(CPI) 1786 .addImm(PCLabelId) 1787 .cloneMemRefs(Orig); 1788 break; 1789 } 1790 } 1791 } 1792 1793 MachineInstr & 1794 ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB, 1795 MachineBasicBlock::iterator InsertBefore, 1796 const MachineInstr &Orig) const { 1797 MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig); 1798 MachineBasicBlock::instr_iterator I = Cloned.getIterator(); 1799 for (;;) { 1800 switch (I->getOpcode()) { 1801 case ARM::tLDRpci_pic: 1802 case ARM::t2LDRpci_pic: { 1803 MachineFunction &MF = *MBB.getParent(); 1804 unsigned CPI = I->getOperand(1).getIndex(); 1805 unsigned PCLabelId = duplicateCPV(MF, CPI); 1806 I->getOperand(1).setIndex(CPI); 1807 I->getOperand(2).setImm(PCLabelId); 1808 break; 1809 } 1810 } 1811 if (!I->isBundledWithSucc()) 1812 break; 1813 ++I; 1814 } 1815 return Cloned; 1816 } 1817 1818 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0, 1819 const MachineInstr &MI1, 1820 const MachineRegisterInfo *MRI) const { 1821 unsigned Opcode = MI0.getOpcode(); 1822 if (Opcode == ARM::t2LDRpci || 1823 Opcode == ARM::t2LDRpci_pic || 1824 Opcode == ARM::tLDRpci || 1825 Opcode == ARM::tLDRpci_pic || 1826 Opcode == ARM::LDRLIT_ga_pcrel || 1827 Opcode == ARM::LDRLIT_ga_pcrel_ldr || 1828 Opcode == ARM::tLDRLIT_ga_pcrel || 1829 Opcode == ARM::MOV_ga_pcrel || 1830 Opcode == ARM::MOV_ga_pcrel_ldr || 1831 Opcode == ARM::t2MOV_ga_pcrel) { 1832 if (MI1.getOpcode() != Opcode) 1833 return false; 1834 if (MI0.getNumOperands() != MI1.getNumOperands()) 1835 return false; 1836 1837 const MachineOperand &MO0 = MI0.getOperand(1); 1838 const MachineOperand &MO1 = MI1.getOperand(1); 1839 if (MO0.getOffset() != MO1.getOffset()) 1840 return false; 1841 1842 if (Opcode == ARM::LDRLIT_ga_pcrel || 1843 Opcode == ARM::LDRLIT_ga_pcrel_ldr || 1844 Opcode == ARM::tLDRLIT_ga_pcrel || 1845 Opcode == ARM::MOV_ga_pcrel || 1846 Opcode == ARM::MOV_ga_pcrel_ldr || 1847 Opcode == ARM::t2MOV_ga_pcrel) 1848 // Ignore the PC labels. 1849 return MO0.getGlobal() == MO1.getGlobal(); 1850 1851 const MachineFunction *MF = MI0.getParent()->getParent(); 1852 const MachineConstantPool *MCP = MF->getConstantPool(); 1853 int CPI0 = MO0.getIndex(); 1854 int CPI1 = MO1.getIndex(); 1855 const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0]; 1856 const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1]; 1857 bool isARMCP0 = MCPE0.isMachineConstantPoolEntry(); 1858 bool isARMCP1 = MCPE1.isMachineConstantPoolEntry(); 1859 if (isARMCP0 && isARMCP1) { 1860 ARMConstantPoolValue *ACPV0 = 1861 static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal); 1862 ARMConstantPoolValue *ACPV1 = 1863 static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal); 1864 return ACPV0->hasSameValue(ACPV1); 1865 } else if (!isARMCP0 && !isARMCP1) { 1866 return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal; 1867 } 1868 return false; 1869 } else if (Opcode == ARM::PICLDR) { 1870 if (MI1.getOpcode() != Opcode) 1871 return false; 1872 if (MI0.getNumOperands() != MI1.getNumOperands()) 1873 return false; 1874 1875 Register Addr0 = MI0.getOperand(1).getReg(); 1876 Register Addr1 = MI1.getOperand(1).getReg(); 1877 if (Addr0 != Addr1) { 1878 if (!MRI || !Register::isVirtualRegister(Addr0) || 1879 !Register::isVirtualRegister(Addr1)) 1880 return false; 1881 1882 // This assumes SSA form. 1883 MachineInstr *Def0 = MRI->getVRegDef(Addr0); 1884 MachineInstr *Def1 = MRI->getVRegDef(Addr1); 1885 // Check if the loaded value, e.g. a constantpool of a global address, are 1886 // the same. 1887 if (!produceSameValue(*Def0, *Def1, MRI)) 1888 return false; 1889 } 1890 1891 for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) { 1892 // %12 = PICLDR %11, 0, 14, %noreg 1893 const MachineOperand &MO0 = MI0.getOperand(i); 1894 const MachineOperand &MO1 = MI1.getOperand(i); 1895 if (!MO0.isIdenticalTo(MO1)) 1896 return false; 1897 } 1898 return true; 1899 } 1900 1901 return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs); 1902 } 1903 1904 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to 1905 /// determine if two loads are loading from the same base address. It should 1906 /// only return true if the base pointers are the same and the only differences 1907 /// between the two addresses is the offset. It also returns the offsets by 1908 /// reference. 1909 /// 1910 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched 1911 /// is permanently disabled. 1912 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, 1913 int64_t &Offset1, 1914 int64_t &Offset2) const { 1915 // Don't worry about Thumb: just ARM and Thumb2. 1916 if (Subtarget.isThumb1Only()) return false; 1917 1918 if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode()) 1919 return false; 1920 1921 switch (Load1->getMachineOpcode()) { 1922 default: 1923 return false; 1924 case ARM::LDRi12: 1925 case ARM::LDRBi12: 1926 case ARM::LDRD: 1927 case ARM::LDRH: 1928 case ARM::LDRSB: 1929 case ARM::LDRSH: 1930 case ARM::VLDRD: 1931 case ARM::VLDRS: 1932 case ARM::t2LDRi8: 1933 case ARM::t2LDRBi8: 1934 case ARM::t2LDRDi8: 1935 case ARM::t2LDRSHi8: 1936 case ARM::t2LDRi12: 1937 case ARM::t2LDRBi12: 1938 case ARM::t2LDRSHi12: 1939 break; 1940 } 1941 1942 switch (Load2->getMachineOpcode()) { 1943 default: 1944 return false; 1945 case ARM::LDRi12: 1946 case ARM::LDRBi12: 1947 case ARM::LDRD: 1948 case ARM::LDRH: 1949 case ARM::LDRSB: 1950 case ARM::LDRSH: 1951 case ARM::VLDRD: 1952 case ARM::VLDRS: 1953 case ARM::t2LDRi8: 1954 case ARM::t2LDRBi8: 1955 case ARM::t2LDRSHi8: 1956 case ARM::t2LDRi12: 1957 case ARM::t2LDRBi12: 1958 case ARM::t2LDRSHi12: 1959 break; 1960 } 1961 1962 // Check if base addresses and chain operands match. 1963 if (Load1->getOperand(0) != Load2->getOperand(0) || 1964 Load1->getOperand(4) != Load2->getOperand(4)) 1965 return false; 1966 1967 // Index should be Reg0. 1968 if (Load1->getOperand(3) != Load2->getOperand(3)) 1969 return false; 1970 1971 // Determine the offsets. 1972 if (isa<ConstantSDNode>(Load1->getOperand(1)) && 1973 isa<ConstantSDNode>(Load2->getOperand(1))) { 1974 Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue(); 1975 Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue(); 1976 return true; 1977 } 1978 1979 return false; 1980 } 1981 1982 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to 1983 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should 1984 /// be scheduled togther. On some targets if two loads are loading from 1985 /// addresses in the same cache line, it's better if they are scheduled 1986 /// together. This function takes two integers that represent the load offsets 1987 /// from the common base address. It returns true if it decides it's desirable 1988 /// to schedule the two loads together. "NumLoads" is the number of loads that 1989 /// have already been scheduled after Load1. 1990 /// 1991 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched 1992 /// is permanently disabled. 1993 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2, 1994 int64_t Offset1, int64_t Offset2, 1995 unsigned NumLoads) const { 1996 // Don't worry about Thumb: just ARM and Thumb2. 1997 if (Subtarget.isThumb1Only()) return false; 1998 1999 assert(Offset2 > Offset1); 2000 2001 if ((Offset2 - Offset1) / 8 > 64) 2002 return false; 2003 2004 // Check if the machine opcodes are different. If they are different 2005 // then we consider them to not be of the same base address, 2006 // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12. 2007 // In this case, they are considered to be the same because they are different 2008 // encoding forms of the same basic instruction. 2009 if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) && 2010 !((Load1->getMachineOpcode() == ARM::t2LDRBi8 && 2011 Load2->getMachineOpcode() == ARM::t2LDRBi12) || 2012 (Load1->getMachineOpcode() == ARM::t2LDRBi12 && 2013 Load2->getMachineOpcode() == ARM::t2LDRBi8))) 2014 return false; // FIXME: overly conservative? 2015 2016 // Four loads in a row should be sufficient. 2017 if (NumLoads >= 3) 2018 return false; 2019 2020 return true; 2021 } 2022 2023 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI, 2024 const MachineBasicBlock *MBB, 2025 const MachineFunction &MF) const { 2026 // Debug info is never a scheduling boundary. It's necessary to be explicit 2027 // due to the special treatment of IT instructions below, otherwise a 2028 // dbg_value followed by an IT will result in the IT instruction being 2029 // considered a scheduling hazard, which is wrong. It should be the actual 2030 // instruction preceding the dbg_value instruction(s), just like it is 2031 // when debug info is not present. 2032 if (MI.isDebugInstr()) 2033 return false; 2034 2035 // Terminators and labels can't be scheduled around. 2036 if (MI.isTerminator() || MI.isPosition()) 2037 return true; 2038 2039 // INLINEASM_BR can jump to another block 2040 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) 2041 return true; 2042 2043 // Treat the start of the IT block as a scheduling boundary, but schedule 2044 // t2IT along with all instructions following it. 2045 // FIXME: This is a big hammer. But the alternative is to add all potential 2046 // true and anti dependencies to IT block instructions as implicit operands 2047 // to the t2IT instruction. The added compile time and complexity does not 2048 // seem worth it. 2049 MachineBasicBlock::const_iterator I = MI; 2050 // Make sure to skip any debug instructions 2051 while (++I != MBB->end() && I->isDebugInstr()) 2052 ; 2053 if (I != MBB->end() && I->getOpcode() == ARM::t2IT) 2054 return true; 2055 2056 // Don't attempt to schedule around any instruction that defines 2057 // a stack-oriented pointer, as it's unlikely to be profitable. This 2058 // saves compile time, because it doesn't require every single 2059 // stack slot reference to depend on the instruction that does the 2060 // modification. 2061 // Calls don't actually change the stack pointer, even if they have imp-defs. 2062 // No ARM calling conventions change the stack pointer. (X86 calling 2063 // conventions sometimes do). 2064 if (!MI.isCall() && MI.definesRegister(ARM::SP)) 2065 return true; 2066 2067 return false; 2068 } 2069 2070 bool ARMBaseInstrInfo:: 2071 isProfitableToIfCvt(MachineBasicBlock &MBB, 2072 unsigned NumCycles, unsigned ExtraPredCycles, 2073 BranchProbability Probability) const { 2074 if (!NumCycles) 2075 return false; 2076 2077 // If we are optimizing for size, see if the branch in the predecessor can be 2078 // lowered to cbn?z by the constant island lowering pass, and return false if 2079 // so. This results in a shorter instruction sequence. 2080 if (MBB.getParent()->getFunction().hasOptSize()) { 2081 MachineBasicBlock *Pred = *MBB.pred_begin(); 2082 if (!Pred->empty()) { 2083 MachineInstr *LastMI = &*Pred->rbegin(); 2084 if (LastMI->getOpcode() == ARM::t2Bcc) { 2085 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2086 MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI); 2087 if (CmpMI) 2088 return false; 2089 } 2090 } 2091 } 2092 return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles, 2093 MBB, 0, 0, Probability); 2094 } 2095 2096 bool ARMBaseInstrInfo:: 2097 isProfitableToIfCvt(MachineBasicBlock &TBB, 2098 unsigned TCycles, unsigned TExtra, 2099 MachineBasicBlock &FBB, 2100 unsigned FCycles, unsigned FExtra, 2101 BranchProbability Probability) const { 2102 if (!TCycles) 2103 return false; 2104 2105 // In thumb code we often end up trading one branch for a IT block, and 2106 // if we are cloning the instruction can increase code size. Prevent 2107 // blocks with multiple predecesors from being ifcvted to prevent this 2108 // cloning. 2109 if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) { 2110 if (TBB.pred_size() != 1 || FBB.pred_size() != 1) 2111 return false; 2112 } 2113 2114 // Attempt to estimate the relative costs of predication versus branching. 2115 // Here we scale up each component of UnpredCost to avoid precision issue when 2116 // scaling TCycles/FCycles by Probability. 2117 const unsigned ScalingUpFactor = 1024; 2118 2119 unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor; 2120 unsigned UnpredCost; 2121 if (!Subtarget.hasBranchPredictor()) { 2122 // When we don't have a branch predictor it's always cheaper to not take a 2123 // branch than take it, so we have to take that into account. 2124 unsigned NotTakenBranchCost = 1; 2125 unsigned TakenBranchCost = Subtarget.getMispredictionPenalty(); 2126 unsigned TUnpredCycles, FUnpredCycles; 2127 if (!FCycles) { 2128 // Triangle: TBB is the fallthrough 2129 TUnpredCycles = TCycles + NotTakenBranchCost; 2130 FUnpredCycles = TakenBranchCost; 2131 } else { 2132 // Diamond: TBB is the block that is branched to, FBB is the fallthrough 2133 TUnpredCycles = TCycles + TakenBranchCost; 2134 FUnpredCycles = FCycles + NotTakenBranchCost; 2135 // The branch at the end of FBB will disappear when it's predicated, so 2136 // discount it from PredCost. 2137 PredCost -= 1 * ScalingUpFactor; 2138 } 2139 // The total cost is the cost of each path scaled by their probabilites 2140 unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor); 2141 unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor); 2142 UnpredCost = TUnpredCost + FUnpredCost; 2143 // When predicating assume that the first IT can be folded away but later 2144 // ones cost one cycle each 2145 if (Subtarget.isThumb2() && TCycles + FCycles > 4) { 2146 PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor; 2147 } 2148 } else { 2149 unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor); 2150 unsigned FUnpredCost = 2151 Probability.getCompl().scale(FCycles * ScalingUpFactor); 2152 UnpredCost = TUnpredCost + FUnpredCost; 2153 UnpredCost += 1 * ScalingUpFactor; // The branch itself 2154 UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10; 2155 } 2156 2157 return PredCost <= UnpredCost; 2158 } 2159 2160 unsigned 2161 ARMBaseInstrInfo::extraSizeToPredicateInstructions(const MachineFunction &MF, 2162 unsigned NumInsts) const { 2163 // Thumb2 needs a 2-byte IT instruction to predicate up to 4 instructions. 2164 // ARM has a condition code field in every predicable instruction, using it 2165 // doesn't change code size. 2166 if (!Subtarget.isThumb2()) 2167 return 0; 2168 2169 // It's possible that the size of the IT is restricted to a single block. 2170 unsigned MaxInsts = Subtarget.restrictIT() ? 1 : 4; 2171 return divideCeil(NumInsts, MaxInsts) * 2; 2172 } 2173 2174 unsigned 2175 ARMBaseInstrInfo::predictBranchSizeForIfCvt(MachineInstr &MI) const { 2176 // If this branch is likely to be folded into the comparison to form a 2177 // CB(N)Z, then removing it won't reduce code size at all, because that will 2178 // just replace the CB(N)Z with a CMP. 2179 if (MI.getOpcode() == ARM::t2Bcc && 2180 findCMPToFoldIntoCBZ(&MI, &getRegisterInfo())) 2181 return 0; 2182 2183 unsigned Size = getInstSizeInBytes(MI); 2184 2185 // For Thumb2, all branches are 32-bit instructions during the if conversion 2186 // pass, but may be replaced with 16-bit instructions during size reduction. 2187 // Since the branches considered by if conversion tend to be forward branches 2188 // over small basic blocks, they are very likely to be in range for the 2189 // narrow instructions, so we assume the final code size will be half what it 2190 // currently is. 2191 if (Subtarget.isThumb2()) 2192 Size /= 2; 2193 2194 return Size; 2195 } 2196 2197 bool 2198 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB, 2199 MachineBasicBlock &FMBB) const { 2200 // Reduce false anti-dependencies to let the target's out-of-order execution 2201 // engine do its thing. 2202 return Subtarget.isProfitableToUnpredicate(); 2203 } 2204 2205 /// getInstrPredicate - If instruction is predicated, returns its predicate 2206 /// condition, otherwise returns AL. It also returns the condition code 2207 /// register by reference. 2208 ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI, 2209 Register &PredReg) { 2210 int PIdx = MI.findFirstPredOperandIdx(); 2211 if (PIdx == -1) { 2212 PredReg = 0; 2213 return ARMCC::AL; 2214 } 2215 2216 PredReg = MI.getOperand(PIdx+1).getReg(); 2217 return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm(); 2218 } 2219 2220 unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) { 2221 if (Opc == ARM::B) 2222 return ARM::Bcc; 2223 if (Opc == ARM::tB) 2224 return ARM::tBcc; 2225 if (Opc == ARM::t2B) 2226 return ARM::t2Bcc; 2227 2228 llvm_unreachable("Unknown unconditional branch opcode!"); 2229 } 2230 2231 MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI, 2232 bool NewMI, 2233 unsigned OpIdx1, 2234 unsigned OpIdx2) const { 2235 switch (MI.getOpcode()) { 2236 case ARM::MOVCCr: 2237 case ARM::t2MOVCCr: { 2238 // MOVCC can be commuted by inverting the condition. 2239 Register PredReg; 2240 ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg); 2241 // MOVCC AL can't be inverted. Shouldn't happen. 2242 if (CC == ARMCC::AL || PredReg != ARM::CPSR) 2243 return nullptr; 2244 MachineInstr *CommutedMI = 2245 TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 2246 if (!CommutedMI) 2247 return nullptr; 2248 // After swapping the MOVCC operands, also invert the condition. 2249 CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx()) 2250 .setImm(ARMCC::getOppositeCondition(CC)); 2251 return CommutedMI; 2252 } 2253 } 2254 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 2255 } 2256 2257 /// Identify instructions that can be folded into a MOVCC instruction, and 2258 /// return the defining instruction. 2259 MachineInstr * 2260 ARMBaseInstrInfo::canFoldIntoMOVCC(Register Reg, const MachineRegisterInfo &MRI, 2261 const TargetInstrInfo *TII) const { 2262 if (!Reg.isVirtual()) 2263 return nullptr; 2264 if (!MRI.hasOneNonDBGUse(Reg)) 2265 return nullptr; 2266 MachineInstr *MI = MRI.getVRegDef(Reg); 2267 if (!MI) 2268 return nullptr; 2269 // Check if MI can be predicated and folded into the MOVCC. 2270 if (!isPredicable(*MI)) 2271 return nullptr; 2272 // Check if MI has any non-dead defs or physreg uses. This also detects 2273 // predicated instructions which will be reading CPSR. 2274 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) { 2275 const MachineOperand &MO = MI->getOperand(i); 2276 // Reject frame index operands, PEI can't handle the predicated pseudos. 2277 if (MO.isFI() || MO.isCPI() || MO.isJTI()) 2278 return nullptr; 2279 if (!MO.isReg()) 2280 continue; 2281 // MI can't have any tied operands, that would conflict with predication. 2282 if (MO.isTied()) 2283 return nullptr; 2284 if (Register::isPhysicalRegister(MO.getReg())) 2285 return nullptr; 2286 if (MO.isDef() && !MO.isDead()) 2287 return nullptr; 2288 } 2289 bool DontMoveAcrossStores = true; 2290 if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores)) 2291 return nullptr; 2292 return MI; 2293 } 2294 2295 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI, 2296 SmallVectorImpl<MachineOperand> &Cond, 2297 unsigned &TrueOp, unsigned &FalseOp, 2298 bool &Optimizable) const { 2299 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) && 2300 "Unknown select instruction"); 2301 // MOVCC operands: 2302 // 0: Def. 2303 // 1: True use. 2304 // 2: False use. 2305 // 3: Condition code. 2306 // 4: CPSR use. 2307 TrueOp = 1; 2308 FalseOp = 2; 2309 Cond.push_back(MI.getOperand(3)); 2310 Cond.push_back(MI.getOperand(4)); 2311 // We can always fold a def. 2312 Optimizable = true; 2313 return false; 2314 } 2315 2316 MachineInstr * 2317 ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI, 2318 SmallPtrSetImpl<MachineInstr *> &SeenMIs, 2319 bool PreferFalse) const { 2320 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) && 2321 "Unknown select instruction"); 2322 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 2323 MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this); 2324 bool Invert = !DefMI; 2325 if (!DefMI) 2326 DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this); 2327 if (!DefMI) 2328 return nullptr; 2329 2330 // Find new register class to use. 2331 MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1); 2332 Register DestReg = MI.getOperand(0).getReg(); 2333 const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg()); 2334 if (!MRI.constrainRegClass(DestReg, PreviousClass)) 2335 return nullptr; 2336 2337 // Create a new predicated version of DefMI. 2338 // Rfalse is the first use. 2339 MachineInstrBuilder NewMI = 2340 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg); 2341 2342 // Copy all the DefMI operands, excluding its (null) predicate. 2343 const MCInstrDesc &DefDesc = DefMI->getDesc(); 2344 for (unsigned i = 1, e = DefDesc.getNumOperands(); 2345 i != e && !DefDesc.OpInfo[i].isPredicate(); ++i) 2346 NewMI.add(DefMI->getOperand(i)); 2347 2348 unsigned CondCode = MI.getOperand(3).getImm(); 2349 if (Invert) 2350 NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode))); 2351 else 2352 NewMI.addImm(CondCode); 2353 NewMI.add(MI.getOperand(4)); 2354 2355 // DefMI is not the -S version that sets CPSR, so add an optional %noreg. 2356 if (NewMI->hasOptionalDef()) 2357 NewMI.add(condCodeOp()); 2358 2359 // The output register value when the predicate is false is an implicit 2360 // register operand tied to the first def. 2361 // The tie makes the register allocator ensure the FalseReg is allocated the 2362 // same register as operand 0. 2363 FalseReg.setImplicit(); 2364 NewMI.add(FalseReg); 2365 NewMI->tieOperands(0, NewMI->getNumOperands() - 1); 2366 2367 // Update SeenMIs set: register newly created MI and erase removed DefMI. 2368 SeenMIs.insert(NewMI); 2369 SeenMIs.erase(DefMI); 2370 2371 // If MI is inside a loop, and DefMI is outside the loop, then kill flags on 2372 // DefMI would be invalid when tranferred inside the loop. Checking for a 2373 // loop is expensive, but at least remove kill flags if they are in different 2374 // BBs. 2375 if (DefMI->getParent() != MI.getParent()) 2376 NewMI->clearKillInfo(); 2377 2378 // The caller will erase MI, but not DefMI. 2379 DefMI->eraseFromParent(); 2380 return NewMI; 2381 } 2382 2383 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the 2384 /// instruction is encoded with an 'S' bit is determined by the optional CPSR 2385 /// def operand. 2386 /// 2387 /// This will go away once we can teach tblgen how to set the optional CPSR def 2388 /// operand itself. 2389 struct AddSubFlagsOpcodePair { 2390 uint16_t PseudoOpc; 2391 uint16_t MachineOpc; 2392 }; 2393 2394 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = { 2395 {ARM::ADDSri, ARM::ADDri}, 2396 {ARM::ADDSrr, ARM::ADDrr}, 2397 {ARM::ADDSrsi, ARM::ADDrsi}, 2398 {ARM::ADDSrsr, ARM::ADDrsr}, 2399 2400 {ARM::SUBSri, ARM::SUBri}, 2401 {ARM::SUBSrr, ARM::SUBrr}, 2402 {ARM::SUBSrsi, ARM::SUBrsi}, 2403 {ARM::SUBSrsr, ARM::SUBrsr}, 2404 2405 {ARM::RSBSri, ARM::RSBri}, 2406 {ARM::RSBSrsi, ARM::RSBrsi}, 2407 {ARM::RSBSrsr, ARM::RSBrsr}, 2408 2409 {ARM::tADDSi3, ARM::tADDi3}, 2410 {ARM::tADDSi8, ARM::tADDi8}, 2411 {ARM::tADDSrr, ARM::tADDrr}, 2412 {ARM::tADCS, ARM::tADC}, 2413 2414 {ARM::tSUBSi3, ARM::tSUBi3}, 2415 {ARM::tSUBSi8, ARM::tSUBi8}, 2416 {ARM::tSUBSrr, ARM::tSUBrr}, 2417 {ARM::tSBCS, ARM::tSBC}, 2418 {ARM::tRSBS, ARM::tRSB}, 2419 {ARM::tLSLSri, ARM::tLSLri}, 2420 2421 {ARM::t2ADDSri, ARM::t2ADDri}, 2422 {ARM::t2ADDSrr, ARM::t2ADDrr}, 2423 {ARM::t2ADDSrs, ARM::t2ADDrs}, 2424 2425 {ARM::t2SUBSri, ARM::t2SUBri}, 2426 {ARM::t2SUBSrr, ARM::t2SUBrr}, 2427 {ARM::t2SUBSrs, ARM::t2SUBrs}, 2428 2429 {ARM::t2RSBSri, ARM::t2RSBri}, 2430 {ARM::t2RSBSrs, ARM::t2RSBrs}, 2431 }; 2432 2433 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) { 2434 for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i) 2435 if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc) 2436 return AddSubFlagsOpcodeMap[i].MachineOpc; 2437 return 0; 2438 } 2439 2440 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB, 2441 MachineBasicBlock::iterator &MBBI, 2442 const DebugLoc &dl, Register DestReg, 2443 Register BaseReg, int NumBytes, 2444 ARMCC::CondCodes Pred, Register PredReg, 2445 const ARMBaseInstrInfo &TII, 2446 unsigned MIFlags) { 2447 if (NumBytes == 0 && DestReg != BaseReg) { 2448 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg) 2449 .addReg(BaseReg, RegState::Kill) 2450 .add(predOps(Pred, PredReg)) 2451 .add(condCodeOp()) 2452 .setMIFlags(MIFlags); 2453 return; 2454 } 2455 2456 bool isSub = NumBytes < 0; 2457 if (isSub) NumBytes = -NumBytes; 2458 2459 while (NumBytes) { 2460 unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes); 2461 unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt); 2462 assert(ThisVal && "Didn't extract field correctly"); 2463 2464 // We will handle these bits from offset, clear them. 2465 NumBytes &= ~ThisVal; 2466 2467 assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?"); 2468 2469 // Build the new ADD / SUB. 2470 unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri; 2471 BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg) 2472 .addReg(BaseReg, RegState::Kill) 2473 .addImm(ThisVal) 2474 .add(predOps(Pred, PredReg)) 2475 .add(condCodeOp()) 2476 .setMIFlags(MIFlags); 2477 BaseReg = DestReg; 2478 } 2479 } 2480 2481 bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget, 2482 MachineFunction &MF, MachineInstr *MI, 2483 unsigned NumBytes) { 2484 // This optimisation potentially adds lots of load and store 2485 // micro-operations, it's only really a great benefit to code-size. 2486 if (!Subtarget.hasMinSize()) 2487 return false; 2488 2489 // If only one register is pushed/popped, LLVM can use an LDR/STR 2490 // instead. We can't modify those so make sure we're dealing with an 2491 // instruction we understand. 2492 bool IsPop = isPopOpcode(MI->getOpcode()); 2493 bool IsPush = isPushOpcode(MI->getOpcode()); 2494 if (!IsPush && !IsPop) 2495 return false; 2496 2497 bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD || 2498 MI->getOpcode() == ARM::VLDMDIA_UPD; 2499 bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH || 2500 MI->getOpcode() == ARM::tPOP || 2501 MI->getOpcode() == ARM::tPOP_RET; 2502 2503 assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP && 2504 MI->getOperand(1).getReg() == ARM::SP)) && 2505 "trying to fold sp update into non-sp-updating push/pop"); 2506 2507 // The VFP push & pop act on D-registers, so we can only fold an adjustment 2508 // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try 2509 // if this is violated. 2510 if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0) 2511 return false; 2512 2513 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+ 2514 // pred) so the list starts at 4. Thumb1 starts after the predicate. 2515 int RegListIdx = IsT1PushPop ? 2 : 4; 2516 2517 // Calculate the space we'll need in terms of registers. 2518 unsigned RegsNeeded; 2519 const TargetRegisterClass *RegClass; 2520 if (IsVFPPushPop) { 2521 RegsNeeded = NumBytes / 8; 2522 RegClass = &ARM::DPRRegClass; 2523 } else { 2524 RegsNeeded = NumBytes / 4; 2525 RegClass = &ARM::GPRRegClass; 2526 } 2527 2528 // We're going to have to strip all list operands off before 2529 // re-adding them since the order matters, so save the existing ones 2530 // for later. 2531 SmallVector<MachineOperand, 4> RegList; 2532 2533 // We're also going to need the first register transferred by this 2534 // instruction, which won't necessarily be the first register in the list. 2535 unsigned FirstRegEnc = -1; 2536 2537 const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo(); 2538 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) { 2539 MachineOperand &MO = MI->getOperand(i); 2540 RegList.push_back(MO); 2541 2542 if (MO.isReg() && !MO.isImplicit() && 2543 TRI->getEncodingValue(MO.getReg()) < FirstRegEnc) 2544 FirstRegEnc = TRI->getEncodingValue(MO.getReg()); 2545 } 2546 2547 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF); 2548 2549 // Now try to find enough space in the reglist to allocate NumBytes. 2550 for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded; 2551 --CurRegEnc) { 2552 unsigned CurReg = RegClass->getRegister(CurRegEnc); 2553 if (IsT1PushPop && CurRegEnc > TRI->getEncodingValue(ARM::R7)) 2554 continue; 2555 if (!IsPop) { 2556 // Pushing any register is completely harmless, mark the register involved 2557 // as undef since we don't care about its value and must not restore it 2558 // during stack unwinding. 2559 RegList.push_back(MachineOperand::CreateReg(CurReg, false, false, 2560 false, false, true)); 2561 --RegsNeeded; 2562 continue; 2563 } 2564 2565 // However, we can only pop an extra register if it's not live. For 2566 // registers live within the function we might clobber a return value 2567 // register; the other way a register can be live here is if it's 2568 // callee-saved. 2569 if (isCalleeSavedRegister(CurReg, CSRegs) || 2570 MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) != 2571 MachineBasicBlock::LQR_Dead) { 2572 // VFP pops don't allow holes in the register list, so any skip is fatal 2573 // for our transformation. GPR pops do, so we should just keep looking. 2574 if (IsVFPPushPop) 2575 return false; 2576 else 2577 continue; 2578 } 2579 2580 // Mark the unimportant registers as <def,dead> in the POP. 2581 RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false, 2582 true)); 2583 --RegsNeeded; 2584 } 2585 2586 if (RegsNeeded > 0) 2587 return false; 2588 2589 // Finally we know we can profitably perform the optimisation so go 2590 // ahead: strip all existing registers off and add them back again 2591 // in the right order. 2592 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) 2593 MI->RemoveOperand(i); 2594 2595 // Add the complete list back in. 2596 MachineInstrBuilder MIB(MF, &*MI); 2597 for (int i = RegList.size() - 1; i >= 0; --i) 2598 MIB.add(RegList[i]); 2599 2600 return true; 2601 } 2602 2603 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx, 2604 Register FrameReg, int &Offset, 2605 const ARMBaseInstrInfo &TII) { 2606 unsigned Opcode = MI.getOpcode(); 2607 const MCInstrDesc &Desc = MI.getDesc(); 2608 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask); 2609 bool isSub = false; 2610 2611 // Memory operands in inline assembly always use AddrMode2. 2612 if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR) 2613 AddrMode = ARMII::AddrMode2; 2614 2615 if (Opcode == ARM::ADDri) { 2616 Offset += MI.getOperand(FrameRegIdx+1).getImm(); 2617 if (Offset == 0) { 2618 // Turn it into a move. 2619 MI.setDesc(TII.get(ARM::MOVr)); 2620 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); 2621 MI.RemoveOperand(FrameRegIdx+1); 2622 Offset = 0; 2623 return true; 2624 } else if (Offset < 0) { 2625 Offset = -Offset; 2626 isSub = true; 2627 MI.setDesc(TII.get(ARM::SUBri)); 2628 } 2629 2630 // Common case: small offset, fits into instruction. 2631 if (ARM_AM::getSOImmVal(Offset) != -1) { 2632 // Replace the FrameIndex with sp / fp 2633 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); 2634 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset); 2635 Offset = 0; 2636 return true; 2637 } 2638 2639 // Otherwise, pull as much of the immedidate into this ADDri/SUBri 2640 // as possible. 2641 unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset); 2642 unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt); 2643 2644 // We will handle these bits from offset, clear them. 2645 Offset &= ~ThisImmVal; 2646 2647 // Get the properly encoded SOImmVal field. 2648 assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 && 2649 "Bit extraction didn't work?"); 2650 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal); 2651 } else { 2652 unsigned ImmIdx = 0; 2653 int InstrOffs = 0; 2654 unsigned NumBits = 0; 2655 unsigned Scale = 1; 2656 switch (AddrMode) { 2657 case ARMII::AddrMode_i12: 2658 ImmIdx = FrameRegIdx + 1; 2659 InstrOffs = MI.getOperand(ImmIdx).getImm(); 2660 NumBits = 12; 2661 break; 2662 case ARMII::AddrMode2: 2663 ImmIdx = FrameRegIdx+2; 2664 InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm()); 2665 if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2666 InstrOffs *= -1; 2667 NumBits = 12; 2668 break; 2669 case ARMII::AddrMode3: 2670 ImmIdx = FrameRegIdx+2; 2671 InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm()); 2672 if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2673 InstrOffs *= -1; 2674 NumBits = 8; 2675 break; 2676 case ARMII::AddrMode4: 2677 case ARMII::AddrMode6: 2678 // Can't fold any offset even if it's zero. 2679 return false; 2680 case ARMII::AddrMode5: 2681 ImmIdx = FrameRegIdx+1; 2682 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm()); 2683 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2684 InstrOffs *= -1; 2685 NumBits = 8; 2686 Scale = 4; 2687 break; 2688 case ARMII::AddrMode5FP16: 2689 ImmIdx = FrameRegIdx+1; 2690 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm()); 2691 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2692 InstrOffs *= -1; 2693 NumBits = 8; 2694 Scale = 2; 2695 break; 2696 case ARMII::AddrModeT2_i7: 2697 case ARMII::AddrModeT2_i7s2: 2698 case ARMII::AddrModeT2_i7s4: 2699 ImmIdx = FrameRegIdx+1; 2700 InstrOffs = MI.getOperand(ImmIdx).getImm(); 2701 NumBits = 7; 2702 Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 : 2703 AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1); 2704 break; 2705 default: 2706 llvm_unreachable("Unsupported addressing mode!"); 2707 } 2708 2709 Offset += InstrOffs * Scale; 2710 assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!"); 2711 if (Offset < 0) { 2712 Offset = -Offset; 2713 isSub = true; 2714 } 2715 2716 // Attempt to fold address comp. if opcode has offset bits 2717 if (NumBits > 0) { 2718 // Common case: small offset, fits into instruction. 2719 MachineOperand &ImmOp = MI.getOperand(ImmIdx); 2720 int ImmedOffset = Offset / Scale; 2721 unsigned Mask = (1 << NumBits) - 1; 2722 if ((unsigned)Offset <= Mask * Scale) { 2723 // Replace the FrameIndex with sp 2724 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); 2725 // FIXME: When addrmode2 goes away, this will simplify (like the 2726 // T2 version), as the LDR.i12 versions don't need the encoding 2727 // tricks for the offset value. 2728 if (isSub) { 2729 if (AddrMode == ARMII::AddrMode_i12) 2730 ImmedOffset = -ImmedOffset; 2731 else 2732 ImmedOffset |= 1 << NumBits; 2733 } 2734 ImmOp.ChangeToImmediate(ImmedOffset); 2735 Offset = 0; 2736 return true; 2737 } 2738 2739 // Otherwise, it didn't fit. Pull in what we can to simplify the immed. 2740 ImmedOffset = ImmedOffset & Mask; 2741 if (isSub) { 2742 if (AddrMode == ARMII::AddrMode_i12) 2743 ImmedOffset = -ImmedOffset; 2744 else 2745 ImmedOffset |= 1 << NumBits; 2746 } 2747 ImmOp.ChangeToImmediate(ImmedOffset); 2748 Offset &= ~(Mask*Scale); 2749 } 2750 } 2751 2752 Offset = (isSub) ? -Offset : Offset; 2753 return Offset == 0; 2754 } 2755 2756 /// analyzeCompare - For a comparison instruction, return the source registers 2757 /// in SrcReg and SrcReg2 if having two register operands, and the value it 2758 /// compares against in CmpValue. Return true if the comparison instruction 2759 /// can be analyzed. 2760 bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg, 2761 Register &SrcReg2, int &CmpMask, 2762 int &CmpValue) const { 2763 switch (MI.getOpcode()) { 2764 default: break; 2765 case ARM::CMPri: 2766 case ARM::t2CMPri: 2767 case ARM::tCMPi8: 2768 SrcReg = MI.getOperand(0).getReg(); 2769 SrcReg2 = 0; 2770 CmpMask = ~0; 2771 CmpValue = MI.getOperand(1).getImm(); 2772 return true; 2773 case ARM::CMPrr: 2774 case ARM::t2CMPrr: 2775 case ARM::tCMPr: 2776 SrcReg = MI.getOperand(0).getReg(); 2777 SrcReg2 = MI.getOperand(1).getReg(); 2778 CmpMask = ~0; 2779 CmpValue = 0; 2780 return true; 2781 case ARM::TSTri: 2782 case ARM::t2TSTri: 2783 SrcReg = MI.getOperand(0).getReg(); 2784 SrcReg2 = 0; 2785 CmpMask = MI.getOperand(1).getImm(); 2786 CmpValue = 0; 2787 return true; 2788 } 2789 2790 return false; 2791 } 2792 2793 /// isSuitableForMask - Identify a suitable 'and' instruction that 2794 /// operates on the given source register and applies the same mask 2795 /// as a 'tst' instruction. Provide a limited look-through for copies. 2796 /// When successful, MI will hold the found instruction. 2797 static bool isSuitableForMask(MachineInstr *&MI, Register SrcReg, 2798 int CmpMask, bool CommonUse) { 2799 switch (MI->getOpcode()) { 2800 case ARM::ANDri: 2801 case ARM::t2ANDri: 2802 if (CmpMask != MI->getOperand(2).getImm()) 2803 return false; 2804 if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg()) 2805 return true; 2806 break; 2807 } 2808 2809 return false; 2810 } 2811 2812 /// getCmpToAddCondition - assume the flags are set by CMP(a,b), return 2813 /// the condition code if we modify the instructions such that flags are 2814 /// set by ADD(a,b,X). 2815 inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) { 2816 switch (CC) { 2817 default: return ARMCC::AL; 2818 case ARMCC::HS: return ARMCC::LO; 2819 case ARMCC::LO: return ARMCC::HS; 2820 case ARMCC::VS: return ARMCC::VS; 2821 case ARMCC::VC: return ARMCC::VC; 2822 } 2823 } 2824 2825 /// isRedundantFlagInstr - check whether the first instruction, whose only 2826 /// purpose is to update flags, can be made redundant. 2827 /// CMPrr can be made redundant by SUBrr if the operands are the same. 2828 /// CMPri can be made redundant by SUBri if the operands are the same. 2829 /// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X). 2830 /// This function can be extended later on. 2831 inline static bool isRedundantFlagInstr(const MachineInstr *CmpI, 2832 Register SrcReg, Register SrcReg2, 2833 int ImmValue, const MachineInstr *OI, 2834 bool &IsThumb1) { 2835 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) && 2836 (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) && 2837 ((OI->getOperand(1).getReg() == SrcReg && 2838 OI->getOperand(2).getReg() == SrcReg2) || 2839 (OI->getOperand(1).getReg() == SrcReg2 && 2840 OI->getOperand(2).getReg() == SrcReg))) { 2841 IsThumb1 = false; 2842 return true; 2843 } 2844 2845 if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr && 2846 ((OI->getOperand(2).getReg() == SrcReg && 2847 OI->getOperand(3).getReg() == SrcReg2) || 2848 (OI->getOperand(2).getReg() == SrcReg2 && 2849 OI->getOperand(3).getReg() == SrcReg))) { 2850 IsThumb1 = true; 2851 return true; 2852 } 2853 2854 if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) && 2855 (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) && 2856 OI->getOperand(1).getReg() == SrcReg && 2857 OI->getOperand(2).getImm() == ImmValue) { 2858 IsThumb1 = false; 2859 return true; 2860 } 2861 2862 if (CmpI->getOpcode() == ARM::tCMPi8 && 2863 (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) && 2864 OI->getOperand(2).getReg() == SrcReg && 2865 OI->getOperand(3).getImm() == ImmValue) { 2866 IsThumb1 = true; 2867 return true; 2868 } 2869 2870 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) && 2871 (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr || 2872 OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) && 2873 OI->getOperand(0).isReg() && OI->getOperand(1).isReg() && 2874 OI->getOperand(0).getReg() == SrcReg && 2875 OI->getOperand(1).getReg() == SrcReg2) { 2876 IsThumb1 = false; 2877 return true; 2878 } 2879 2880 if (CmpI->getOpcode() == ARM::tCMPr && 2881 (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 || 2882 OI->getOpcode() == ARM::tADDrr) && 2883 OI->getOperand(0).getReg() == SrcReg && 2884 OI->getOperand(2).getReg() == SrcReg2) { 2885 IsThumb1 = true; 2886 return true; 2887 } 2888 2889 return false; 2890 } 2891 2892 static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) { 2893 switch (MI->getOpcode()) { 2894 default: return false; 2895 case ARM::tLSLri: 2896 case ARM::tLSRri: 2897 case ARM::tLSLrr: 2898 case ARM::tLSRrr: 2899 case ARM::tSUBrr: 2900 case ARM::tADDrr: 2901 case ARM::tADDi3: 2902 case ARM::tADDi8: 2903 case ARM::tSUBi3: 2904 case ARM::tSUBi8: 2905 case ARM::tMUL: 2906 case ARM::tADC: 2907 case ARM::tSBC: 2908 case ARM::tRSB: 2909 case ARM::tAND: 2910 case ARM::tORR: 2911 case ARM::tEOR: 2912 case ARM::tBIC: 2913 case ARM::tMVN: 2914 case ARM::tASRri: 2915 case ARM::tASRrr: 2916 case ARM::tROR: 2917 IsThumb1 = true; 2918 LLVM_FALLTHROUGH; 2919 case ARM::RSBrr: 2920 case ARM::RSBri: 2921 case ARM::RSCrr: 2922 case ARM::RSCri: 2923 case ARM::ADDrr: 2924 case ARM::ADDri: 2925 case ARM::ADCrr: 2926 case ARM::ADCri: 2927 case ARM::SUBrr: 2928 case ARM::SUBri: 2929 case ARM::SBCrr: 2930 case ARM::SBCri: 2931 case ARM::t2RSBri: 2932 case ARM::t2ADDrr: 2933 case ARM::t2ADDri: 2934 case ARM::t2ADCrr: 2935 case ARM::t2ADCri: 2936 case ARM::t2SUBrr: 2937 case ARM::t2SUBri: 2938 case ARM::t2SBCrr: 2939 case ARM::t2SBCri: 2940 case ARM::ANDrr: 2941 case ARM::ANDri: 2942 case ARM::t2ANDrr: 2943 case ARM::t2ANDri: 2944 case ARM::ORRrr: 2945 case ARM::ORRri: 2946 case ARM::t2ORRrr: 2947 case ARM::t2ORRri: 2948 case ARM::EORrr: 2949 case ARM::EORri: 2950 case ARM::t2EORrr: 2951 case ARM::t2EORri: 2952 case ARM::t2LSRri: 2953 case ARM::t2LSRrr: 2954 case ARM::t2LSLri: 2955 case ARM::t2LSLrr: 2956 return true; 2957 } 2958 } 2959 2960 /// optimizeCompareInstr - Convert the instruction supplying the argument to the 2961 /// comparison into one that sets the zero bit in the flags register; 2962 /// Remove a redundant Compare instruction if an earlier instruction can set the 2963 /// flags in the same way as Compare. 2964 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two 2965 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the 2966 /// condition code of instructions which use the flags. 2967 bool ARMBaseInstrInfo::optimizeCompareInstr( 2968 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int CmpMask, 2969 int CmpValue, const MachineRegisterInfo *MRI) const { 2970 // Get the unique definition of SrcReg. 2971 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg); 2972 if (!MI) return false; 2973 2974 // Masked compares sometimes use the same register as the corresponding 'and'. 2975 if (CmpMask != ~0) { 2976 if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) { 2977 MI = nullptr; 2978 for (MachineRegisterInfo::use_instr_iterator 2979 UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end(); 2980 UI != UE; ++UI) { 2981 if (UI->getParent() != CmpInstr.getParent()) 2982 continue; 2983 MachineInstr *PotentialAND = &*UI; 2984 if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) || 2985 isPredicated(*PotentialAND)) 2986 continue; 2987 MI = PotentialAND; 2988 break; 2989 } 2990 if (!MI) return false; 2991 } 2992 } 2993 2994 // Get ready to iterate backward from CmpInstr. 2995 MachineBasicBlock::iterator I = CmpInstr, E = MI, 2996 B = CmpInstr.getParent()->begin(); 2997 2998 // Early exit if CmpInstr is at the beginning of the BB. 2999 if (I == B) return false; 3000 3001 // There are two possible candidates which can be changed to set CPSR: 3002 // One is MI, the other is a SUB or ADD instruction. 3003 // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or 3004 // ADDr[ri](r1, r2, X). 3005 // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue). 3006 MachineInstr *SubAdd = nullptr; 3007 if (SrcReg2 != 0) 3008 // MI is not a candidate for CMPrr. 3009 MI = nullptr; 3010 else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) { 3011 // Conservatively refuse to convert an instruction which isn't in the same 3012 // BB as the comparison. 3013 // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate. 3014 // Thus we cannot return here. 3015 if (CmpInstr.getOpcode() == ARM::CMPri || 3016 CmpInstr.getOpcode() == ARM::t2CMPri || 3017 CmpInstr.getOpcode() == ARM::tCMPi8) 3018 MI = nullptr; 3019 else 3020 return false; 3021 } 3022 3023 bool IsThumb1 = false; 3024 if (MI && !isOptimizeCompareCandidate(MI, IsThumb1)) 3025 return false; 3026 3027 // We also want to do this peephole for cases like this: if (a*b == 0), 3028 // and optimise away the CMP instruction from the generated code sequence: 3029 // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values 3030 // resulting from the select instruction, but these MOVS instructions for 3031 // Thumb1 (V6M) are flag setting and are thus preventing this optimisation. 3032 // However, if we only have MOVS instructions in between the CMP and the 3033 // other instruction (the MULS in this example), then the CPSR is dead so we 3034 // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this 3035 // reordering and then continue the analysis hoping we can eliminate the 3036 // CMP. This peephole works on the vregs, so is still in SSA form. As a 3037 // consequence, the movs won't redefine/kill the MUL operands which would 3038 // make this reordering illegal. 3039 const TargetRegisterInfo *TRI = &getRegisterInfo(); 3040 if (MI && IsThumb1) { 3041 --I; 3042 if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) { 3043 bool CanReorder = true; 3044 for (; I != E; --I) { 3045 if (I->getOpcode() != ARM::tMOVi8) { 3046 CanReorder = false; 3047 break; 3048 } 3049 } 3050 if (CanReorder) { 3051 MI = MI->removeFromParent(); 3052 E = CmpInstr; 3053 CmpInstr.getParent()->insert(E, MI); 3054 } 3055 } 3056 I = CmpInstr; 3057 E = MI; 3058 } 3059 3060 // Check that CPSR isn't set between the comparison instruction and the one we 3061 // want to change. At the same time, search for SubAdd. 3062 bool SubAddIsThumb1 = false; 3063 do { 3064 const MachineInstr &Instr = *--I; 3065 3066 // Check whether CmpInstr can be made redundant by the current instruction. 3067 if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr, 3068 SubAddIsThumb1)) { 3069 SubAdd = &*I; 3070 break; 3071 } 3072 3073 // Allow E (which was initially MI) to be SubAdd but do not search before E. 3074 if (I == E) 3075 break; 3076 3077 if (Instr.modifiesRegister(ARM::CPSR, TRI) || 3078 Instr.readsRegister(ARM::CPSR, TRI)) 3079 // This instruction modifies or uses CPSR after the one we want to 3080 // change. We can't do this transformation. 3081 return false; 3082 3083 if (I == B) { 3084 // In some cases, we scan the use-list of an instruction for an AND; 3085 // that AND is in the same BB, but may not be scheduled before the 3086 // corresponding TST. In that case, bail out. 3087 // 3088 // FIXME: We could try to reschedule the AND. 3089 return false; 3090 } 3091 } while (true); 3092 3093 // Return false if no candidates exist. 3094 if (!MI && !SubAdd) 3095 return false; 3096 3097 // If we found a SubAdd, use it as it will be closer to the CMP 3098 if (SubAdd) { 3099 MI = SubAdd; 3100 IsThumb1 = SubAddIsThumb1; 3101 } 3102 3103 // We can't use a predicated instruction - it doesn't always write the flags. 3104 if (isPredicated(*MI)) 3105 return false; 3106 3107 // Scan forward for the use of CPSR 3108 // When checking against MI: if it's a conditional code that requires 3109 // checking of the V bit or C bit, then this is not safe to do. 3110 // It is safe to remove CmpInstr if CPSR is redefined or killed. 3111 // If we are done with the basic block, we need to check whether CPSR is 3112 // live-out. 3113 SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4> 3114 OperandsToUpdate; 3115 bool isSafe = false; 3116 I = CmpInstr; 3117 E = CmpInstr.getParent()->end(); 3118 while (!isSafe && ++I != E) { 3119 const MachineInstr &Instr = *I; 3120 for (unsigned IO = 0, EO = Instr.getNumOperands(); 3121 !isSafe && IO != EO; ++IO) { 3122 const MachineOperand &MO = Instr.getOperand(IO); 3123 if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) { 3124 isSafe = true; 3125 break; 3126 } 3127 if (!MO.isReg() || MO.getReg() != ARM::CPSR) 3128 continue; 3129 if (MO.isDef()) { 3130 isSafe = true; 3131 break; 3132 } 3133 // Condition code is after the operand before CPSR except for VSELs. 3134 ARMCC::CondCodes CC; 3135 bool IsInstrVSel = true; 3136 switch (Instr.getOpcode()) { 3137 default: 3138 IsInstrVSel = false; 3139 CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm(); 3140 break; 3141 case ARM::VSELEQD: 3142 case ARM::VSELEQS: 3143 case ARM::VSELEQH: 3144 CC = ARMCC::EQ; 3145 break; 3146 case ARM::VSELGTD: 3147 case ARM::VSELGTS: 3148 case ARM::VSELGTH: 3149 CC = ARMCC::GT; 3150 break; 3151 case ARM::VSELGED: 3152 case ARM::VSELGES: 3153 case ARM::VSELGEH: 3154 CC = ARMCC::GE; 3155 break; 3156 case ARM::VSELVSD: 3157 case ARM::VSELVSS: 3158 case ARM::VSELVSH: 3159 CC = ARMCC::VS; 3160 break; 3161 } 3162 3163 if (SubAdd) { 3164 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based 3165 // on CMP needs to be updated to be based on SUB. 3166 // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also 3167 // needs to be modified. 3168 // Push the condition code operands to OperandsToUpdate. 3169 // If it is safe to remove CmpInstr, the condition code of these 3170 // operands will be modified. 3171 unsigned Opc = SubAdd->getOpcode(); 3172 bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr || 3173 Opc == ARM::SUBri || Opc == ARM::t2SUBri || 3174 Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 || 3175 Opc == ARM::tSUBi8; 3176 unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2; 3177 if (!IsSub || 3178 (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 && 3179 SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) { 3180 // VSel doesn't support condition code update. 3181 if (IsInstrVSel) 3182 return false; 3183 // Ensure we can swap the condition. 3184 ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC)); 3185 if (NewCC == ARMCC::AL) 3186 return false; 3187 OperandsToUpdate.push_back( 3188 std::make_pair(&((*I).getOperand(IO - 1)), NewCC)); 3189 } 3190 } else { 3191 // No SubAdd, so this is x = <op> y, z; cmp x, 0. 3192 switch (CC) { 3193 case ARMCC::EQ: // Z 3194 case ARMCC::NE: // Z 3195 case ARMCC::MI: // N 3196 case ARMCC::PL: // N 3197 case ARMCC::AL: // none 3198 // CPSR can be used multiple times, we should continue. 3199 break; 3200 case ARMCC::HS: // C 3201 case ARMCC::LO: // C 3202 case ARMCC::VS: // V 3203 case ARMCC::VC: // V 3204 case ARMCC::HI: // C Z 3205 case ARMCC::LS: // C Z 3206 case ARMCC::GE: // N V 3207 case ARMCC::LT: // N V 3208 case ARMCC::GT: // Z N V 3209 case ARMCC::LE: // Z N V 3210 // The instruction uses the V bit or C bit which is not safe. 3211 return false; 3212 } 3213 } 3214 } 3215 } 3216 3217 // If CPSR is not killed nor re-defined, we should check whether it is 3218 // live-out. If it is live-out, do not optimize. 3219 if (!isSafe) { 3220 MachineBasicBlock *MBB = CmpInstr.getParent(); 3221 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), 3222 SE = MBB->succ_end(); SI != SE; ++SI) 3223 if ((*SI)->isLiveIn(ARM::CPSR)) 3224 return false; 3225 } 3226 3227 // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always 3228 // set CPSR so this is represented as an explicit output) 3229 if (!IsThumb1) { 3230 MI->getOperand(5).setReg(ARM::CPSR); 3231 MI->getOperand(5).setIsDef(true); 3232 } 3233 assert(!isPredicated(*MI) && "Can't use flags from predicated instruction"); 3234 CmpInstr.eraseFromParent(); 3235 3236 // Modify the condition code of operands in OperandsToUpdate. 3237 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to 3238 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc. 3239 for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++) 3240 OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second); 3241 3242 MI->clearRegisterDeads(ARM::CPSR); 3243 3244 return true; 3245 } 3246 3247 bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const { 3248 // Do not sink MI if it might be used to optimize a redundant compare. 3249 // We heuristically only look at the instruction immediately following MI to 3250 // avoid potentially searching the entire basic block. 3251 if (isPredicated(MI)) 3252 return true; 3253 MachineBasicBlock::const_iterator Next = &MI; 3254 ++Next; 3255 Register SrcReg, SrcReg2; 3256 int CmpMask, CmpValue; 3257 bool IsThumb1; 3258 if (Next != MI.getParent()->end() && 3259 analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) && 3260 isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1)) 3261 return false; 3262 return true; 3263 } 3264 3265 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, 3266 Register Reg, 3267 MachineRegisterInfo *MRI) const { 3268 // Fold large immediates into add, sub, or, xor. 3269 unsigned DefOpc = DefMI.getOpcode(); 3270 if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm) 3271 return false; 3272 if (!DefMI.getOperand(1).isImm()) 3273 // Could be t2MOVi32imm @xx 3274 return false; 3275 3276 if (!MRI->hasOneNonDBGUse(Reg)) 3277 return false; 3278 3279 const MCInstrDesc &DefMCID = DefMI.getDesc(); 3280 if (DefMCID.hasOptionalDef()) { 3281 unsigned NumOps = DefMCID.getNumOperands(); 3282 const MachineOperand &MO = DefMI.getOperand(NumOps - 1); 3283 if (MO.getReg() == ARM::CPSR && !MO.isDead()) 3284 // If DefMI defines CPSR and it is not dead, it's obviously not safe 3285 // to delete DefMI. 3286 return false; 3287 } 3288 3289 const MCInstrDesc &UseMCID = UseMI.getDesc(); 3290 if (UseMCID.hasOptionalDef()) { 3291 unsigned NumOps = UseMCID.getNumOperands(); 3292 if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR) 3293 // If the instruction sets the flag, do not attempt this optimization 3294 // since it may change the semantics of the code. 3295 return false; 3296 } 3297 3298 unsigned UseOpc = UseMI.getOpcode(); 3299 unsigned NewUseOpc = 0; 3300 uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm(); 3301 uint32_t SOImmValV1 = 0, SOImmValV2 = 0; 3302 bool Commute = false; 3303 switch (UseOpc) { 3304 default: return false; 3305 case ARM::SUBrr: 3306 case ARM::ADDrr: 3307 case ARM::ORRrr: 3308 case ARM::EORrr: 3309 case ARM::t2SUBrr: 3310 case ARM::t2ADDrr: 3311 case ARM::t2ORRrr: 3312 case ARM::t2EORrr: { 3313 Commute = UseMI.getOperand(2).getReg() != Reg; 3314 switch (UseOpc) { 3315 default: break; 3316 case ARM::ADDrr: 3317 case ARM::SUBrr: 3318 if (UseOpc == ARM::SUBrr && Commute) 3319 return false; 3320 3321 // ADD/SUB are special because they're essentially the same operation, so 3322 // we can handle a larger range of immediates. 3323 if (ARM_AM::isSOImmTwoPartVal(ImmVal)) 3324 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri; 3325 else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) { 3326 ImmVal = -ImmVal; 3327 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri; 3328 } else 3329 return false; 3330 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal); 3331 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal); 3332 break; 3333 case ARM::ORRrr: 3334 case ARM::EORrr: 3335 if (!ARM_AM::isSOImmTwoPartVal(ImmVal)) 3336 return false; 3337 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal); 3338 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal); 3339 switch (UseOpc) { 3340 default: break; 3341 case ARM::ORRrr: NewUseOpc = ARM::ORRri; break; 3342 case ARM::EORrr: NewUseOpc = ARM::EORri; break; 3343 } 3344 break; 3345 case ARM::t2ADDrr: 3346 case ARM::t2SUBrr: { 3347 if (UseOpc == ARM::t2SUBrr && Commute) 3348 return false; 3349 3350 // ADD/SUB are special because they're essentially the same operation, so 3351 // we can handle a larger range of immediates. 3352 const bool ToSP = DefMI.getOperand(0).getReg() == ARM::SP; 3353 const unsigned t2ADD = ToSP ? ARM::t2ADDspImm : ARM::t2ADDri; 3354 const unsigned t2SUB = ToSP ? ARM::t2SUBspImm : ARM::t2SUBri; 3355 if (ARM_AM::isT2SOImmTwoPartVal(ImmVal)) 3356 NewUseOpc = UseOpc == ARM::t2ADDrr ? t2ADD : t2SUB; 3357 else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) { 3358 ImmVal = -ImmVal; 3359 NewUseOpc = UseOpc == ARM::t2ADDrr ? t2SUB : t2ADD; 3360 } else 3361 return false; 3362 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal); 3363 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal); 3364 break; 3365 } 3366 case ARM::t2ORRrr: 3367 case ARM::t2EORrr: 3368 if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal)) 3369 return false; 3370 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal); 3371 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal); 3372 switch (UseOpc) { 3373 default: break; 3374 case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break; 3375 case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break; 3376 } 3377 break; 3378 } 3379 } 3380 } 3381 3382 unsigned OpIdx = Commute ? 2 : 1; 3383 Register Reg1 = UseMI.getOperand(OpIdx).getReg(); 3384 bool isKill = UseMI.getOperand(OpIdx).isKill(); 3385 const TargetRegisterClass *TRC = MRI->getRegClass(Reg); 3386 Register NewReg = MRI->createVirtualRegister(TRC); 3387 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc), 3388 NewReg) 3389 .addReg(Reg1, getKillRegState(isKill)) 3390 .addImm(SOImmValV1) 3391 .add(predOps(ARMCC::AL)) 3392 .add(condCodeOp()); 3393 UseMI.setDesc(get(NewUseOpc)); 3394 UseMI.getOperand(1).setReg(NewReg); 3395 UseMI.getOperand(1).setIsKill(); 3396 UseMI.getOperand(2).ChangeToImmediate(SOImmValV2); 3397 DefMI.eraseFromParent(); 3398 // FIXME: t2ADDrr should be split, as different rulles apply when writing to SP. 3399 // Just as t2ADDri, that was split to [t2ADDri, t2ADDspImm]. 3400 // Then the below code will not be needed, as the input/output register 3401 // classes will be rgpr or gprSP. 3402 // For now, we fix the UseMI operand explicitly here: 3403 switch(NewUseOpc){ 3404 case ARM::t2ADDspImm: 3405 case ARM::t2SUBspImm: 3406 case ARM::t2ADDri: 3407 case ARM::t2SUBri: 3408 MRI->setRegClass(UseMI.getOperand(0).getReg(), TRC); 3409 } 3410 return true; 3411 } 3412 3413 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData, 3414 const MachineInstr &MI) { 3415 switch (MI.getOpcode()) { 3416 default: { 3417 const MCInstrDesc &Desc = MI.getDesc(); 3418 int UOps = ItinData->getNumMicroOps(Desc.getSchedClass()); 3419 assert(UOps >= 0 && "bad # UOps"); 3420 return UOps; 3421 } 3422 3423 case ARM::LDRrs: 3424 case ARM::LDRBrs: 3425 case ARM::STRrs: 3426 case ARM::STRBrs: { 3427 unsigned ShOpVal = MI.getOperand(3).getImm(); 3428 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3429 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3430 if (!isSub && 3431 (ShImm == 0 || 3432 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3433 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3434 return 1; 3435 return 2; 3436 } 3437 3438 case ARM::LDRH: 3439 case ARM::STRH: { 3440 if (!MI.getOperand(2).getReg()) 3441 return 1; 3442 3443 unsigned ShOpVal = MI.getOperand(3).getImm(); 3444 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3445 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3446 if (!isSub && 3447 (ShImm == 0 || 3448 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3449 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3450 return 1; 3451 return 2; 3452 } 3453 3454 case ARM::LDRSB: 3455 case ARM::LDRSH: 3456 return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2; 3457 3458 case ARM::LDRSB_POST: 3459 case ARM::LDRSH_POST: { 3460 Register Rt = MI.getOperand(0).getReg(); 3461 Register Rm = MI.getOperand(3).getReg(); 3462 return (Rt == Rm) ? 4 : 3; 3463 } 3464 3465 case ARM::LDR_PRE_REG: 3466 case ARM::LDRB_PRE_REG: { 3467 Register Rt = MI.getOperand(0).getReg(); 3468 Register Rm = MI.getOperand(3).getReg(); 3469 if (Rt == Rm) 3470 return 3; 3471 unsigned ShOpVal = MI.getOperand(4).getImm(); 3472 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3473 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3474 if (!isSub && 3475 (ShImm == 0 || 3476 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3477 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3478 return 2; 3479 return 3; 3480 } 3481 3482 case ARM::STR_PRE_REG: 3483 case ARM::STRB_PRE_REG: { 3484 unsigned ShOpVal = MI.getOperand(4).getImm(); 3485 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3486 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3487 if (!isSub && 3488 (ShImm == 0 || 3489 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3490 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3491 return 2; 3492 return 3; 3493 } 3494 3495 case ARM::LDRH_PRE: 3496 case ARM::STRH_PRE: { 3497 Register Rt = MI.getOperand(0).getReg(); 3498 Register Rm = MI.getOperand(3).getReg(); 3499 if (!Rm) 3500 return 2; 3501 if (Rt == Rm) 3502 return 3; 3503 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2; 3504 } 3505 3506 case ARM::LDR_POST_REG: 3507 case ARM::LDRB_POST_REG: 3508 case ARM::LDRH_POST: { 3509 Register Rt = MI.getOperand(0).getReg(); 3510 Register Rm = MI.getOperand(3).getReg(); 3511 return (Rt == Rm) ? 3 : 2; 3512 } 3513 3514 case ARM::LDR_PRE_IMM: 3515 case ARM::LDRB_PRE_IMM: 3516 case ARM::LDR_POST_IMM: 3517 case ARM::LDRB_POST_IMM: 3518 case ARM::STRB_POST_IMM: 3519 case ARM::STRB_POST_REG: 3520 case ARM::STRB_PRE_IMM: 3521 case ARM::STRH_POST: 3522 case ARM::STR_POST_IMM: 3523 case ARM::STR_POST_REG: 3524 case ARM::STR_PRE_IMM: 3525 return 2; 3526 3527 case ARM::LDRSB_PRE: 3528 case ARM::LDRSH_PRE: { 3529 Register Rm = MI.getOperand(3).getReg(); 3530 if (Rm == 0) 3531 return 3; 3532 Register Rt = MI.getOperand(0).getReg(); 3533 if (Rt == Rm) 3534 return 4; 3535 unsigned ShOpVal = MI.getOperand(4).getImm(); 3536 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3537 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3538 if (!isSub && 3539 (ShImm == 0 || 3540 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3541 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3542 return 3; 3543 return 4; 3544 } 3545 3546 case ARM::LDRD: { 3547 Register Rt = MI.getOperand(0).getReg(); 3548 Register Rn = MI.getOperand(2).getReg(); 3549 Register Rm = MI.getOperand(3).getReg(); 3550 if (Rm) 3551 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4 3552 : 3; 3553 return (Rt == Rn) ? 3 : 2; 3554 } 3555 3556 case ARM::STRD: { 3557 Register Rm = MI.getOperand(3).getReg(); 3558 if (Rm) 3559 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4 3560 : 3; 3561 return 2; 3562 } 3563 3564 case ARM::LDRD_POST: 3565 case ARM::t2LDRD_POST: 3566 return 3; 3567 3568 case ARM::STRD_POST: 3569 case ARM::t2STRD_POST: 3570 return 4; 3571 3572 case ARM::LDRD_PRE: { 3573 Register Rt = MI.getOperand(0).getReg(); 3574 Register Rn = MI.getOperand(3).getReg(); 3575 Register Rm = MI.getOperand(4).getReg(); 3576 if (Rm) 3577 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5 3578 : 4; 3579 return (Rt == Rn) ? 4 : 3; 3580 } 3581 3582 case ARM::t2LDRD_PRE: { 3583 Register Rt = MI.getOperand(0).getReg(); 3584 Register Rn = MI.getOperand(3).getReg(); 3585 return (Rt == Rn) ? 4 : 3; 3586 } 3587 3588 case ARM::STRD_PRE: { 3589 Register Rm = MI.getOperand(4).getReg(); 3590 if (Rm) 3591 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5 3592 : 4; 3593 return 3; 3594 } 3595 3596 case ARM::t2STRD_PRE: 3597 return 3; 3598 3599 case ARM::t2LDR_POST: 3600 case ARM::t2LDRB_POST: 3601 case ARM::t2LDRB_PRE: 3602 case ARM::t2LDRSBi12: 3603 case ARM::t2LDRSBi8: 3604 case ARM::t2LDRSBpci: 3605 case ARM::t2LDRSBs: 3606 case ARM::t2LDRH_POST: 3607 case ARM::t2LDRH_PRE: 3608 case ARM::t2LDRSBT: 3609 case ARM::t2LDRSB_POST: 3610 case ARM::t2LDRSB_PRE: 3611 case ARM::t2LDRSH_POST: 3612 case ARM::t2LDRSH_PRE: 3613 case ARM::t2LDRSHi12: 3614 case ARM::t2LDRSHi8: 3615 case ARM::t2LDRSHpci: 3616 case ARM::t2LDRSHs: 3617 return 2; 3618 3619 case ARM::t2LDRDi8: { 3620 Register Rt = MI.getOperand(0).getReg(); 3621 Register Rn = MI.getOperand(2).getReg(); 3622 return (Rt == Rn) ? 3 : 2; 3623 } 3624 3625 case ARM::t2STRB_POST: 3626 case ARM::t2STRB_PRE: 3627 case ARM::t2STRBs: 3628 case ARM::t2STRDi8: 3629 case ARM::t2STRH_POST: 3630 case ARM::t2STRH_PRE: 3631 case ARM::t2STRHs: 3632 case ARM::t2STR_POST: 3633 case ARM::t2STR_PRE: 3634 case ARM::t2STRs: 3635 return 2; 3636 } 3637 } 3638 3639 // Return the number of 32-bit words loaded by LDM or stored by STM. If this 3640 // can't be easily determined return 0 (missing MachineMemOperand). 3641 // 3642 // FIXME: The current MachineInstr design does not support relying on machine 3643 // mem operands to determine the width of a memory access. Instead, we expect 3644 // the target to provide this information based on the instruction opcode and 3645 // operands. However, using MachineMemOperand is the best solution now for 3646 // two reasons: 3647 // 3648 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI 3649 // operands. This is much more dangerous than using the MachineMemOperand 3650 // sizes because CodeGen passes can insert/remove optional machine operands. In 3651 // fact, it's totally incorrect for preRA passes and appears to be wrong for 3652 // postRA passes as well. 3653 // 3654 // 2) getNumLDMAddresses is only used by the scheduling machine model and any 3655 // machine model that calls this should handle the unknown (zero size) case. 3656 // 3657 // Long term, we should require a target hook that verifies MachineMemOperand 3658 // sizes during MC lowering. That target hook should be local to MC lowering 3659 // because we can't ensure that it is aware of other MI forms. Doing this will 3660 // ensure that MachineMemOperands are correctly propagated through all passes. 3661 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const { 3662 unsigned Size = 0; 3663 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(), 3664 E = MI.memoperands_end(); 3665 I != E; ++I) { 3666 Size += (*I)->getSize(); 3667 } 3668 // FIXME: The scheduler currently can't handle values larger than 16. But 3669 // the values can actually go up to 32 for floating-point load/store 3670 // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory 3671 // operations isn't right; we could end up with "extra" memory operands for 3672 // various reasons, like tail merge merging two memory operations. 3673 return std::min(Size / 4, 16U); 3674 } 3675 3676 static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc, 3677 unsigned NumRegs) { 3678 unsigned UOps = 1 + NumRegs; // 1 for address computation. 3679 switch (Opc) { 3680 default: 3681 break; 3682 case ARM::VLDMDIA_UPD: 3683 case ARM::VLDMDDB_UPD: 3684 case ARM::VLDMSIA_UPD: 3685 case ARM::VLDMSDB_UPD: 3686 case ARM::VSTMDIA_UPD: 3687 case ARM::VSTMDDB_UPD: 3688 case ARM::VSTMSIA_UPD: 3689 case ARM::VSTMSDB_UPD: 3690 case ARM::LDMIA_UPD: 3691 case ARM::LDMDA_UPD: 3692 case ARM::LDMDB_UPD: 3693 case ARM::LDMIB_UPD: 3694 case ARM::STMIA_UPD: 3695 case ARM::STMDA_UPD: 3696 case ARM::STMDB_UPD: 3697 case ARM::STMIB_UPD: 3698 case ARM::tLDMIA_UPD: 3699 case ARM::tSTMIA_UPD: 3700 case ARM::t2LDMIA_UPD: 3701 case ARM::t2LDMDB_UPD: 3702 case ARM::t2STMIA_UPD: 3703 case ARM::t2STMDB_UPD: 3704 ++UOps; // One for base register writeback. 3705 break; 3706 case ARM::LDMIA_RET: 3707 case ARM::tPOP_RET: 3708 case ARM::t2LDMIA_RET: 3709 UOps += 2; // One for base reg wb, one for write to pc. 3710 break; 3711 } 3712 return UOps; 3713 } 3714 3715 unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData, 3716 const MachineInstr &MI) const { 3717 if (!ItinData || ItinData->isEmpty()) 3718 return 1; 3719 3720 const MCInstrDesc &Desc = MI.getDesc(); 3721 unsigned Class = Desc.getSchedClass(); 3722 int ItinUOps = ItinData->getNumMicroOps(Class); 3723 if (ItinUOps >= 0) { 3724 if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore())) 3725 return getNumMicroOpsSwiftLdSt(ItinData, MI); 3726 3727 return ItinUOps; 3728 } 3729 3730 unsigned Opc = MI.getOpcode(); 3731 switch (Opc) { 3732 default: 3733 llvm_unreachable("Unexpected multi-uops instruction!"); 3734 case ARM::VLDMQIA: 3735 case ARM::VSTMQIA: 3736 return 2; 3737 3738 // The number of uOps for load / store multiple are determined by the number 3739 // registers. 3740 // 3741 // On Cortex-A8, each pair of register loads / stores can be scheduled on the 3742 // same cycle. The scheduling for the first load / store must be done 3743 // separately by assuming the address is not 64-bit aligned. 3744 // 3745 // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address 3746 // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON 3747 // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1. 3748 case ARM::VLDMDIA: 3749 case ARM::VLDMDIA_UPD: 3750 case ARM::VLDMDDB_UPD: 3751 case ARM::VLDMSIA: 3752 case ARM::VLDMSIA_UPD: 3753 case ARM::VLDMSDB_UPD: 3754 case ARM::VSTMDIA: 3755 case ARM::VSTMDIA_UPD: 3756 case ARM::VSTMDDB_UPD: 3757 case ARM::VSTMSIA: 3758 case ARM::VSTMSIA_UPD: 3759 case ARM::VSTMSDB_UPD: { 3760 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands(); 3761 return (NumRegs / 2) + (NumRegs % 2) + 1; 3762 } 3763 3764 case ARM::LDMIA_RET: 3765 case ARM::LDMIA: 3766 case ARM::LDMDA: 3767 case ARM::LDMDB: 3768 case ARM::LDMIB: 3769 case ARM::LDMIA_UPD: 3770 case ARM::LDMDA_UPD: 3771 case ARM::LDMDB_UPD: 3772 case ARM::LDMIB_UPD: 3773 case ARM::STMIA: 3774 case ARM::STMDA: 3775 case ARM::STMDB: 3776 case ARM::STMIB: 3777 case ARM::STMIA_UPD: 3778 case ARM::STMDA_UPD: 3779 case ARM::STMDB_UPD: 3780 case ARM::STMIB_UPD: 3781 case ARM::tLDMIA: 3782 case ARM::tLDMIA_UPD: 3783 case ARM::tSTMIA_UPD: 3784 case ARM::tPOP_RET: 3785 case ARM::tPOP: 3786 case ARM::tPUSH: 3787 case ARM::t2LDMIA_RET: 3788 case ARM::t2LDMIA: 3789 case ARM::t2LDMDB: 3790 case ARM::t2LDMIA_UPD: 3791 case ARM::t2LDMDB_UPD: 3792 case ARM::t2STMIA: 3793 case ARM::t2STMDB: 3794 case ARM::t2STMIA_UPD: 3795 case ARM::t2STMDB_UPD: { 3796 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1; 3797 switch (Subtarget.getLdStMultipleTiming()) { 3798 case ARMSubtarget::SingleIssuePlusExtras: 3799 return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs); 3800 case ARMSubtarget::SingleIssue: 3801 // Assume the worst. 3802 return NumRegs; 3803 case ARMSubtarget::DoubleIssue: { 3804 if (NumRegs < 4) 3805 return 2; 3806 // 4 registers would be issued: 2, 2. 3807 // 5 registers would be issued: 2, 2, 1. 3808 unsigned UOps = (NumRegs / 2); 3809 if (NumRegs % 2) 3810 ++UOps; 3811 return UOps; 3812 } 3813 case ARMSubtarget::DoubleIssueCheckUnalignedAccess: { 3814 unsigned UOps = (NumRegs / 2); 3815 // If there are odd number of registers or if it's not 64-bit aligned, 3816 // then it takes an extra AGU (Address Generation Unit) cycle. 3817 if ((NumRegs % 2) || !MI.hasOneMemOperand() || 3818 (*MI.memoperands_begin())->getAlign() < Align(8)) 3819 ++UOps; 3820 return UOps; 3821 } 3822 } 3823 } 3824 } 3825 llvm_unreachable("Didn't find the number of microops"); 3826 } 3827 3828 int 3829 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData, 3830 const MCInstrDesc &DefMCID, 3831 unsigned DefClass, 3832 unsigned DefIdx, unsigned DefAlign) const { 3833 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1; 3834 if (RegNo <= 0) 3835 // Def is the address writeback. 3836 return ItinData->getOperandCycle(DefClass, DefIdx); 3837 3838 int DefCycle; 3839 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3840 // (regno / 2) + (regno % 2) + 1 3841 DefCycle = RegNo / 2 + 1; 3842 if (RegNo % 2) 3843 ++DefCycle; 3844 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3845 DefCycle = RegNo; 3846 bool isSLoad = false; 3847 3848 switch (DefMCID.getOpcode()) { 3849 default: break; 3850 case ARM::VLDMSIA: 3851 case ARM::VLDMSIA_UPD: 3852 case ARM::VLDMSDB_UPD: 3853 isSLoad = true; 3854 break; 3855 } 3856 3857 // If there are odd number of 'S' registers or if it's not 64-bit aligned, 3858 // then it takes an extra cycle. 3859 if ((isSLoad && (RegNo % 2)) || DefAlign < 8) 3860 ++DefCycle; 3861 } else { 3862 // Assume the worst. 3863 DefCycle = RegNo + 2; 3864 } 3865 3866 return DefCycle; 3867 } 3868 3869 bool ARMBaseInstrInfo::isLDMBaseRegInList(const MachineInstr &MI) const { 3870 Register BaseReg = MI.getOperand(0).getReg(); 3871 for (unsigned i = 1, sz = MI.getNumOperands(); i < sz; ++i) { 3872 const auto &Op = MI.getOperand(i); 3873 if (Op.isReg() && Op.getReg() == BaseReg) 3874 return true; 3875 } 3876 return false; 3877 } 3878 unsigned 3879 ARMBaseInstrInfo::getLDMVariableDefsSize(const MachineInstr &MI) const { 3880 // ins GPR:$Rn, $p (2xOp), reglist:$regs, variable_ops 3881 // (outs GPR:$wb), (ins GPR:$Rn, $p (2xOp), reglist:$regs, variable_ops) 3882 return MI.getNumOperands() + 1 - MI.getDesc().getNumOperands(); 3883 } 3884 3885 int 3886 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData, 3887 const MCInstrDesc &DefMCID, 3888 unsigned DefClass, 3889 unsigned DefIdx, unsigned DefAlign) const { 3890 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1; 3891 if (RegNo <= 0) 3892 // Def is the address writeback. 3893 return ItinData->getOperandCycle(DefClass, DefIdx); 3894 3895 int DefCycle; 3896 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3897 // 4 registers would be issued: 1, 2, 1. 3898 // 5 registers would be issued: 1, 2, 2. 3899 DefCycle = RegNo / 2; 3900 if (DefCycle < 1) 3901 DefCycle = 1; 3902 // Result latency is issue cycle + 2: E2. 3903 DefCycle += 2; 3904 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3905 DefCycle = (RegNo / 2); 3906 // If there are odd number of registers or if it's not 64-bit aligned, 3907 // then it takes an extra AGU (Address Generation Unit) cycle. 3908 if ((RegNo % 2) || DefAlign < 8) 3909 ++DefCycle; 3910 // Result latency is AGU cycles + 2. 3911 DefCycle += 2; 3912 } else { 3913 // Assume the worst. 3914 DefCycle = RegNo + 2; 3915 } 3916 3917 return DefCycle; 3918 } 3919 3920 int 3921 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData, 3922 const MCInstrDesc &UseMCID, 3923 unsigned UseClass, 3924 unsigned UseIdx, unsigned UseAlign) const { 3925 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1; 3926 if (RegNo <= 0) 3927 return ItinData->getOperandCycle(UseClass, UseIdx); 3928 3929 int UseCycle; 3930 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3931 // (regno / 2) + (regno % 2) + 1 3932 UseCycle = RegNo / 2 + 1; 3933 if (RegNo % 2) 3934 ++UseCycle; 3935 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3936 UseCycle = RegNo; 3937 bool isSStore = false; 3938 3939 switch (UseMCID.getOpcode()) { 3940 default: break; 3941 case ARM::VSTMSIA: 3942 case ARM::VSTMSIA_UPD: 3943 case ARM::VSTMSDB_UPD: 3944 isSStore = true; 3945 break; 3946 } 3947 3948 // If there are odd number of 'S' registers or if it's not 64-bit aligned, 3949 // then it takes an extra cycle. 3950 if ((isSStore && (RegNo % 2)) || UseAlign < 8) 3951 ++UseCycle; 3952 } else { 3953 // Assume the worst. 3954 UseCycle = RegNo + 2; 3955 } 3956 3957 return UseCycle; 3958 } 3959 3960 int 3961 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData, 3962 const MCInstrDesc &UseMCID, 3963 unsigned UseClass, 3964 unsigned UseIdx, unsigned UseAlign) const { 3965 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1; 3966 if (RegNo <= 0) 3967 return ItinData->getOperandCycle(UseClass, UseIdx); 3968 3969 int UseCycle; 3970 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3971 UseCycle = RegNo / 2; 3972 if (UseCycle < 2) 3973 UseCycle = 2; 3974 // Read in E3. 3975 UseCycle += 2; 3976 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3977 UseCycle = (RegNo / 2); 3978 // If there are odd number of registers or if it's not 64-bit aligned, 3979 // then it takes an extra AGU (Address Generation Unit) cycle. 3980 if ((RegNo % 2) || UseAlign < 8) 3981 ++UseCycle; 3982 } else { 3983 // Assume the worst. 3984 UseCycle = 1; 3985 } 3986 return UseCycle; 3987 } 3988 3989 int 3990 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 3991 const MCInstrDesc &DefMCID, 3992 unsigned DefIdx, unsigned DefAlign, 3993 const MCInstrDesc &UseMCID, 3994 unsigned UseIdx, unsigned UseAlign) const { 3995 unsigned DefClass = DefMCID.getSchedClass(); 3996 unsigned UseClass = UseMCID.getSchedClass(); 3997 3998 if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands()) 3999 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 4000 4001 // This may be a def / use of a variable_ops instruction, the operand 4002 // latency might be determinable dynamically. Let the target try to 4003 // figure it out. 4004 int DefCycle = -1; 4005 bool LdmBypass = false; 4006 switch (DefMCID.getOpcode()) { 4007 default: 4008 DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); 4009 break; 4010 4011 case ARM::VLDMDIA: 4012 case ARM::VLDMDIA_UPD: 4013 case ARM::VLDMDDB_UPD: 4014 case ARM::VLDMSIA: 4015 case ARM::VLDMSIA_UPD: 4016 case ARM::VLDMSDB_UPD: 4017 DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign); 4018 break; 4019 4020 case ARM::LDMIA_RET: 4021 case ARM::LDMIA: 4022 case ARM::LDMDA: 4023 case ARM::LDMDB: 4024 case ARM::LDMIB: 4025 case ARM::LDMIA_UPD: 4026 case ARM::LDMDA_UPD: 4027 case ARM::LDMDB_UPD: 4028 case ARM::LDMIB_UPD: 4029 case ARM::tLDMIA: 4030 case ARM::tLDMIA_UPD: 4031 case ARM::tPUSH: 4032 case ARM::t2LDMIA_RET: 4033 case ARM::t2LDMIA: 4034 case ARM::t2LDMDB: 4035 case ARM::t2LDMIA_UPD: 4036 case ARM::t2LDMDB_UPD: 4037 LdmBypass = true; 4038 DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign); 4039 break; 4040 } 4041 4042 if (DefCycle == -1) 4043 // We can't seem to determine the result latency of the def, assume it's 2. 4044 DefCycle = 2; 4045 4046 int UseCycle = -1; 4047 switch (UseMCID.getOpcode()) { 4048 default: 4049 UseCycle = ItinData->getOperandCycle(UseClass, UseIdx); 4050 break; 4051 4052 case ARM::VSTMDIA: 4053 case ARM::VSTMDIA_UPD: 4054 case ARM::VSTMDDB_UPD: 4055 case ARM::VSTMSIA: 4056 case ARM::VSTMSIA_UPD: 4057 case ARM::VSTMSDB_UPD: 4058 UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign); 4059 break; 4060 4061 case ARM::STMIA: 4062 case ARM::STMDA: 4063 case ARM::STMDB: 4064 case ARM::STMIB: 4065 case ARM::STMIA_UPD: 4066 case ARM::STMDA_UPD: 4067 case ARM::STMDB_UPD: 4068 case ARM::STMIB_UPD: 4069 case ARM::tSTMIA_UPD: 4070 case ARM::tPOP_RET: 4071 case ARM::tPOP: 4072 case ARM::t2STMIA: 4073 case ARM::t2STMDB: 4074 case ARM::t2STMIA_UPD: 4075 case ARM::t2STMDB_UPD: 4076 UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign); 4077 break; 4078 } 4079 4080 if (UseCycle == -1) 4081 // Assume it's read in the first stage. 4082 UseCycle = 1; 4083 4084 UseCycle = DefCycle - UseCycle + 1; 4085 if (UseCycle > 0) { 4086 if (LdmBypass) { 4087 // It's a variable_ops instruction so we can't use DefIdx here. Just use 4088 // first def operand. 4089 if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1, 4090 UseClass, UseIdx)) 4091 --UseCycle; 4092 } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx, 4093 UseClass, UseIdx)) { 4094 --UseCycle; 4095 } 4096 } 4097 4098 return UseCycle; 4099 } 4100 4101 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI, 4102 const MachineInstr *MI, unsigned Reg, 4103 unsigned &DefIdx, unsigned &Dist) { 4104 Dist = 0; 4105 4106 MachineBasicBlock::const_iterator I = MI; ++I; 4107 MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator()); 4108 assert(II->isInsideBundle() && "Empty bundle?"); 4109 4110 int Idx = -1; 4111 while (II->isInsideBundle()) { 4112 Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI); 4113 if (Idx != -1) 4114 break; 4115 --II; 4116 ++Dist; 4117 } 4118 4119 assert(Idx != -1 && "Cannot find bundled definition!"); 4120 DefIdx = Idx; 4121 return &*II; 4122 } 4123 4124 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI, 4125 const MachineInstr &MI, unsigned Reg, 4126 unsigned &UseIdx, unsigned &Dist) { 4127 Dist = 0; 4128 4129 MachineBasicBlock::const_instr_iterator II = ++MI.getIterator(); 4130 assert(II->isInsideBundle() && "Empty bundle?"); 4131 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 4132 4133 // FIXME: This doesn't properly handle multiple uses. 4134 int Idx = -1; 4135 while (II != E && II->isInsideBundle()) { 4136 Idx = II->findRegisterUseOperandIdx(Reg, false, TRI); 4137 if (Idx != -1) 4138 break; 4139 if (II->getOpcode() != ARM::t2IT) 4140 ++Dist; 4141 ++II; 4142 } 4143 4144 if (Idx == -1) { 4145 Dist = 0; 4146 return nullptr; 4147 } 4148 4149 UseIdx = Idx; 4150 return &*II; 4151 } 4152 4153 /// Return the number of cycles to add to (or subtract from) the static 4154 /// itinerary based on the def opcode and alignment. The caller will ensure that 4155 /// adjusted latency is at least one cycle. 4156 static int adjustDefLatency(const ARMSubtarget &Subtarget, 4157 const MachineInstr &DefMI, 4158 const MCInstrDesc &DefMCID, unsigned DefAlign) { 4159 int Adjust = 0; 4160 if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) { 4161 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2] 4162 // variants are one cycle cheaper. 4163 switch (DefMCID.getOpcode()) { 4164 default: break; 4165 case ARM::LDRrs: 4166 case ARM::LDRBrs: { 4167 unsigned ShOpVal = DefMI.getOperand(3).getImm(); 4168 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4169 if (ShImm == 0 || 4170 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) 4171 --Adjust; 4172 break; 4173 } 4174 case ARM::t2LDRs: 4175 case ARM::t2LDRBs: 4176 case ARM::t2LDRHs: 4177 case ARM::t2LDRSHs: { 4178 // Thumb2 mode: lsl only. 4179 unsigned ShAmt = DefMI.getOperand(3).getImm(); 4180 if (ShAmt == 0 || ShAmt == 2) 4181 --Adjust; 4182 break; 4183 } 4184 } 4185 } else if (Subtarget.isSwift()) { 4186 // FIXME: Properly handle all of the latency adjustments for address 4187 // writeback. 4188 switch (DefMCID.getOpcode()) { 4189 default: break; 4190 case ARM::LDRrs: 4191 case ARM::LDRBrs: { 4192 unsigned ShOpVal = DefMI.getOperand(3).getImm(); 4193 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 4194 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4195 if (!isSub && 4196 (ShImm == 0 || 4197 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 4198 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 4199 Adjust -= 2; 4200 else if (!isSub && 4201 ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr) 4202 --Adjust; 4203 break; 4204 } 4205 case ARM::t2LDRs: 4206 case ARM::t2LDRBs: 4207 case ARM::t2LDRHs: 4208 case ARM::t2LDRSHs: { 4209 // Thumb2 mode: lsl only. 4210 unsigned ShAmt = DefMI.getOperand(3).getImm(); 4211 if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3) 4212 Adjust -= 2; 4213 break; 4214 } 4215 } 4216 } 4217 4218 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) { 4219 switch (DefMCID.getOpcode()) { 4220 default: break; 4221 case ARM::VLD1q8: 4222 case ARM::VLD1q16: 4223 case ARM::VLD1q32: 4224 case ARM::VLD1q64: 4225 case ARM::VLD1q8wb_fixed: 4226 case ARM::VLD1q16wb_fixed: 4227 case ARM::VLD1q32wb_fixed: 4228 case ARM::VLD1q64wb_fixed: 4229 case ARM::VLD1q8wb_register: 4230 case ARM::VLD1q16wb_register: 4231 case ARM::VLD1q32wb_register: 4232 case ARM::VLD1q64wb_register: 4233 case ARM::VLD2d8: 4234 case ARM::VLD2d16: 4235 case ARM::VLD2d32: 4236 case ARM::VLD2q8: 4237 case ARM::VLD2q16: 4238 case ARM::VLD2q32: 4239 case ARM::VLD2d8wb_fixed: 4240 case ARM::VLD2d16wb_fixed: 4241 case ARM::VLD2d32wb_fixed: 4242 case ARM::VLD2q8wb_fixed: 4243 case ARM::VLD2q16wb_fixed: 4244 case ARM::VLD2q32wb_fixed: 4245 case ARM::VLD2d8wb_register: 4246 case ARM::VLD2d16wb_register: 4247 case ARM::VLD2d32wb_register: 4248 case ARM::VLD2q8wb_register: 4249 case ARM::VLD2q16wb_register: 4250 case ARM::VLD2q32wb_register: 4251 case ARM::VLD3d8: 4252 case ARM::VLD3d16: 4253 case ARM::VLD3d32: 4254 case ARM::VLD1d64T: 4255 case ARM::VLD3d8_UPD: 4256 case ARM::VLD3d16_UPD: 4257 case ARM::VLD3d32_UPD: 4258 case ARM::VLD1d64Twb_fixed: 4259 case ARM::VLD1d64Twb_register: 4260 case ARM::VLD3q8_UPD: 4261 case ARM::VLD3q16_UPD: 4262 case ARM::VLD3q32_UPD: 4263 case ARM::VLD4d8: 4264 case ARM::VLD4d16: 4265 case ARM::VLD4d32: 4266 case ARM::VLD1d64Q: 4267 case ARM::VLD4d8_UPD: 4268 case ARM::VLD4d16_UPD: 4269 case ARM::VLD4d32_UPD: 4270 case ARM::VLD1d64Qwb_fixed: 4271 case ARM::VLD1d64Qwb_register: 4272 case ARM::VLD4q8_UPD: 4273 case ARM::VLD4q16_UPD: 4274 case ARM::VLD4q32_UPD: 4275 case ARM::VLD1DUPq8: 4276 case ARM::VLD1DUPq16: 4277 case ARM::VLD1DUPq32: 4278 case ARM::VLD1DUPq8wb_fixed: 4279 case ARM::VLD1DUPq16wb_fixed: 4280 case ARM::VLD1DUPq32wb_fixed: 4281 case ARM::VLD1DUPq8wb_register: 4282 case ARM::VLD1DUPq16wb_register: 4283 case ARM::VLD1DUPq32wb_register: 4284 case ARM::VLD2DUPd8: 4285 case ARM::VLD2DUPd16: 4286 case ARM::VLD2DUPd32: 4287 case ARM::VLD2DUPd8wb_fixed: 4288 case ARM::VLD2DUPd16wb_fixed: 4289 case ARM::VLD2DUPd32wb_fixed: 4290 case ARM::VLD2DUPd8wb_register: 4291 case ARM::VLD2DUPd16wb_register: 4292 case ARM::VLD2DUPd32wb_register: 4293 case ARM::VLD4DUPd8: 4294 case ARM::VLD4DUPd16: 4295 case ARM::VLD4DUPd32: 4296 case ARM::VLD4DUPd8_UPD: 4297 case ARM::VLD4DUPd16_UPD: 4298 case ARM::VLD4DUPd32_UPD: 4299 case ARM::VLD1LNd8: 4300 case ARM::VLD1LNd16: 4301 case ARM::VLD1LNd32: 4302 case ARM::VLD1LNd8_UPD: 4303 case ARM::VLD1LNd16_UPD: 4304 case ARM::VLD1LNd32_UPD: 4305 case ARM::VLD2LNd8: 4306 case ARM::VLD2LNd16: 4307 case ARM::VLD2LNd32: 4308 case ARM::VLD2LNq16: 4309 case ARM::VLD2LNq32: 4310 case ARM::VLD2LNd8_UPD: 4311 case ARM::VLD2LNd16_UPD: 4312 case ARM::VLD2LNd32_UPD: 4313 case ARM::VLD2LNq16_UPD: 4314 case ARM::VLD2LNq32_UPD: 4315 case ARM::VLD4LNd8: 4316 case ARM::VLD4LNd16: 4317 case ARM::VLD4LNd32: 4318 case ARM::VLD4LNq16: 4319 case ARM::VLD4LNq32: 4320 case ARM::VLD4LNd8_UPD: 4321 case ARM::VLD4LNd16_UPD: 4322 case ARM::VLD4LNd32_UPD: 4323 case ARM::VLD4LNq16_UPD: 4324 case ARM::VLD4LNq32_UPD: 4325 // If the address is not 64-bit aligned, the latencies of these 4326 // instructions increases by one. 4327 ++Adjust; 4328 break; 4329 } 4330 } 4331 return Adjust; 4332 } 4333 4334 int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 4335 const MachineInstr &DefMI, 4336 unsigned DefIdx, 4337 const MachineInstr &UseMI, 4338 unsigned UseIdx) const { 4339 // No operand latency. The caller may fall back to getInstrLatency. 4340 if (!ItinData || ItinData->isEmpty()) 4341 return -1; 4342 4343 const MachineOperand &DefMO = DefMI.getOperand(DefIdx); 4344 Register Reg = DefMO.getReg(); 4345 4346 const MachineInstr *ResolvedDefMI = &DefMI; 4347 unsigned DefAdj = 0; 4348 if (DefMI.isBundle()) 4349 ResolvedDefMI = 4350 getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj); 4351 if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() || 4352 ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) { 4353 return 1; 4354 } 4355 4356 const MachineInstr *ResolvedUseMI = &UseMI; 4357 unsigned UseAdj = 0; 4358 if (UseMI.isBundle()) { 4359 ResolvedUseMI = 4360 getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj); 4361 if (!ResolvedUseMI) 4362 return -1; 4363 } 4364 4365 return getOperandLatencyImpl( 4366 ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO, 4367 Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj); 4368 } 4369 4370 int ARMBaseInstrInfo::getOperandLatencyImpl( 4371 const InstrItineraryData *ItinData, const MachineInstr &DefMI, 4372 unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj, 4373 const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI, 4374 unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const { 4375 if (Reg == ARM::CPSR) { 4376 if (DefMI.getOpcode() == ARM::FMSTAT) { 4377 // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?) 4378 return Subtarget.isLikeA9() ? 1 : 20; 4379 } 4380 4381 // CPSR set and branch can be paired in the same cycle. 4382 if (UseMI.isBranch()) 4383 return 0; 4384 4385 // Otherwise it takes the instruction latency (generally one). 4386 unsigned Latency = getInstrLatency(ItinData, DefMI); 4387 4388 // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to 4389 // its uses. Instructions which are otherwise scheduled between them may 4390 // incur a code size penalty (not able to use the CPSR setting 16-bit 4391 // instructions). 4392 if (Latency > 0 && Subtarget.isThumb2()) { 4393 const MachineFunction *MF = DefMI.getParent()->getParent(); 4394 // FIXME: Use Function::hasOptSize(). 4395 if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize)) 4396 --Latency; 4397 } 4398 return Latency; 4399 } 4400 4401 if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit()) 4402 return -1; 4403 4404 unsigned DefAlign = DefMI.hasOneMemOperand() 4405 ? (*DefMI.memoperands_begin())->getAlign().value() 4406 : 0; 4407 unsigned UseAlign = UseMI.hasOneMemOperand() 4408 ? (*UseMI.memoperands_begin())->getAlign().value() 4409 : 0; 4410 4411 // Get the itinerary's latency if possible, and handle variable_ops. 4412 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID, 4413 UseIdx, UseAlign); 4414 // Unable to find operand latency. The caller may resort to getInstrLatency. 4415 if (Latency < 0) 4416 return Latency; 4417 4418 // Adjust for IT block position. 4419 int Adj = DefAdj + UseAdj; 4420 4421 // Adjust for dynamic def-side opcode variants not captured by the itinerary. 4422 Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign); 4423 if (Adj >= 0 || (int)Latency > -Adj) { 4424 return Latency + Adj; 4425 } 4426 // Return the itinerary latency, which may be zero but not less than zero. 4427 return Latency; 4428 } 4429 4430 int 4431 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 4432 SDNode *DefNode, unsigned DefIdx, 4433 SDNode *UseNode, unsigned UseIdx) const { 4434 if (!DefNode->isMachineOpcode()) 4435 return 1; 4436 4437 const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode()); 4438 4439 if (isZeroCost(DefMCID.Opcode)) 4440 return 0; 4441 4442 if (!ItinData || ItinData->isEmpty()) 4443 return DefMCID.mayLoad() ? 3 : 1; 4444 4445 if (!UseNode->isMachineOpcode()) { 4446 int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx); 4447 int Adj = Subtarget.getPreISelOperandLatencyAdjustment(); 4448 int Threshold = 1 + Adj; 4449 return Latency <= Threshold ? 1 : Latency - Adj; 4450 } 4451 4452 const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode()); 4453 auto *DefMN = cast<MachineSDNode>(DefNode); 4454 unsigned DefAlign = !DefMN->memoperands_empty() 4455 ? (*DefMN->memoperands_begin())->getAlign().value() 4456 : 0; 4457 auto *UseMN = cast<MachineSDNode>(UseNode); 4458 unsigned UseAlign = !UseMN->memoperands_empty() 4459 ? (*UseMN->memoperands_begin())->getAlign().value() 4460 : 0; 4461 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, 4462 UseMCID, UseIdx, UseAlign); 4463 4464 if (Latency > 1 && 4465 (Subtarget.isCortexA8() || Subtarget.isLikeA9() || 4466 Subtarget.isCortexA7())) { 4467 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2] 4468 // variants are one cycle cheaper. 4469 switch (DefMCID.getOpcode()) { 4470 default: break; 4471 case ARM::LDRrs: 4472 case ARM::LDRBrs: { 4473 unsigned ShOpVal = 4474 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue(); 4475 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4476 if (ShImm == 0 || 4477 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) 4478 --Latency; 4479 break; 4480 } 4481 case ARM::t2LDRs: 4482 case ARM::t2LDRBs: 4483 case ARM::t2LDRHs: 4484 case ARM::t2LDRSHs: { 4485 // Thumb2 mode: lsl only. 4486 unsigned ShAmt = 4487 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue(); 4488 if (ShAmt == 0 || ShAmt == 2) 4489 --Latency; 4490 break; 4491 } 4492 } 4493 } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) { 4494 // FIXME: Properly handle all of the latency adjustments for address 4495 // writeback. 4496 switch (DefMCID.getOpcode()) { 4497 default: break; 4498 case ARM::LDRrs: 4499 case ARM::LDRBrs: { 4500 unsigned ShOpVal = 4501 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue(); 4502 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4503 if (ShImm == 0 || 4504 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 4505 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) 4506 Latency -= 2; 4507 else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr) 4508 --Latency; 4509 break; 4510 } 4511 case ARM::t2LDRs: 4512 case ARM::t2LDRBs: 4513 case ARM::t2LDRHs: 4514 case ARM::t2LDRSHs: 4515 // Thumb2 mode: lsl 0-3 only. 4516 Latency -= 2; 4517 break; 4518 } 4519 } 4520 4521 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) 4522 switch (DefMCID.getOpcode()) { 4523 default: break; 4524 case ARM::VLD1q8: 4525 case ARM::VLD1q16: 4526 case ARM::VLD1q32: 4527 case ARM::VLD1q64: 4528 case ARM::VLD1q8wb_register: 4529 case ARM::VLD1q16wb_register: 4530 case ARM::VLD1q32wb_register: 4531 case ARM::VLD1q64wb_register: 4532 case ARM::VLD1q8wb_fixed: 4533 case ARM::VLD1q16wb_fixed: 4534 case ARM::VLD1q32wb_fixed: 4535 case ARM::VLD1q64wb_fixed: 4536 case ARM::VLD2d8: 4537 case ARM::VLD2d16: 4538 case ARM::VLD2d32: 4539 case ARM::VLD2q8Pseudo: 4540 case ARM::VLD2q16Pseudo: 4541 case ARM::VLD2q32Pseudo: 4542 case ARM::VLD2d8wb_fixed: 4543 case ARM::VLD2d16wb_fixed: 4544 case ARM::VLD2d32wb_fixed: 4545 case ARM::VLD2q8PseudoWB_fixed: 4546 case ARM::VLD2q16PseudoWB_fixed: 4547 case ARM::VLD2q32PseudoWB_fixed: 4548 case ARM::VLD2d8wb_register: 4549 case ARM::VLD2d16wb_register: 4550 case ARM::VLD2d32wb_register: 4551 case ARM::VLD2q8PseudoWB_register: 4552 case ARM::VLD2q16PseudoWB_register: 4553 case ARM::VLD2q32PseudoWB_register: 4554 case ARM::VLD3d8Pseudo: 4555 case ARM::VLD3d16Pseudo: 4556 case ARM::VLD3d32Pseudo: 4557 case ARM::VLD1d8TPseudo: 4558 case ARM::VLD1d16TPseudo: 4559 case ARM::VLD1d32TPseudo: 4560 case ARM::VLD1d64TPseudo: 4561 case ARM::VLD1d64TPseudoWB_fixed: 4562 case ARM::VLD1d64TPseudoWB_register: 4563 case ARM::VLD3d8Pseudo_UPD: 4564 case ARM::VLD3d16Pseudo_UPD: 4565 case ARM::VLD3d32Pseudo_UPD: 4566 case ARM::VLD3q8Pseudo_UPD: 4567 case ARM::VLD3q16Pseudo_UPD: 4568 case ARM::VLD3q32Pseudo_UPD: 4569 case ARM::VLD3q8oddPseudo: 4570 case ARM::VLD3q16oddPseudo: 4571 case ARM::VLD3q32oddPseudo: 4572 case ARM::VLD3q8oddPseudo_UPD: 4573 case ARM::VLD3q16oddPseudo_UPD: 4574 case ARM::VLD3q32oddPseudo_UPD: 4575 case ARM::VLD4d8Pseudo: 4576 case ARM::VLD4d16Pseudo: 4577 case ARM::VLD4d32Pseudo: 4578 case ARM::VLD1d8QPseudo: 4579 case ARM::VLD1d16QPseudo: 4580 case ARM::VLD1d32QPseudo: 4581 case ARM::VLD1d64QPseudo: 4582 case ARM::VLD1d64QPseudoWB_fixed: 4583 case ARM::VLD1d64QPseudoWB_register: 4584 case ARM::VLD1q8HighQPseudo: 4585 case ARM::VLD1q8LowQPseudo_UPD: 4586 case ARM::VLD1q8HighTPseudo: 4587 case ARM::VLD1q8LowTPseudo_UPD: 4588 case ARM::VLD1q16HighQPseudo: 4589 case ARM::VLD1q16LowQPseudo_UPD: 4590 case ARM::VLD1q16HighTPseudo: 4591 case ARM::VLD1q16LowTPseudo_UPD: 4592 case ARM::VLD1q32HighQPseudo: 4593 case ARM::VLD1q32LowQPseudo_UPD: 4594 case ARM::VLD1q32HighTPseudo: 4595 case ARM::VLD1q32LowTPseudo_UPD: 4596 case ARM::VLD1q64HighQPseudo: 4597 case ARM::VLD1q64LowQPseudo_UPD: 4598 case ARM::VLD1q64HighTPseudo: 4599 case ARM::VLD1q64LowTPseudo_UPD: 4600 case ARM::VLD4d8Pseudo_UPD: 4601 case ARM::VLD4d16Pseudo_UPD: 4602 case ARM::VLD4d32Pseudo_UPD: 4603 case ARM::VLD4q8Pseudo_UPD: 4604 case ARM::VLD4q16Pseudo_UPD: 4605 case ARM::VLD4q32Pseudo_UPD: 4606 case ARM::VLD4q8oddPseudo: 4607 case ARM::VLD4q16oddPseudo: 4608 case ARM::VLD4q32oddPseudo: 4609 case ARM::VLD4q8oddPseudo_UPD: 4610 case ARM::VLD4q16oddPseudo_UPD: 4611 case ARM::VLD4q32oddPseudo_UPD: 4612 case ARM::VLD1DUPq8: 4613 case ARM::VLD1DUPq16: 4614 case ARM::VLD1DUPq32: 4615 case ARM::VLD1DUPq8wb_fixed: 4616 case ARM::VLD1DUPq16wb_fixed: 4617 case ARM::VLD1DUPq32wb_fixed: 4618 case ARM::VLD1DUPq8wb_register: 4619 case ARM::VLD1DUPq16wb_register: 4620 case ARM::VLD1DUPq32wb_register: 4621 case ARM::VLD2DUPd8: 4622 case ARM::VLD2DUPd16: 4623 case ARM::VLD2DUPd32: 4624 case ARM::VLD2DUPd8wb_fixed: 4625 case ARM::VLD2DUPd16wb_fixed: 4626 case ARM::VLD2DUPd32wb_fixed: 4627 case ARM::VLD2DUPd8wb_register: 4628 case ARM::VLD2DUPd16wb_register: 4629 case ARM::VLD2DUPd32wb_register: 4630 case ARM::VLD2DUPq8EvenPseudo: 4631 case ARM::VLD2DUPq8OddPseudo: 4632 case ARM::VLD2DUPq16EvenPseudo: 4633 case ARM::VLD2DUPq16OddPseudo: 4634 case ARM::VLD2DUPq32EvenPseudo: 4635 case ARM::VLD2DUPq32OddPseudo: 4636 case ARM::VLD3DUPq8EvenPseudo: 4637 case ARM::VLD3DUPq8OddPseudo: 4638 case ARM::VLD3DUPq16EvenPseudo: 4639 case ARM::VLD3DUPq16OddPseudo: 4640 case ARM::VLD3DUPq32EvenPseudo: 4641 case ARM::VLD3DUPq32OddPseudo: 4642 case ARM::VLD4DUPd8Pseudo: 4643 case ARM::VLD4DUPd16Pseudo: 4644 case ARM::VLD4DUPd32Pseudo: 4645 case ARM::VLD4DUPd8Pseudo_UPD: 4646 case ARM::VLD4DUPd16Pseudo_UPD: 4647 case ARM::VLD4DUPd32Pseudo_UPD: 4648 case ARM::VLD4DUPq8EvenPseudo: 4649 case ARM::VLD4DUPq8OddPseudo: 4650 case ARM::VLD4DUPq16EvenPseudo: 4651 case ARM::VLD4DUPq16OddPseudo: 4652 case ARM::VLD4DUPq32EvenPseudo: 4653 case ARM::VLD4DUPq32OddPseudo: 4654 case ARM::VLD1LNq8Pseudo: 4655 case ARM::VLD1LNq16Pseudo: 4656 case ARM::VLD1LNq32Pseudo: 4657 case ARM::VLD1LNq8Pseudo_UPD: 4658 case ARM::VLD1LNq16Pseudo_UPD: 4659 case ARM::VLD1LNq32Pseudo_UPD: 4660 case ARM::VLD2LNd8Pseudo: 4661 case ARM::VLD2LNd16Pseudo: 4662 case ARM::VLD2LNd32Pseudo: 4663 case ARM::VLD2LNq16Pseudo: 4664 case ARM::VLD2LNq32Pseudo: 4665 case ARM::VLD2LNd8Pseudo_UPD: 4666 case ARM::VLD2LNd16Pseudo_UPD: 4667 case ARM::VLD2LNd32Pseudo_UPD: 4668 case ARM::VLD2LNq16Pseudo_UPD: 4669 case ARM::VLD2LNq32Pseudo_UPD: 4670 case ARM::VLD4LNd8Pseudo: 4671 case ARM::VLD4LNd16Pseudo: 4672 case ARM::VLD4LNd32Pseudo: 4673 case ARM::VLD4LNq16Pseudo: 4674 case ARM::VLD4LNq32Pseudo: 4675 case ARM::VLD4LNd8Pseudo_UPD: 4676 case ARM::VLD4LNd16Pseudo_UPD: 4677 case ARM::VLD4LNd32Pseudo_UPD: 4678 case ARM::VLD4LNq16Pseudo_UPD: 4679 case ARM::VLD4LNq32Pseudo_UPD: 4680 // If the address is not 64-bit aligned, the latencies of these 4681 // instructions increases by one. 4682 ++Latency; 4683 break; 4684 } 4685 4686 return Latency; 4687 } 4688 4689 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const { 4690 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() || 4691 MI.isImplicitDef()) 4692 return 0; 4693 4694 if (MI.isBundle()) 4695 return 0; 4696 4697 const MCInstrDesc &MCID = MI.getDesc(); 4698 4699 if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) && 4700 !Subtarget.cheapPredicableCPSRDef())) { 4701 // When predicated, CPSR is an additional source operand for CPSR updating 4702 // instructions, this apparently increases their latencies. 4703 return 1; 4704 } 4705 return 0; 4706 } 4707 4708 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 4709 const MachineInstr &MI, 4710 unsigned *PredCost) const { 4711 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() || 4712 MI.isImplicitDef()) 4713 return 1; 4714 4715 // An instruction scheduler typically runs on unbundled instructions, however 4716 // other passes may query the latency of a bundled instruction. 4717 if (MI.isBundle()) { 4718 unsigned Latency = 0; 4719 MachineBasicBlock::const_instr_iterator I = MI.getIterator(); 4720 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 4721 while (++I != E && I->isInsideBundle()) { 4722 if (I->getOpcode() != ARM::t2IT) 4723 Latency += getInstrLatency(ItinData, *I, PredCost); 4724 } 4725 return Latency; 4726 } 4727 4728 const MCInstrDesc &MCID = MI.getDesc(); 4729 if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) && 4730 !Subtarget.cheapPredicableCPSRDef()))) { 4731 // When predicated, CPSR is an additional source operand for CPSR updating 4732 // instructions, this apparently increases their latencies. 4733 *PredCost = 1; 4734 } 4735 // Be sure to call getStageLatency for an empty itinerary in case it has a 4736 // valid MinLatency property. 4737 if (!ItinData) 4738 return MI.mayLoad() ? 3 : 1; 4739 4740 unsigned Class = MCID.getSchedClass(); 4741 4742 // For instructions with variable uops, use uops as latency. 4743 if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0) 4744 return getNumMicroOps(ItinData, MI); 4745 4746 // For the common case, fall back on the itinerary's latency. 4747 unsigned Latency = ItinData->getStageLatency(Class); 4748 4749 // Adjust for dynamic def-side opcode variants not captured by the itinerary. 4750 unsigned DefAlign = 4751 MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlign().value() : 0; 4752 int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign); 4753 if (Adj >= 0 || (int)Latency > -Adj) { 4754 return Latency + Adj; 4755 } 4756 return Latency; 4757 } 4758 4759 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 4760 SDNode *Node) const { 4761 if (!Node->isMachineOpcode()) 4762 return 1; 4763 4764 if (!ItinData || ItinData->isEmpty()) 4765 return 1; 4766 4767 unsigned Opcode = Node->getMachineOpcode(); 4768 switch (Opcode) { 4769 default: 4770 return ItinData->getStageLatency(get(Opcode).getSchedClass()); 4771 case ARM::VLDMQIA: 4772 case ARM::VSTMQIA: 4773 return 2; 4774 } 4775 } 4776 4777 bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel, 4778 const MachineRegisterInfo *MRI, 4779 const MachineInstr &DefMI, 4780 unsigned DefIdx, 4781 const MachineInstr &UseMI, 4782 unsigned UseIdx) const { 4783 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask; 4784 unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask; 4785 if (Subtarget.nonpipelinedVFP() && 4786 (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP)) 4787 return true; 4788 4789 // Hoist VFP / NEON instructions with 4 or higher latency. 4790 unsigned Latency = 4791 SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx); 4792 if (Latency <= 3) 4793 return false; 4794 return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON || 4795 UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON; 4796 } 4797 4798 bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel, 4799 const MachineInstr &DefMI, 4800 unsigned DefIdx) const { 4801 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries(); 4802 if (!ItinData || ItinData->isEmpty()) 4803 return false; 4804 4805 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask; 4806 if (DDomain == ARMII::DomainGeneral) { 4807 unsigned DefClass = DefMI.getDesc().getSchedClass(); 4808 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); 4809 return (DefCycle != -1 && DefCycle <= 2); 4810 } 4811 return false; 4812 } 4813 4814 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI, 4815 StringRef &ErrInfo) const { 4816 if (convertAddSubFlagsOpcode(MI.getOpcode())) { 4817 ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG"; 4818 return false; 4819 } 4820 if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) { 4821 // Make sure we don't generate a lo-lo mov that isn't supported. 4822 if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) && 4823 !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) { 4824 ErrInfo = "Non-flag-setting Thumb1 mov is v6-only"; 4825 return false; 4826 } 4827 } 4828 if (MI.getOpcode() == ARM::tPUSH || 4829 MI.getOpcode() == ARM::tPOP || 4830 MI.getOpcode() == ARM::tPOP_RET) { 4831 for (int i = 2, e = MI.getNumOperands(); i < e; ++i) { 4832 if (MI.getOperand(i).isImplicit() || 4833 !MI.getOperand(i).isReg()) 4834 continue; 4835 Register Reg = MI.getOperand(i).getReg(); 4836 if (Reg < ARM::R0 || Reg > ARM::R7) { 4837 if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) && 4838 !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) { 4839 ErrInfo = "Unsupported register in Thumb1 push/pop"; 4840 return false; 4841 } 4842 } 4843 } 4844 } 4845 return true; 4846 } 4847 4848 // LoadStackGuard has so far only been implemented for MachO. Different code 4849 // sequence is needed for other targets. 4850 void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI, 4851 unsigned LoadImmOpc, 4852 unsigned LoadOpc) const { 4853 assert(!Subtarget.isROPI() && !Subtarget.isRWPI() && 4854 "ROPI/RWPI not currently supported with stack guard"); 4855 4856 MachineBasicBlock &MBB = *MI->getParent(); 4857 DebugLoc DL = MI->getDebugLoc(); 4858 Register Reg = MI->getOperand(0).getReg(); 4859 const GlobalValue *GV = 4860 cast<GlobalValue>((*MI->memoperands_begin())->getValue()); 4861 MachineInstrBuilder MIB; 4862 4863 BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg) 4864 .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY); 4865 4866 if (Subtarget.isGVIndirectSymbol(GV)) { 4867 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg); 4868 MIB.addReg(Reg, RegState::Kill).addImm(0); 4869 auto Flags = MachineMemOperand::MOLoad | 4870 MachineMemOperand::MODereferenceable | 4871 MachineMemOperand::MOInvariant; 4872 MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand( 4873 MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, Align(4)); 4874 MIB.addMemOperand(MMO).add(predOps(ARMCC::AL)); 4875 } 4876 4877 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg); 4878 MIB.addReg(Reg, RegState::Kill) 4879 .addImm(0) 4880 .cloneMemRefs(*MI) 4881 .add(predOps(ARMCC::AL)); 4882 } 4883 4884 bool 4885 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc, 4886 unsigned &AddSubOpc, 4887 bool &NegAcc, bool &HasLane) const { 4888 DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode); 4889 if (I == MLxEntryMap.end()) 4890 return false; 4891 4892 const ARM_MLxEntry &Entry = ARM_MLxTable[I->second]; 4893 MulOpc = Entry.MulOpc; 4894 AddSubOpc = Entry.AddSubOpc; 4895 NegAcc = Entry.NegAcc; 4896 HasLane = Entry.HasLane; 4897 return true; 4898 } 4899 4900 //===----------------------------------------------------------------------===// 4901 // Execution domains. 4902 //===----------------------------------------------------------------------===// 4903 // 4904 // Some instructions go down the NEON pipeline, some go down the VFP pipeline, 4905 // and some can go down both. The vmov instructions go down the VFP pipeline, 4906 // but they can be changed to vorr equivalents that are executed by the NEON 4907 // pipeline. 4908 // 4909 // We use the following execution domain numbering: 4910 // 4911 enum ARMExeDomain { 4912 ExeGeneric = 0, 4913 ExeVFP = 1, 4914 ExeNEON = 2 4915 }; 4916 4917 // 4918 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h 4919 // 4920 std::pair<uint16_t, uint16_t> 4921 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const { 4922 // If we don't have access to NEON instructions then we won't be able 4923 // to swizzle anything to the NEON domain. Check to make sure. 4924 if (Subtarget.hasNEON()) { 4925 // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON 4926 // if they are not predicated. 4927 if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI)) 4928 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON)); 4929 4930 // CortexA9 is particularly picky about mixing the two and wants these 4931 // converted. 4932 if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) && 4933 (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR || 4934 MI.getOpcode() == ARM::VMOVS)) 4935 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON)); 4936 } 4937 // No other instructions can be swizzled, so just determine their domain. 4938 unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask; 4939 4940 if (Domain & ARMII::DomainNEON) 4941 return std::make_pair(ExeNEON, 0); 4942 4943 // Certain instructions can go either way on Cortex-A8. 4944 // Treat them as NEON instructions. 4945 if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8()) 4946 return std::make_pair(ExeNEON, 0); 4947 4948 if (Domain & ARMII::DomainVFP) 4949 return std::make_pair(ExeVFP, 0); 4950 4951 return std::make_pair(ExeGeneric, 0); 4952 } 4953 4954 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI, 4955 unsigned SReg, unsigned &Lane) { 4956 unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass); 4957 Lane = 0; 4958 4959 if (DReg != ARM::NoRegister) 4960 return DReg; 4961 4962 Lane = 1; 4963 DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass); 4964 4965 assert(DReg && "S-register with no D super-register?"); 4966 return DReg; 4967 } 4968 4969 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane, 4970 /// set ImplicitSReg to a register number that must be marked as implicit-use or 4971 /// zero if no register needs to be defined as implicit-use. 4972 /// 4973 /// If the function cannot determine if an SPR should be marked implicit use or 4974 /// not, it returns false. 4975 /// 4976 /// This function handles cases where an instruction is being modified from taking 4977 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict 4978 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other 4979 /// lane of the DPR). 4980 /// 4981 /// If the other SPR is defined, an implicit-use of it should be added. Else, 4982 /// (including the case where the DPR itself is defined), it should not. 4983 /// 4984 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI, 4985 MachineInstr &MI, unsigned DReg, 4986 unsigned Lane, unsigned &ImplicitSReg) { 4987 // If the DPR is defined or used already, the other SPR lane will be chained 4988 // correctly, so there is nothing to be done. 4989 if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) { 4990 ImplicitSReg = 0; 4991 return true; 4992 } 4993 4994 // Otherwise we need to go searching to see if the SPR is set explicitly. 4995 ImplicitSReg = TRI->getSubReg(DReg, 4996 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1); 4997 MachineBasicBlock::LivenessQueryResult LQR = 4998 MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI); 4999 5000 if (LQR == MachineBasicBlock::LQR_Live) 5001 return true; 5002 else if (LQR == MachineBasicBlock::LQR_Unknown) 5003 return false; 5004 5005 // If the register is known not to be live, there is no need to add an 5006 // implicit-use. 5007 ImplicitSReg = 0; 5008 return true; 5009 } 5010 5011 void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI, 5012 unsigned Domain) const { 5013 unsigned DstReg, SrcReg, DReg; 5014 unsigned Lane; 5015 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI); 5016 const TargetRegisterInfo *TRI = &getRegisterInfo(); 5017 switch (MI.getOpcode()) { 5018 default: 5019 llvm_unreachable("cannot handle opcode!"); 5020 break; 5021 case ARM::VMOVD: 5022 if (Domain != ExeNEON) 5023 break; 5024 5025 // Zap the predicate operands. 5026 assert(!isPredicated(MI) && "Cannot predicate a VORRd"); 5027 5028 // Make sure we've got NEON instructions. 5029 assert(Subtarget.hasNEON() && "VORRd requires NEON"); 5030 5031 // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits) 5032 DstReg = MI.getOperand(0).getReg(); 5033 SrcReg = MI.getOperand(1).getReg(); 5034 5035 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 5036 MI.RemoveOperand(i - 1); 5037 5038 // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits) 5039 MI.setDesc(get(ARM::VORRd)); 5040 MIB.addReg(DstReg, RegState::Define) 5041 .addReg(SrcReg) 5042 .addReg(SrcReg) 5043 .add(predOps(ARMCC::AL)); 5044 break; 5045 case ARM::VMOVRS: 5046 if (Domain != ExeNEON) 5047 break; 5048 assert(!isPredicated(MI) && "Cannot predicate a VGETLN"); 5049 5050 // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits) 5051 DstReg = MI.getOperand(0).getReg(); 5052 SrcReg = MI.getOperand(1).getReg(); 5053 5054 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 5055 MI.RemoveOperand(i - 1); 5056 5057 DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane); 5058 5059 // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps) 5060 // Note that DSrc has been widened and the other lane may be undef, which 5061 // contaminates the entire register. 5062 MI.setDesc(get(ARM::VGETLNi32)); 5063 MIB.addReg(DstReg, RegState::Define) 5064 .addReg(DReg, RegState::Undef) 5065 .addImm(Lane) 5066 .add(predOps(ARMCC::AL)); 5067 5068 // The old source should be an implicit use, otherwise we might think it 5069 // was dead before here. 5070 MIB.addReg(SrcReg, RegState::Implicit); 5071 break; 5072 case ARM::VMOVSR: { 5073 if (Domain != ExeNEON) 5074 break; 5075 assert(!isPredicated(MI) && "Cannot predicate a VSETLN"); 5076 5077 // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits) 5078 DstReg = MI.getOperand(0).getReg(); 5079 SrcReg = MI.getOperand(1).getReg(); 5080 5081 DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane); 5082 5083 unsigned ImplicitSReg; 5084 if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg)) 5085 break; 5086 5087 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 5088 MI.RemoveOperand(i - 1); 5089 5090 // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps) 5091 // Again DDst may be undefined at the beginning of this instruction. 5092 MI.setDesc(get(ARM::VSETLNi32)); 5093 MIB.addReg(DReg, RegState::Define) 5094 .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI))) 5095 .addReg(SrcReg) 5096 .addImm(Lane) 5097 .add(predOps(ARMCC::AL)); 5098 5099 // The narrower destination must be marked as set to keep previous chains 5100 // in place. 5101 MIB.addReg(DstReg, RegState::Define | RegState::Implicit); 5102 if (ImplicitSReg != 0) 5103 MIB.addReg(ImplicitSReg, RegState::Implicit); 5104 break; 5105 } 5106 case ARM::VMOVS: { 5107 if (Domain != ExeNEON) 5108 break; 5109 5110 // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits) 5111 DstReg = MI.getOperand(0).getReg(); 5112 SrcReg = MI.getOperand(1).getReg(); 5113 5114 unsigned DstLane = 0, SrcLane = 0, DDst, DSrc; 5115 DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane); 5116 DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane); 5117 5118 unsigned ImplicitSReg; 5119 if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg)) 5120 break; 5121 5122 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 5123 MI.RemoveOperand(i - 1); 5124 5125 if (DSrc == DDst) { 5126 // Destination can be: 5127 // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits) 5128 MI.setDesc(get(ARM::VDUPLN32d)); 5129 MIB.addReg(DDst, RegState::Define) 5130 .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI))) 5131 .addImm(SrcLane) 5132 .add(predOps(ARMCC::AL)); 5133 5134 // Neither the source or the destination are naturally represented any 5135 // more, so add them in manually. 5136 MIB.addReg(DstReg, RegState::Implicit | RegState::Define); 5137 MIB.addReg(SrcReg, RegState::Implicit); 5138 if (ImplicitSReg != 0) 5139 MIB.addReg(ImplicitSReg, RegState::Implicit); 5140 break; 5141 } 5142 5143 // In general there's no single instruction that can perform an S <-> S 5144 // move in NEON space, but a pair of VEXT instructions *can* do the 5145 // job. It turns out that the VEXTs needed will only use DSrc once, with 5146 // the position based purely on the combination of lane-0 and lane-1 5147 // involved. For example 5148 // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1 5149 // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1 5150 // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1 5151 // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1 5152 // 5153 // Pattern of the MachineInstrs is: 5154 // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits) 5155 MachineInstrBuilder NewMIB; 5156 NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32), 5157 DDst); 5158 5159 // On the first instruction, both DSrc and DDst may be undef if present. 5160 // Specifically when the original instruction didn't have them as an 5161 // <imp-use>. 5162 unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst; 5163 bool CurUndef = !MI.readsRegister(CurReg, TRI); 5164 NewMIB.addReg(CurReg, getUndefRegState(CurUndef)); 5165 5166 CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst; 5167 CurUndef = !MI.readsRegister(CurReg, TRI); 5168 NewMIB.addReg(CurReg, getUndefRegState(CurUndef)) 5169 .addImm(1) 5170 .add(predOps(ARMCC::AL)); 5171 5172 if (SrcLane == DstLane) 5173 NewMIB.addReg(SrcReg, RegState::Implicit); 5174 5175 MI.setDesc(get(ARM::VEXTd32)); 5176 MIB.addReg(DDst, RegState::Define); 5177 5178 // On the second instruction, DDst has definitely been defined above, so 5179 // it is not undef. DSrc, if present, can be undef as above. 5180 CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst; 5181 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI); 5182 MIB.addReg(CurReg, getUndefRegState(CurUndef)); 5183 5184 CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst; 5185 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI); 5186 MIB.addReg(CurReg, getUndefRegState(CurUndef)) 5187 .addImm(1) 5188 .add(predOps(ARMCC::AL)); 5189 5190 if (SrcLane != DstLane) 5191 MIB.addReg(SrcReg, RegState::Implicit); 5192 5193 // As before, the original destination is no longer represented, add it 5194 // implicitly. 5195 MIB.addReg(DstReg, RegState::Define | RegState::Implicit); 5196 if (ImplicitSReg != 0) 5197 MIB.addReg(ImplicitSReg, RegState::Implicit); 5198 break; 5199 } 5200 } 5201 } 5202 5203 //===----------------------------------------------------------------------===// 5204 // Partial register updates 5205 //===----------------------------------------------------------------------===// 5206 // 5207 // Swift renames NEON registers with 64-bit granularity. That means any 5208 // instruction writing an S-reg implicitly reads the containing D-reg. The 5209 // problem is mostly avoided by translating f32 operations to v2f32 operations 5210 // on D-registers, but f32 loads are still a problem. 5211 // 5212 // These instructions can load an f32 into a NEON register: 5213 // 5214 // VLDRS - Only writes S, partial D update. 5215 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops. 5216 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops. 5217 // 5218 // FCONSTD can be used as a dependency-breaking instruction. 5219 unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance( 5220 const MachineInstr &MI, unsigned OpNum, 5221 const TargetRegisterInfo *TRI) const { 5222 auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance(); 5223 if (!PartialUpdateClearance) 5224 return 0; 5225 5226 assert(TRI && "Need TRI instance"); 5227 5228 const MachineOperand &MO = MI.getOperand(OpNum); 5229 if (MO.readsReg()) 5230 return 0; 5231 Register Reg = MO.getReg(); 5232 int UseOp = -1; 5233 5234 switch (MI.getOpcode()) { 5235 // Normal instructions writing only an S-register. 5236 case ARM::VLDRS: 5237 case ARM::FCONSTS: 5238 case ARM::VMOVSR: 5239 case ARM::VMOVv8i8: 5240 case ARM::VMOVv4i16: 5241 case ARM::VMOVv2i32: 5242 case ARM::VMOVv2f32: 5243 case ARM::VMOVv1i64: 5244 UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI); 5245 break; 5246 5247 // Explicitly reads the dependency. 5248 case ARM::VLD1LNd32: 5249 UseOp = 3; 5250 break; 5251 default: 5252 return 0; 5253 } 5254 5255 // If this instruction actually reads a value from Reg, there is no unwanted 5256 // dependency. 5257 if (UseOp != -1 && MI.getOperand(UseOp).readsReg()) 5258 return 0; 5259 5260 // We must be able to clobber the whole D-reg. 5261 if (Register::isVirtualRegister(Reg)) { 5262 // Virtual register must be a def undef foo:ssub_0 operand. 5263 if (!MO.getSubReg() || MI.readsVirtualRegister(Reg)) 5264 return 0; 5265 } else if (ARM::SPRRegClass.contains(Reg)) { 5266 // Physical register: MI must define the full D-reg. 5267 unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0, 5268 &ARM::DPRRegClass); 5269 if (!DReg || !MI.definesRegister(DReg, TRI)) 5270 return 0; 5271 } 5272 5273 // MI has an unwanted D-register dependency. 5274 // Avoid defs in the previous N instructrions. 5275 return PartialUpdateClearance; 5276 } 5277 5278 // Break a partial register dependency after getPartialRegUpdateClearance 5279 // returned non-zero. 5280 void ARMBaseInstrInfo::breakPartialRegDependency( 5281 MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const { 5282 assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def"); 5283 assert(TRI && "Need TRI instance"); 5284 5285 const MachineOperand &MO = MI.getOperand(OpNum); 5286 Register Reg = MO.getReg(); 5287 assert(Register::isPhysicalRegister(Reg) && 5288 "Can't break virtual register dependencies."); 5289 unsigned DReg = Reg; 5290 5291 // If MI defines an S-reg, find the corresponding D super-register. 5292 if (ARM::SPRRegClass.contains(Reg)) { 5293 DReg = ARM::D0 + (Reg - ARM::S0) / 2; 5294 assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken"); 5295 } 5296 5297 assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps"); 5298 assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg"); 5299 5300 // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines 5301 // the full D-register by loading the same value to both lanes. The 5302 // instruction is micro-coded with 2 uops, so don't do this until we can 5303 // properly schedule micro-coded instructions. The dispatcher stalls cause 5304 // too big regressions. 5305 5306 // Insert the dependency-breaking FCONSTD before MI. 5307 // 96 is the encoding of 0.5, but the actual value doesn't matter here. 5308 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg) 5309 .addImm(96) 5310 .add(predOps(ARMCC::AL)); 5311 MI.addRegisterKilled(DReg, TRI, true); 5312 } 5313 5314 bool ARMBaseInstrInfo::hasNOP() const { 5315 return Subtarget.getFeatureBits()[ARM::HasV6KOps]; 5316 } 5317 5318 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const { 5319 if (MI->getNumOperands() < 4) 5320 return true; 5321 unsigned ShOpVal = MI->getOperand(3).getImm(); 5322 unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal); 5323 // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1. 5324 if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) || 5325 ((ShImm == 1 || ShImm == 2) && 5326 ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl)) 5327 return true; 5328 5329 return false; 5330 } 5331 5332 bool ARMBaseInstrInfo::getRegSequenceLikeInputs( 5333 const MachineInstr &MI, unsigned DefIdx, 5334 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const { 5335 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index"); 5336 assert(MI.isRegSequenceLike() && "Invalid kind of instruction"); 5337 5338 switch (MI.getOpcode()) { 5339 case ARM::VMOVDRR: 5340 // dX = VMOVDRR rY, rZ 5341 // is the same as: 5342 // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1 5343 // Populate the InputRegs accordingly. 5344 // rY 5345 const MachineOperand *MOReg = &MI.getOperand(1); 5346 if (!MOReg->isUndef()) 5347 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(), 5348 MOReg->getSubReg(), ARM::ssub_0)); 5349 // rZ 5350 MOReg = &MI.getOperand(2); 5351 if (!MOReg->isUndef()) 5352 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(), 5353 MOReg->getSubReg(), ARM::ssub_1)); 5354 return true; 5355 } 5356 llvm_unreachable("Target dependent opcode missing"); 5357 } 5358 5359 bool ARMBaseInstrInfo::getExtractSubregLikeInputs( 5360 const MachineInstr &MI, unsigned DefIdx, 5361 RegSubRegPairAndIdx &InputReg) const { 5362 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index"); 5363 assert(MI.isExtractSubregLike() && "Invalid kind of instruction"); 5364 5365 switch (MI.getOpcode()) { 5366 case ARM::VMOVRRD: 5367 // rX, rY = VMOVRRD dZ 5368 // is the same as: 5369 // rX = EXTRACT_SUBREG dZ, ssub_0 5370 // rY = EXTRACT_SUBREG dZ, ssub_1 5371 const MachineOperand &MOReg = MI.getOperand(2); 5372 if (MOReg.isUndef()) 5373 return false; 5374 InputReg.Reg = MOReg.getReg(); 5375 InputReg.SubReg = MOReg.getSubReg(); 5376 InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1; 5377 return true; 5378 } 5379 llvm_unreachable("Target dependent opcode missing"); 5380 } 5381 5382 bool ARMBaseInstrInfo::getInsertSubregLikeInputs( 5383 const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, 5384 RegSubRegPairAndIdx &InsertedReg) const { 5385 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index"); 5386 assert(MI.isInsertSubregLike() && "Invalid kind of instruction"); 5387 5388 switch (MI.getOpcode()) { 5389 case ARM::VSETLNi32: 5390 // dX = VSETLNi32 dY, rZ, imm 5391 const MachineOperand &MOBaseReg = MI.getOperand(1); 5392 const MachineOperand &MOInsertedReg = MI.getOperand(2); 5393 if (MOInsertedReg.isUndef()) 5394 return false; 5395 const MachineOperand &MOIndex = MI.getOperand(3); 5396 BaseReg.Reg = MOBaseReg.getReg(); 5397 BaseReg.SubReg = MOBaseReg.getSubReg(); 5398 5399 InsertedReg.Reg = MOInsertedReg.getReg(); 5400 InsertedReg.SubReg = MOInsertedReg.getSubReg(); 5401 InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1; 5402 return true; 5403 } 5404 llvm_unreachable("Target dependent opcode missing"); 5405 } 5406 5407 std::pair<unsigned, unsigned> 5408 ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const { 5409 const unsigned Mask = ARMII::MO_OPTION_MASK; 5410 return std::make_pair(TF & Mask, TF & ~Mask); 5411 } 5412 5413 ArrayRef<std::pair<unsigned, const char *>> 5414 ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const { 5415 using namespace ARMII; 5416 5417 static const std::pair<unsigned, const char *> TargetFlags[] = { 5418 {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}}; 5419 return makeArrayRef(TargetFlags); 5420 } 5421 5422 ArrayRef<std::pair<unsigned, const char *>> 5423 ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const { 5424 using namespace ARMII; 5425 5426 static const std::pair<unsigned, const char *> TargetFlags[] = { 5427 {MO_COFFSTUB, "arm-coffstub"}, 5428 {MO_GOT, "arm-got"}, 5429 {MO_SBREL, "arm-sbrel"}, 5430 {MO_DLLIMPORT, "arm-dllimport"}, 5431 {MO_SECREL, "arm-secrel"}, 5432 {MO_NONLAZY, "arm-nonlazy"}}; 5433 return makeArrayRef(TargetFlags); 5434 } 5435 5436 Optional<RegImmPair> ARMBaseInstrInfo::isAddImmediate(const MachineInstr &MI, 5437 Register Reg) const { 5438 int Sign = 1; 5439 unsigned Opcode = MI.getOpcode(); 5440 int64_t Offset = 0; 5441 5442 // TODO: Handle cases where Reg is a super- or sub-register of the 5443 // destination register. 5444 const MachineOperand &Op0 = MI.getOperand(0); 5445 if (!Op0.isReg() || Reg != Op0.getReg()) 5446 return None; 5447 5448 // We describe SUBri or ADDri instructions. 5449 if (Opcode == ARM::SUBri) 5450 Sign = -1; 5451 else if (Opcode != ARM::ADDri) 5452 return None; 5453 5454 // TODO: Third operand can be global address (usually some string). Since 5455 // strings can be relocated we cannot calculate their offsets for 5456 // now. 5457 if (!MI.getOperand(1).isReg() || !MI.getOperand(2).isImm()) 5458 return None; 5459 5460 Offset = MI.getOperand(2).getImm() * Sign; 5461 return RegImmPair{MI.getOperand(1).getReg(), Offset}; 5462 } 5463 5464 bool llvm::registerDefinedBetween(unsigned Reg, 5465 MachineBasicBlock::iterator From, 5466 MachineBasicBlock::iterator To, 5467 const TargetRegisterInfo *TRI) { 5468 for (auto I = From; I != To; ++I) 5469 if (I->modifiesRegister(Reg, TRI)) 5470 return true; 5471 return false; 5472 } 5473 5474 MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br, 5475 const TargetRegisterInfo *TRI) { 5476 // Search backwards to the instruction that defines CSPR. This may or not 5477 // be a CMP, we check that after this loop. If we find another instruction 5478 // that reads cpsr, we return nullptr. 5479 MachineBasicBlock::iterator CmpMI = Br; 5480 while (CmpMI != Br->getParent()->begin()) { 5481 --CmpMI; 5482 if (CmpMI->modifiesRegister(ARM::CPSR, TRI)) 5483 break; 5484 if (CmpMI->readsRegister(ARM::CPSR, TRI)) 5485 break; 5486 } 5487 5488 // Check that this inst is a CMP r[0-7], #0 and that the register 5489 // is not redefined between the cmp and the br. 5490 if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri) 5491 return nullptr; 5492 Register Reg = CmpMI->getOperand(0).getReg(); 5493 Register PredReg; 5494 ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg); 5495 if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0) 5496 return nullptr; 5497 if (!isARMLowRegister(Reg)) 5498 return nullptr; 5499 if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI)) 5500 return nullptr; 5501 5502 return &*CmpMI; 5503 } 5504 5505 unsigned llvm::ConstantMaterializationCost(unsigned Val, 5506 const ARMSubtarget *Subtarget, 5507 bool ForCodesize) { 5508 if (Subtarget->isThumb()) { 5509 if (Val <= 255) // MOV 5510 return ForCodesize ? 2 : 1; 5511 if (Subtarget->hasV6T2Ops() && (Val <= 0xffff || // MOV 5512 ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW 5513 ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN 5514 return ForCodesize ? 4 : 1; 5515 if (Val <= 510) // MOV + ADDi8 5516 return ForCodesize ? 4 : 2; 5517 if (~Val <= 255) // MOV + MVN 5518 return ForCodesize ? 4 : 2; 5519 if (ARM_AM::isThumbImmShiftedVal(Val)) // MOV + LSL 5520 return ForCodesize ? 4 : 2; 5521 } else { 5522 if (ARM_AM::getSOImmVal(Val) != -1) // MOV 5523 return ForCodesize ? 4 : 1; 5524 if (ARM_AM::getSOImmVal(~Val) != -1) // MVN 5525 return ForCodesize ? 4 : 1; 5526 if (Subtarget->hasV6T2Ops() && Val <= 0xffff) // MOVW 5527 return ForCodesize ? 4 : 1; 5528 if (ARM_AM::isSOImmTwoPartVal(Val)) // two instrs 5529 return ForCodesize ? 8 : 2; 5530 if (ARM_AM::isSOImmTwoPartValNeg(Val)) // two instrs 5531 return ForCodesize ? 8 : 2; 5532 } 5533 if (Subtarget->useMovt()) // MOVW + MOVT 5534 return ForCodesize ? 8 : 2; 5535 return ForCodesize ? 8 : 3; // Literal pool load 5536 } 5537 5538 bool llvm::HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2, 5539 const ARMSubtarget *Subtarget, 5540 bool ForCodesize) { 5541 // Check with ForCodesize 5542 unsigned Cost1 = ConstantMaterializationCost(Val1, Subtarget, ForCodesize); 5543 unsigned Cost2 = ConstantMaterializationCost(Val2, Subtarget, ForCodesize); 5544 if (Cost1 < Cost2) 5545 return true; 5546 if (Cost1 > Cost2) 5547 return false; 5548 5549 // If they are equal, try with !ForCodesize 5550 return ConstantMaterializationCost(Val1, Subtarget, !ForCodesize) < 5551 ConstantMaterializationCost(Val2, Subtarget, !ForCodesize); 5552 } 5553 5554 /// Constants defining how certain sequences should be outlined. 5555 /// This encompasses how an outlined function should be called, and what kind of 5556 /// frame should be emitted for that outlined function. 5557 /// 5558 /// \p MachineOutlinerTailCall implies that the function is being created from 5559 /// a sequence of instructions ending in a return. 5560 /// 5561 /// That is, 5562 /// 5563 /// I1 OUTLINED_FUNCTION: 5564 /// I2 --> B OUTLINED_FUNCTION I1 5565 /// BX LR I2 5566 /// BX LR 5567 /// 5568 /// +-------------------------+--------+-----+ 5569 /// | | Thumb2 | ARM | 5570 /// +-------------------------+--------+-----+ 5571 /// | Call overhead in Bytes | 4 | 4 | 5572 /// | Frame overhead in Bytes | 0 | 0 | 5573 /// | Stack fixup required | No | No | 5574 /// +-------------------------+--------+-----+ 5575 /// 5576 /// \p MachineOutlinerThunk implies that the function is being created from 5577 /// a sequence of instructions ending in a call. The outlined function is 5578 /// called with a BL instruction, and the outlined function tail-calls the 5579 /// original call destination. 5580 /// 5581 /// That is, 5582 /// 5583 /// I1 OUTLINED_FUNCTION: 5584 /// I2 --> BL OUTLINED_FUNCTION I1 5585 /// BL f I2 5586 /// B f 5587 /// 5588 /// +-------------------------+--------+-----+ 5589 /// | | Thumb2 | ARM | 5590 /// +-------------------------+--------+-----+ 5591 /// | Call overhead in Bytes | 4 | 4 | 5592 /// | Frame overhead in Bytes | 0 | 0 | 5593 /// | Stack fixup required | No | No | 5594 /// +-------------------------+--------+-----+ 5595 /// 5596 /// \p MachineOutlinerNoLRSave implies that the function should be called using 5597 /// a BL instruction, but doesn't require LR to be saved and restored. This 5598 /// happens when LR is known to be dead. 5599 /// 5600 /// That is, 5601 /// 5602 /// I1 OUTLINED_FUNCTION: 5603 /// I2 --> BL OUTLINED_FUNCTION I1 5604 /// I3 I2 5605 /// I3 5606 /// BX LR 5607 /// 5608 /// +-------------------------+--------+-----+ 5609 /// | | Thumb2 | ARM | 5610 /// +-------------------------+--------+-----+ 5611 /// | Call overhead in Bytes | 4 | 4 | 5612 /// | Frame overhead in Bytes | 4 | 4 | 5613 /// | Stack fixup required | No | No | 5614 /// +-------------------------+--------+-----+ 5615 /// 5616 /// \p MachineOutlinerRegSave implies that the function should be called with a 5617 /// save and restore of LR to an available register. This allows us to avoid 5618 /// stack fixups. Note that this outlining variant is compatible with the 5619 /// NoLRSave case. 5620 /// 5621 /// That is, 5622 /// 5623 /// I1 Save LR OUTLINED_FUNCTION: 5624 /// I2 --> BL OUTLINED_FUNCTION I1 5625 /// I3 Restore LR I2 5626 /// I3 5627 /// BX LR 5628 /// 5629 /// +-------------------------+--------+-----+ 5630 /// | | Thumb2 | ARM | 5631 /// +-------------------------+--------+-----+ 5632 /// | Call overhead in Bytes | 8 | 12 | 5633 /// | Frame overhead in Bytes | 2 | 4 | 5634 /// | Stack fixup required | No | No | 5635 /// +-------------------------+--------+-----+ 5636 /// 5637 /// \p MachineOutlinerDefault implies that the function should be called with 5638 /// a save and restore of LR to the stack. 5639 /// 5640 /// That is, 5641 /// 5642 /// I1 Save LR OUTLINED_FUNCTION: 5643 /// I2 --> BL OUTLINED_FUNCTION I1 5644 /// I3 Restore LR I2 5645 /// I3 5646 /// BX LR 5647 /// 5648 /// +-------------------------+--------+-----+ 5649 /// | | Thumb2 | ARM | 5650 /// +-------------------------+--------+-----+ 5651 /// | Call overhead in Bytes | 8 | 12 | 5652 /// | Frame overhead in Bytes | 2 | 4 | 5653 /// | Stack fixup required | Yes | Yes | 5654 /// +-------------------------+--------+-----+ 5655 5656 enum MachineOutlinerClass { 5657 MachineOutlinerTailCall, 5658 MachineOutlinerThunk, 5659 MachineOutlinerNoLRSave, 5660 MachineOutlinerRegSave, 5661 MachineOutlinerDefault 5662 }; 5663 5664 enum MachineOutlinerMBBFlags { 5665 LRUnavailableSomewhere = 0x2, 5666 HasCalls = 0x4, 5667 UnsafeRegsDead = 0x8 5668 }; 5669 5670 struct OutlinerCosts { 5671 const int CallTailCall; 5672 const int FrameTailCall; 5673 const int CallThunk; 5674 const int FrameThunk; 5675 const int CallNoLRSave; 5676 const int FrameNoLRSave; 5677 const int CallRegSave; 5678 const int FrameRegSave; 5679 const int CallDefault; 5680 const int FrameDefault; 5681 5682 OutlinerCosts(const ARMSubtarget &target) 5683 : CallTailCall(target.isThumb() ? 4 : 4), 5684 FrameTailCall(target.isThumb() ? 0 : 0), 5685 CallThunk(target.isThumb() ? 4 : 4), 5686 FrameThunk(target.isThumb() ? 0 : 0), 5687 CallNoLRSave(target.isThumb() ? 4 : 4), 5688 FrameNoLRSave(target.isThumb() ? 4 : 4), 5689 CallRegSave(target.isThumb() ? 8 : 12), 5690 FrameRegSave(target.isThumb() ? 2 : 4), 5691 CallDefault(target.isThumb() ? 8 : 12), 5692 FrameDefault(target.isThumb() ? 2 : 4) {} 5693 }; 5694 5695 unsigned 5696 ARMBaseInstrInfo::findRegisterToSaveLRTo(const outliner::Candidate &C) const { 5697 assert(C.LRUWasSet && "LRU wasn't set?"); 5698 MachineFunction *MF = C.getMF(); 5699 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo *>( 5700 MF->getSubtarget().getRegisterInfo()); 5701 5702 BitVector regsReserved = ARI->getReservedRegs(*MF); 5703 // Check if there is an available register across the sequence that we can 5704 // use. 5705 for (unsigned Reg : ARM::rGPRRegClass) { 5706 if (!(Reg < regsReserved.size() && regsReserved.test(Reg)) && 5707 Reg != ARM::LR && // LR is not reserved, but don't use it. 5708 Reg != ARM::R12 && // R12 is not guaranteed to be preserved. 5709 C.LRU.available(Reg) && C.UsedInSequence.available(Reg)) 5710 return Reg; 5711 } 5712 5713 // No suitable register. Return 0. 5714 return 0u; 5715 } 5716 5717 outliner::OutlinedFunction ARMBaseInstrInfo::getOutliningCandidateInfo( 5718 std::vector<outliner::Candidate> &RepeatedSequenceLocs) const { 5719 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0]; 5720 unsigned SequenceSize = 5721 std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0, 5722 [this](unsigned Sum, const MachineInstr &MI) { 5723 return Sum + getInstSizeInBytes(MI); 5724 }); 5725 5726 // Properties about candidate MBBs that hold for all of them. 5727 unsigned FlagsSetInAll = 0xF; 5728 5729 // Compute liveness information for each candidate, and set FlagsSetInAll. 5730 const TargetRegisterInfo &TRI = getRegisterInfo(); 5731 std::for_each( 5732 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(), 5733 [&FlagsSetInAll](outliner::Candidate &C) { FlagsSetInAll &= C.Flags; }); 5734 5735 // According to the ARM Procedure Call Standard, the following are 5736 // undefined on entry/exit from a function call: 5737 // 5738 // * Register R12(IP), 5739 // * Condition codes (and thus the CPSR register) 5740 // 5741 // Since we control the instructions which are part of the outlined regions 5742 // we don't need to be fully compliant with the AAPCS, but we have to 5743 // guarantee that if a veneer is inserted at link time the code is still 5744 // correct. Because of this, we can't outline any sequence of instructions 5745 // where one of these registers is live into/across it. Thus, we need to 5746 // delete those candidates. 5747 auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) { 5748 // If the unsafe registers in this block are all dead, then we don't need 5749 // to compute liveness here. 5750 if (C.Flags & UnsafeRegsDead) 5751 return false; 5752 C.initLRU(TRI); 5753 LiveRegUnits LRU = C.LRU; 5754 return (!LRU.available(ARM::R12) || !LRU.available(ARM::CPSR)); 5755 }; 5756 5757 // Are there any candidates where those registers are live? 5758 if (!(FlagsSetInAll & UnsafeRegsDead)) { 5759 // Erase every candidate that violates the restrictions above. (It could be 5760 // true that we have viable candidates, so it's not worth bailing out in 5761 // the case that, say, 1 out of 20 candidates violate the restructions.) 5762 RepeatedSequenceLocs.erase(std::remove_if(RepeatedSequenceLocs.begin(), 5763 RepeatedSequenceLocs.end(), 5764 CantGuaranteeValueAcrossCall), 5765 RepeatedSequenceLocs.end()); 5766 5767 // If the sequence doesn't have enough candidates left, then we're done. 5768 if (RepeatedSequenceLocs.size() < 2) 5769 return outliner::OutlinedFunction(); 5770 } 5771 5772 // At this point, we have only "safe" candidates to outline. Figure out 5773 // frame + call instruction information. 5774 5775 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode(); 5776 5777 // Helper lambda which sets call information for every candidate. 5778 auto SetCandidateCallInfo = 5779 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) { 5780 for (outliner::Candidate &C : RepeatedSequenceLocs) 5781 C.setCallInfo(CallID, NumBytesForCall); 5782 }; 5783 5784 OutlinerCosts Costs(Subtarget); 5785 unsigned FrameID = MachineOutlinerDefault; 5786 unsigned NumBytesToCreateFrame = Costs.FrameDefault; 5787 5788 // If the last instruction in any candidate is a terminator, then we should 5789 // tail call all of the candidates. 5790 if (RepeatedSequenceLocs[0].back()->isTerminator()) { 5791 FrameID = MachineOutlinerTailCall; 5792 NumBytesToCreateFrame = Costs.FrameTailCall; 5793 SetCandidateCallInfo(MachineOutlinerTailCall, Costs.CallTailCall); 5794 } else if (LastInstrOpcode == ARM::BL || LastInstrOpcode == ARM::BLX || 5795 LastInstrOpcode == ARM::tBL || LastInstrOpcode == ARM::tBLXr || 5796 LastInstrOpcode == ARM::tBLXi) { 5797 FrameID = MachineOutlinerThunk; 5798 NumBytesToCreateFrame = Costs.FrameThunk; 5799 SetCandidateCallInfo(MachineOutlinerThunk, Costs.CallThunk); 5800 } else { 5801 // We need to decide how to emit calls + frames. We can always emit the same 5802 // frame if we don't need to save to the stack. If we have to save to the 5803 // stack, then we need a different frame. 5804 unsigned NumBytesNoStackCalls = 0; 5805 std::vector<outliner::Candidate> CandidatesWithoutStackFixups; 5806 5807 for (outliner::Candidate &C : RepeatedSequenceLocs) { 5808 C.initLRU(TRI); 5809 // Is LR available? If so, we don't need a save. 5810 if (C.LRU.available(ARM::LR)) { 5811 FrameID = MachineOutlinerNoLRSave; 5812 NumBytesNoStackCalls += Costs.CallNoLRSave; 5813 C.setCallInfo(MachineOutlinerNoLRSave, Costs.CallNoLRSave); 5814 CandidatesWithoutStackFixups.push_back(C); 5815 } 5816 5817 // Is an unused register available? If so, we won't modify the stack, so 5818 // we can outline with the same frame type as those that don't save LR. 5819 else if (findRegisterToSaveLRTo(C)) { 5820 FrameID = MachineOutlinerRegSave; 5821 NumBytesNoStackCalls += Costs.CallRegSave; 5822 C.setCallInfo(MachineOutlinerRegSave, Costs.CallRegSave); 5823 CandidatesWithoutStackFixups.push_back(C); 5824 } 5825 5826 // Is SP used in the sequence at all? If not, we don't have to modify 5827 // the stack, so we are guaranteed to get the same frame. 5828 else if (C.UsedInSequence.available(ARM::SP)) { 5829 NumBytesNoStackCalls += Costs.CallDefault; 5830 C.setCallInfo(MachineOutlinerDefault, Costs.CallDefault); 5831 SetCandidateCallInfo(MachineOutlinerDefault, Costs.CallDefault); 5832 CandidatesWithoutStackFixups.push_back(C); 5833 } 5834 else 5835 return outliner::OutlinedFunction(); 5836 } 5837 RepeatedSequenceLocs = CandidatesWithoutStackFixups; 5838 } 5839 5840 return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize, 5841 NumBytesToCreateFrame, FrameID); 5842 } 5843 5844 bool ARMBaseInstrInfo::isFunctionSafeToOutlineFrom( 5845 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const { 5846 const Function &F = MF.getFunction(); 5847 5848 // Can F be deduplicated by the linker? If it can, don't outline from it. 5849 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage()) 5850 return false; 5851 5852 // Don't outline from functions with section markings; the program could 5853 // expect that all the code is in the named section. 5854 // FIXME: Allow outlining from multiple functions with the same section 5855 // marking. 5856 if (F.hasSection()) 5857 return false; 5858 5859 // FIXME: Thumb1 outlining is not handled 5860 if (MF.getInfo<ARMFunctionInfo>()->isThumb1OnlyFunction()) 5861 return false; 5862 5863 // It's safe to outline from MF. 5864 return true; 5865 } 5866 5867 bool ARMBaseInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB, 5868 unsigned &Flags) const { 5869 // Check if LR is available through all of the MBB. If it's not, then set 5870 // a flag. 5871 assert(MBB.getParent()->getRegInfo().tracksLiveness() && 5872 "Suitable Machine Function for outlining must track liveness"); 5873 5874 LiveRegUnits LRU(getRegisterInfo()); 5875 5876 std::for_each(MBB.rbegin(), MBB.rend(), 5877 [&LRU](MachineInstr &MI) { LRU.accumulate(MI); }); 5878 5879 // Check if each of the unsafe registers are available... 5880 bool R12AvailableInBlock = LRU.available(ARM::R12); 5881 bool CPSRAvailableInBlock = LRU.available(ARM::CPSR); 5882 5883 // If all of these are dead (and not live out), we know we don't have to check 5884 // them later. 5885 if (R12AvailableInBlock && CPSRAvailableInBlock) 5886 Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead; 5887 5888 // Now, add the live outs to the set. 5889 LRU.addLiveOuts(MBB); 5890 5891 // If any of these registers is available in the MBB, but also a live out of 5892 // the block, then we know outlining is unsafe. 5893 if (R12AvailableInBlock && !LRU.available(ARM::R12)) 5894 return false; 5895 if (CPSRAvailableInBlock && !LRU.available(ARM::CPSR)) 5896 return false; 5897 5898 // Check if there's a call inside this MachineBasicBlock. If there is, then 5899 // set a flag. 5900 if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); })) 5901 Flags |= MachineOutlinerMBBFlags::HasCalls; 5902 5903 if (!LRU.available(ARM::LR)) 5904 Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere; 5905 5906 return true; 5907 } 5908 5909 outliner::InstrType 5910 ARMBaseInstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT, 5911 unsigned Flags) const { 5912 MachineInstr &MI = *MIT; 5913 const TargetRegisterInfo *TRI = &getRegisterInfo(); 5914 5915 // Be conservative with inline ASM 5916 if (MI.isInlineAsm()) 5917 return outliner::InstrType::Illegal; 5918 5919 // Don't allow debug values to impact outlining type. 5920 if (MI.isDebugInstr() || MI.isIndirectDebugValue()) 5921 return outliner::InstrType::Invisible; 5922 5923 // At this point, KILL or IMPLICIT_DEF instructions don't really tell us much 5924 // so we can go ahead and skip over them. 5925 if (MI.isKill() || MI.isImplicitDef()) 5926 return outliner::InstrType::Invisible; 5927 5928 // PIC instructions contain labels, outlining them would break offset 5929 // computing. unsigned Opc = MI.getOpcode(); 5930 unsigned Opc = MI.getOpcode(); 5931 if (Opc == ARM::tPICADD || Opc == ARM::PICADD || Opc == ARM::PICSTR || 5932 Opc == ARM::PICSTRB || Opc == ARM::PICSTRH || Opc == ARM::PICLDR || 5933 Opc == ARM::PICLDRB || Opc == ARM::PICLDRH || Opc == ARM::PICLDRSB || 5934 Opc == ARM::PICLDRSH || Opc == ARM::t2LDRpci_pic || 5935 Opc == ARM::t2MOVi16_ga_pcrel || Opc == ARM::t2MOVTi16_ga_pcrel || 5936 Opc == ARM::t2MOV_ga_pcrel) 5937 return outliner::InstrType::Illegal; 5938 5939 // Be conservative with ARMv8.1 MVE instructions. 5940 if (Opc == ARM::t2BF_LabelPseudo || Opc == ARM::t2DoLoopStart || 5941 Opc == ARM::t2WhileLoopStart || Opc == ARM::t2LoopDec || 5942 Opc == ARM::t2LoopEnd) 5943 return outliner::InstrType::Illegal; 5944 5945 const MCInstrDesc &MCID = MI.getDesc(); 5946 uint64_t MIFlags = MCID.TSFlags; 5947 if ((MIFlags & ARMII::DomainMask) == ARMII::DomainMVE) 5948 return outliner::InstrType::Illegal; 5949 5950 // Is this a terminator for a basic block? 5951 if (MI.isTerminator()) { 5952 // Don't outline if the branch is not unconditional. 5953 if (isPredicated(MI)) 5954 return outliner::InstrType::Illegal; 5955 5956 // Is this the end of a function? 5957 if (MI.getParent()->succ_empty()) 5958 return outliner::InstrType::Legal; 5959 5960 // It's not, so don't outline it. 5961 return outliner::InstrType::Illegal; 5962 } 5963 5964 // Make sure none of the operands are un-outlinable. 5965 for (const MachineOperand &MOP : MI.operands()) { 5966 if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() || 5967 MOP.isTargetIndex()) 5968 return outliner::InstrType::Illegal; 5969 } 5970 5971 // Don't outline if link register or program counter value are used. 5972 if (MI.readsRegister(ARM::LR, TRI) || MI.readsRegister(ARM::PC, TRI)) 5973 return outliner::InstrType::Illegal; 5974 5975 if (MI.isCall()) { 5976 // If we don't know anything about the callee, assume it depends on the 5977 // stack layout of the caller. In that case, it's only legal to outline 5978 // as a tail-call. Explicitly list the call instructions we know about so 5979 // we don't get unexpected results with call pseudo-instructions. 5980 auto UnknownCallOutlineType = outliner::InstrType::Illegal; 5981 if (Opc == ARM::BL || Opc == ARM::tBL || Opc == ARM::BLX || 5982 Opc == ARM::tBLXr || Opc == ARM::tBLXi) 5983 UnknownCallOutlineType = outliner::InstrType::LegalTerminator; 5984 5985 return UnknownCallOutlineType; 5986 } 5987 5988 // Since calls are handled, don't touch LR or PC 5989 if (MI.modifiesRegister(ARM::LR, TRI) || MI.modifiesRegister(ARM::PC, TRI)) 5990 return outliner::InstrType::Illegal; 5991 5992 // Does this use the stack? 5993 if (MI.modifiesRegister(ARM::SP, TRI) || MI.readsRegister(ARM::SP, TRI)) { 5994 // True if there is no chance that any outlined candidate from this range 5995 // could require stack fixups. That is, both 5996 // * LR is available in the range (No save/restore around call) 5997 // * The range doesn't include calls (No save/restore in outlined frame) 5998 // are true. 5999 // FIXME: This is very restrictive; the flags check the whole block, 6000 // not just the bit we will try to outline. 6001 bool MightNeedStackFixUp = 6002 (Flags & (MachineOutlinerMBBFlags::LRUnavailableSomewhere | 6003 MachineOutlinerMBBFlags::HasCalls)); 6004 6005 if (!MightNeedStackFixUp) 6006 return outliner::InstrType::Legal; 6007 6008 return outliner::InstrType::Illegal; 6009 } 6010 6011 // Be conservative with IT blocks. 6012 if (MI.readsRegister(ARM::ITSTATE, TRI) || 6013 MI.modifiesRegister(ARM::ITSTATE, TRI)) 6014 return outliner::InstrType::Illegal; 6015 6016 // Don't outline positions. 6017 if (MI.isPosition()) 6018 return outliner::InstrType::Illegal; 6019 6020 return outliner::InstrType::Legal; 6021 } 6022 6023 void ARMBaseInstrInfo::saveLROnStack(MachineBasicBlock &MBB, 6024 MachineBasicBlock::iterator &It) const { 6025 unsigned Opc = Subtarget.isThumb() ? ARM::t2STR_PRE : ARM::STR_PRE_IMM; 6026 int Align = -Subtarget.getStackAlignment().value(); 6027 BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::SP) 6028 .addReg(ARM::LR, RegState::Kill) 6029 .addReg(ARM::SP) 6030 .addImm(Align) 6031 .add(predOps(ARMCC::AL)); 6032 } 6033 6034 void ARMBaseInstrInfo::restoreLRFromStack( 6035 MachineBasicBlock &MBB, MachineBasicBlock::iterator &It) const { 6036 unsigned Opc = Subtarget.isThumb() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM; 6037 MachineInstrBuilder MIB = BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::LR) 6038 .addReg(ARM::SP, RegState::Define) 6039 .addReg(ARM::SP); 6040 if (!Subtarget.isThumb()) 6041 MIB.addReg(0); 6042 MIB.addImm(Subtarget.getStackAlignment().value()).add(predOps(ARMCC::AL)); 6043 } 6044 6045 void ARMBaseInstrInfo::buildOutlinedFrame( 6046 MachineBasicBlock &MBB, MachineFunction &MF, 6047 const outliner::OutlinedFunction &OF) const { 6048 // Nothing is needed for tail-calls. 6049 if (OF.FrameConstructionID == MachineOutlinerTailCall) 6050 return; 6051 6052 // For thunk outlining, rewrite the last instruction from a call to a 6053 // tail-call. 6054 if (OF.FrameConstructionID == MachineOutlinerThunk) { 6055 MachineInstr *Call = &*--MBB.instr_end(); 6056 bool isThumb = Subtarget.isThumb(); 6057 unsigned FuncOp = isThumb ? 2 : 0; 6058 unsigned Opc = Call->getOperand(FuncOp).isReg() 6059 ? isThumb ? ARM::tTAILJMPr : ARM::TAILJMPr 6060 : isThumb ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd 6061 : ARM::tTAILJMPdND 6062 : ARM::TAILJMPd; 6063 MachineInstrBuilder MIB = BuildMI(MBB, MBB.end(), DebugLoc(), get(Opc)) 6064 .add(Call->getOperand(FuncOp)); 6065 if (isThumb && !Call->getOperand(FuncOp).isReg()) 6066 MIB.add(predOps(ARMCC::AL)); 6067 Call->eraseFromParent(); 6068 return; 6069 } 6070 6071 // Here we have to insert the return ourselves. Get the correct opcode from 6072 // current feature set. 6073 BuildMI(MBB, MBB.end(), DebugLoc(), get(Subtarget.getReturnOpcode())) 6074 .add(predOps(ARMCC::AL)); 6075 } 6076 6077 MachineBasicBlock::iterator ARMBaseInstrInfo::insertOutlinedCall( 6078 Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It, 6079 MachineFunction &MF, const outliner::Candidate &C) const { 6080 MachineInstrBuilder MIB; 6081 MachineBasicBlock::iterator CallPt; 6082 unsigned Opc; 6083 bool isThumb = Subtarget.isThumb(); 6084 6085 // Are we tail calling? 6086 if (C.CallConstructionID == MachineOutlinerTailCall) { 6087 // If yes, then we can just branch to the label. 6088 Opc = isThumb 6089 ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND 6090 : ARM::TAILJMPd; 6091 MIB = BuildMI(MF, DebugLoc(), get(Opc)) 6092 .addGlobalAddress(M.getNamedValue(MF.getName())); 6093 if (isThumb) 6094 MIB.add(predOps(ARMCC::AL)); 6095 It = MBB.insert(It, MIB); 6096 return It; 6097 } 6098 6099 // Create the call instruction. 6100 Opc = isThumb ? ARM::tBL : ARM::BL; 6101 MachineInstrBuilder CallMIB = BuildMI(MF, DebugLoc(), get(Opc)); 6102 if (isThumb) 6103 CallMIB.add(predOps(ARMCC::AL)); 6104 CallMIB.addGlobalAddress(M.getNamedValue(MF.getName())); 6105 6106 if (C.CallConstructionID == MachineOutlinerNoLRSave || 6107 C.CallConstructionID == MachineOutlinerThunk) { 6108 // No, so just insert the call. 6109 It = MBB.insert(It, CallMIB); 6110 return It; 6111 } 6112 6113 // Can we save to a register? 6114 if (C.CallConstructionID == MachineOutlinerRegSave) { 6115 unsigned Reg = findRegisterToSaveLRTo(C); 6116 assert(Reg != 0 && "No callee-saved register available?"); 6117 6118 // Save and restore LR from that register. 6119 copyPhysReg(MBB, It, DebugLoc(), Reg, ARM::LR, true); 6120 CallPt = MBB.insert(It, CallMIB); 6121 copyPhysReg(MBB, It, DebugLoc(), ARM::LR, Reg, true); 6122 It--; 6123 return CallPt; 6124 } 6125 // We have the default case. Save and restore from SP. 6126 saveLROnStack(MBB, It); 6127 CallPt = MBB.insert(It, CallMIB); 6128 restoreLRFromStack(MBB, It); 6129 It--; 6130 return CallPt; 6131 } 6132 6133 bool ARMBaseInstrInfo::shouldOutlineFromFunctionByDefault( 6134 MachineFunction &MF) const { 6135 return Subtarget.isMClass() && MF.getFunction().hasMinSize(); 6136 } 6137 6138 bool ARMBaseInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI, 6139 AAResults *AA) const { 6140 // Try hard to rematerialize any VCTPs because if we spill P0, it will block 6141 // the tail predication conversion. This means that the element count 6142 // register has to be live for longer, but that has to be better than 6143 // spill/restore and VPT predication. 6144 return isVCTP(&MI) && !isPredicated(MI); 6145 } 6146