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