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