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