1 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the implementation of the FastISel class. 11 // 12 // "Fast" instruction selection is designed to emit very poor code quickly. 13 // Also, it is not designed to be able to do much lowering, so most illegal 14 // types (e.g. i64 on 32-bit targets) and operations are not supported. It is 15 // also not intended to be able to do much optimization, except in a few cases 16 // where doing optimizations reduces overall compile time. For example, folding 17 // constants into immediate fields is often done, because it's cheap and it 18 // reduces the number of instructions later phases have to examine. 19 // 20 // "Fast" instruction selection is able to fail gracefully and transfer 21 // control to the SelectionDAG selector for operations that it doesn't 22 // support. In many cases, this allows us to avoid duplicating a lot of 23 // the complicated lowering logic that SelectionDAG currently has. 24 // 25 // The intended use for "fast" instruction selection is "-O0" mode 26 // compilation, where the quality of the generated code is irrelevant when 27 // weighed against the speed at which the code can be generated. Also, 28 // at -O0, the LLVM optimizers are not running, and this makes the 29 // compile time of codegen a much higher portion of the overall compile 30 // time. Despite its limitations, "fast" instruction selection is able to 31 // handle enough code on its own to provide noticeable overall speedups 32 // in -O0 compiles. 33 // 34 // Basic operations are supported in a target-independent way, by reading 35 // the same instruction descriptions that the SelectionDAG selector reads, 36 // and identifying simple arithmetic operations that can be directly selected 37 // from simple operators. More complicated operations currently require 38 // target-specific code. 39 // 40 //===----------------------------------------------------------------------===// 41 42 #define DEBUG_TYPE "isel" 43 #include "llvm/CodeGen/FastISel.h" 44 #include "llvm/ADT/Statistic.h" 45 #include "llvm/Analysis/Loads.h" 46 #include "llvm/CodeGen/Analysis.h" 47 #include "llvm/CodeGen/FunctionLoweringInfo.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineRegisterInfo.h" 51 #include "llvm/DebugInfo.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GlobalVariable.h" 55 #include "llvm/IR/Instructions.h" 56 #include "llvm/IR/IntrinsicInst.h" 57 #include "llvm/IR/Operator.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/ErrorHandling.h" 60 #include "llvm/Target/TargetInstrInfo.h" 61 #include "llvm/Target/TargetLibraryInfo.h" 62 #include "llvm/Target/TargetLowering.h" 63 #include "llvm/Target/TargetMachine.h" 64 using namespace llvm; 65 66 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by " 67 "target-independent selector"); 68 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by " 69 "target-specific selector"); 70 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure"); 71 72 /// startNewBlock - Set the current block to which generated machine 73 /// instructions will be appended, and clear the local CSE map. 74 /// 75 void FastISel::startNewBlock() { 76 LocalValueMap.clear(); 77 78 // Instructions are appended to FuncInfo.MBB. If the basic block already 79 // contains labels or copies, use the last instruction as the last local 80 // value. 81 EmitStartPt = 0; 82 if (!FuncInfo.MBB->empty()) 83 EmitStartPt = &FuncInfo.MBB->back(); 84 LastLocalValue = EmitStartPt; 85 } 86 87 bool FastISel::LowerArguments() { 88 if (!FuncInfo.CanLowerReturn) 89 // Fallback to SDISel argument lowering code to deal with sret pointer 90 // parameter. 91 return false; 92 93 if (!FastLowerArguments()) 94 return false; 95 96 // Enter non-dead arguments into ValueMap for uses in non-entry BBs. 97 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(), 98 E = FuncInfo.Fn->arg_end(); I != E; ++I) { 99 if (!I->use_empty()) { 100 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I); 101 assert(VI != LocalValueMap.end() && "Missed an argument?"); 102 FuncInfo.ValueMap[I] = VI->second; 103 } 104 } 105 return true; 106 } 107 108 void FastISel::flushLocalValueMap() { 109 LocalValueMap.clear(); 110 LastLocalValue = EmitStartPt; 111 recomputeInsertPt(); 112 } 113 114 bool FastISel::hasTrivialKill(const Value *V) const { 115 // Don't consider constants or arguments to have trivial kills. 116 const Instruction *I = dyn_cast<Instruction>(V); 117 if (!I) 118 return false; 119 120 // No-op casts are trivially coalesced by fast-isel. 121 if (const CastInst *Cast = dyn_cast<CastInst>(I)) 122 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) && 123 !hasTrivialKill(Cast->getOperand(0))) 124 return false; 125 126 // GEPs with all zero indices are trivially coalesced by fast-isel. 127 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) 128 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0))) 129 return false; 130 131 // Only instructions with a single use in the same basic block are considered 132 // to have trivial kills. 133 return I->hasOneUse() && 134 !(I->getOpcode() == Instruction::BitCast || 135 I->getOpcode() == Instruction::PtrToInt || 136 I->getOpcode() == Instruction::IntToPtr) && 137 cast<Instruction>(*I->use_begin())->getParent() == I->getParent(); 138 } 139 140 unsigned FastISel::getRegForValue(const Value *V) { 141 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true); 142 // Don't handle non-simple values in FastISel. 143 if (!RealVT.isSimple()) 144 return 0; 145 146 // Ignore illegal types. We must do this before looking up the value 147 // in ValueMap because Arguments are given virtual registers regardless 148 // of whether FastISel can handle them. 149 MVT VT = RealVT.getSimpleVT(); 150 if (!TLI.isTypeLegal(VT)) { 151 // Handle integer promotions, though, because they're common and easy. 152 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16) 153 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT(); 154 else 155 return 0; 156 } 157 158 // Look up the value to see if we already have a register for it. 159 unsigned Reg = lookUpRegForValue(V); 160 if (Reg != 0) 161 return Reg; 162 163 // In bottom-up mode, just create the virtual register which will be used 164 // to hold the value. It will be materialized later. 165 if (isa<Instruction>(V) && 166 (!isa<AllocaInst>(V) || 167 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V)))) 168 return FuncInfo.InitializeRegForValue(V); 169 170 SavePoint SaveInsertPt = enterLocalValueArea(); 171 172 // Materialize the value in a register. Emit any instructions in the 173 // local value area. 174 Reg = materializeRegForValue(V, VT); 175 176 leaveLocalValueArea(SaveInsertPt); 177 178 return Reg; 179 } 180 181 /// materializeRegForValue - Helper for getRegForValue. This function is 182 /// called when the value isn't already available in a register and must 183 /// be materialized with new instructions. 184 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) { 185 unsigned Reg = 0; 186 187 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 188 if (CI->getValue().getActiveBits() <= 64) 189 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue()); 190 } else if (isa<AllocaInst>(V)) { 191 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V)); 192 } else if (isa<ConstantPointerNull>(V)) { 193 // Translate this as an integer zero so that it can be 194 // local-CSE'd with actual integer zeros. 195 Reg = 196 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext()))); 197 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) { 198 if (CF->isNullValue()) { 199 Reg = TargetMaterializeFloatZero(CF); 200 } else { 201 // Try to emit the constant directly. 202 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF); 203 } 204 205 if (!Reg) { 206 // Try to emit the constant by using an integer constant with a cast. 207 const APFloat &Flt = CF->getValueAPF(); 208 EVT IntVT = TLI.getPointerTy(); 209 210 uint64_t x[2]; 211 uint32_t IntBitWidth = IntVT.getSizeInBits(); 212 bool isExact; 213 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true, 214 APFloat::rmTowardZero, &isExact); 215 if (isExact) { 216 APInt IntVal(IntBitWidth, x); 217 218 unsigned IntegerReg = 219 getRegForValue(ConstantInt::get(V->getContext(), IntVal)); 220 if (IntegerReg != 0) 221 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, 222 IntegerReg, /*Kill=*/false); 223 } 224 } 225 } else if (const Operator *Op = dyn_cast<Operator>(V)) { 226 if (!SelectOperator(Op, Op->getOpcode())) 227 if (!isa<Instruction>(Op) || 228 !TargetSelectInstruction(cast<Instruction>(Op))) 229 return 0; 230 Reg = lookUpRegForValue(Op); 231 } else if (isa<UndefValue>(V)) { 232 Reg = createResultReg(TLI.getRegClassFor(VT)); 233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 234 TII.get(TargetOpcode::IMPLICIT_DEF), Reg); 235 } 236 237 // If target-independent code couldn't handle the value, give target-specific 238 // code a try. 239 if (!Reg && isa<Constant>(V)) 240 Reg = TargetMaterializeConstant(cast<Constant>(V)); 241 242 // Don't cache constant materializations in the general ValueMap. 243 // To do so would require tracking what uses they dominate. 244 if (Reg != 0) { 245 LocalValueMap[V] = Reg; 246 LastLocalValue = MRI.getVRegDef(Reg); 247 } 248 return Reg; 249 } 250 251 unsigned FastISel::lookUpRegForValue(const Value *V) { 252 // Look up the value to see if we already have a register for it. We 253 // cache values defined by Instructions across blocks, and other values 254 // only locally. This is because Instructions already have the SSA 255 // def-dominates-use requirement enforced. 256 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V); 257 if (I != FuncInfo.ValueMap.end()) 258 return I->second; 259 return LocalValueMap[V]; 260 } 261 262 /// UpdateValueMap - Update the value map to include the new mapping for this 263 /// instruction, or insert an extra copy to get the result in a previous 264 /// determined register. 265 /// NOTE: This is only necessary because we might select a block that uses 266 /// a value before we select the block that defines the value. It might be 267 /// possible to fix this by selecting blocks in reverse postorder. 268 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) { 269 if (!isa<Instruction>(I)) { 270 LocalValueMap[I] = Reg; 271 return; 272 } 273 274 unsigned &AssignedReg = FuncInfo.ValueMap[I]; 275 if (AssignedReg == 0) 276 // Use the new register. 277 AssignedReg = Reg; 278 else if (Reg != AssignedReg) { 279 // Arrange for uses of AssignedReg to be replaced by uses of Reg. 280 for (unsigned i = 0; i < NumRegs; i++) 281 FuncInfo.RegFixups[AssignedReg+i] = Reg+i; 282 283 AssignedReg = Reg; 284 } 285 } 286 287 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) { 288 unsigned IdxN = getRegForValue(Idx); 289 if (IdxN == 0) 290 // Unhandled operand. Halt "fast" selection and bail. 291 return std::pair<unsigned, bool>(0, false); 292 293 bool IdxNIsKill = hasTrivialKill(Idx); 294 295 // If the index is smaller or larger than intptr_t, truncate or extend it. 296 MVT PtrVT = TLI.getPointerTy(); 297 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false); 298 if (IdxVT.bitsLT(PtrVT)) { 299 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, 300 IdxN, IdxNIsKill); 301 IdxNIsKill = true; 302 } 303 else if (IdxVT.bitsGT(PtrVT)) { 304 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, 305 IdxN, IdxNIsKill); 306 IdxNIsKill = true; 307 } 308 return std::pair<unsigned, bool>(IdxN, IdxNIsKill); 309 } 310 311 void FastISel::recomputeInsertPt() { 312 if (getLastLocalValue()) { 313 FuncInfo.InsertPt = getLastLocalValue(); 314 FuncInfo.MBB = FuncInfo.InsertPt->getParent(); 315 ++FuncInfo.InsertPt; 316 } else 317 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI(); 318 319 // Now skip past any EH_LABELs, which must remain at the beginning. 320 while (FuncInfo.InsertPt != FuncInfo.MBB->end() && 321 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL) 322 ++FuncInfo.InsertPt; 323 } 324 325 void FastISel::removeDeadCode(MachineBasicBlock::iterator I, 326 MachineBasicBlock::iterator E) { 327 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!"); 328 while (I != E) { 329 MachineInstr *Dead = &*I; 330 ++I; 331 Dead->eraseFromParent(); 332 ++NumFastIselDead; 333 } 334 recomputeInsertPt(); 335 } 336 337 FastISel::SavePoint FastISel::enterLocalValueArea() { 338 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt; 339 DebugLoc OldDL = DL; 340 recomputeInsertPt(); 341 DL = DebugLoc(); 342 SavePoint SP = { OldInsertPt, OldDL }; 343 return SP; 344 } 345 346 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) { 347 if (FuncInfo.InsertPt != FuncInfo.MBB->begin()) 348 LastLocalValue = llvm::prior(FuncInfo.InsertPt); 349 350 // Restore the previous insert position. 351 FuncInfo.InsertPt = OldInsertPt.InsertPt; 352 DL = OldInsertPt.DL; 353 } 354 355 /// SelectBinaryOp - Select and emit code for a binary operator instruction, 356 /// which has an opcode which directly corresponds to the given ISD opcode. 357 /// 358 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) { 359 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true); 360 if (VT == MVT::Other || !VT.isSimple()) 361 // Unhandled type. Halt "fast" selection and bail. 362 return false; 363 364 // We only handle legal types. For example, on x86-32 the instruction 365 // selector contains all of the 64-bit instructions from x86-64, 366 // under the assumption that i64 won't be used if the target doesn't 367 // support it. 368 if (!TLI.isTypeLegal(VT)) { 369 // MVT::i1 is special. Allow AND, OR, or XOR because they 370 // don't require additional zeroing, which makes them easy. 371 if (VT == MVT::i1 && 372 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR || 373 ISDOpcode == ISD::XOR)) 374 VT = TLI.getTypeToTransformTo(I->getContext(), VT); 375 else 376 return false; 377 } 378 379 // Check if the first operand is a constant, and handle it as "ri". At -O0, 380 // we don't have anything that canonicalizes operand order. 381 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0))) 382 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) { 383 unsigned Op1 = getRegForValue(I->getOperand(1)); 384 if (Op1 == 0) return false; 385 386 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 387 388 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, 389 Op1IsKill, CI->getZExtValue(), 390 VT.getSimpleVT()); 391 if (ResultReg == 0) return false; 392 393 // We successfully emitted code for the given LLVM Instruction. 394 UpdateValueMap(I, ResultReg); 395 return true; 396 } 397 398 399 unsigned Op0 = getRegForValue(I->getOperand(0)); 400 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail. 401 return false; 402 403 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 404 405 // Check if the second operand is a constant and handle it appropriately. 406 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 407 uint64_t Imm = CI->getZExtValue(); 408 409 // Transform "sdiv exact X, 8" -> "sra X, 3". 410 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) && 411 cast<BinaryOperator>(I)->isExact() && 412 isPowerOf2_64(Imm)) { 413 Imm = Log2_64(Imm); 414 ISDOpcode = ISD::SRA; 415 } 416 417 // Transform "urem x, pow2" -> "and x, pow2-1". 418 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) && 419 isPowerOf2_64(Imm)) { 420 --Imm; 421 ISDOpcode = ISD::AND; 422 } 423 424 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0, 425 Op0IsKill, Imm, VT.getSimpleVT()); 426 if (ResultReg == 0) return false; 427 428 // We successfully emitted code for the given LLVM Instruction. 429 UpdateValueMap(I, ResultReg); 430 return true; 431 } 432 433 // Check if the second operand is a constant float. 434 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) { 435 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(), 436 ISDOpcode, Op0, Op0IsKill, CF); 437 if (ResultReg != 0) { 438 // We successfully emitted code for the given LLVM Instruction. 439 UpdateValueMap(I, ResultReg); 440 return true; 441 } 442 } 443 444 unsigned Op1 = getRegForValue(I->getOperand(1)); 445 if (Op1 == 0) 446 // Unhandled operand. Halt "fast" selection and bail. 447 return false; 448 449 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 450 451 // Now we have both operands in registers. Emit the instruction. 452 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(), 453 ISDOpcode, 454 Op0, Op0IsKill, 455 Op1, Op1IsKill); 456 if (ResultReg == 0) 457 // Target-specific code wasn't able to find a machine opcode for 458 // the given ISD opcode and type. Halt "fast" selection and bail. 459 return false; 460 461 // We successfully emitted code for the given LLVM Instruction. 462 UpdateValueMap(I, ResultReg); 463 return true; 464 } 465 466 bool FastISel::SelectGetElementPtr(const User *I) { 467 unsigned N = getRegForValue(I->getOperand(0)); 468 if (N == 0) 469 // Unhandled operand. Halt "fast" selection and bail. 470 return false; 471 472 bool NIsKill = hasTrivialKill(I->getOperand(0)); 473 474 // Keep a running tab of the total offset to coalesce multiple N = N + Offset 475 // into a single N = N + TotalOffset. 476 uint64_t TotalOffs = 0; 477 // FIXME: What's a good SWAG number for MaxOffs? 478 uint64_t MaxOffs = 2048; 479 Type *Ty = I->getOperand(0)->getType(); 480 MVT VT = TLI.getPointerTy(); 481 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1, 482 E = I->op_end(); OI != E; ++OI) { 483 const Value *Idx = *OI; 484 if (StructType *StTy = dyn_cast<StructType>(Ty)) { 485 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 486 if (Field) { 487 // N = N + Offset 488 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field); 489 if (TotalOffs >= MaxOffs) { 490 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 491 if (N == 0) 492 // Unhandled operand. Halt "fast" selection and bail. 493 return false; 494 NIsKill = true; 495 TotalOffs = 0; 496 } 497 } 498 Ty = StTy->getElementType(Field); 499 } else { 500 Ty = cast<SequentialType>(Ty)->getElementType(); 501 502 // If this is a constant subscript, handle it quickly. 503 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 504 if (CI->isZero()) continue; 505 // N = N + Offset 506 TotalOffs += 507 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 508 if (TotalOffs >= MaxOffs) { 509 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 510 if (N == 0) 511 // Unhandled operand. Halt "fast" selection and bail. 512 return false; 513 NIsKill = true; 514 TotalOffs = 0; 515 } 516 continue; 517 } 518 if (TotalOffs) { 519 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 520 if (N == 0) 521 // Unhandled operand. Halt "fast" selection and bail. 522 return false; 523 NIsKill = true; 524 TotalOffs = 0; 525 } 526 527 // N = N + Idx * ElementSize; 528 uint64_t ElementSize = TD.getTypeAllocSize(Ty); 529 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx); 530 unsigned IdxN = Pair.first; 531 bool IdxNIsKill = Pair.second; 532 if (IdxN == 0) 533 // Unhandled operand. Halt "fast" selection and bail. 534 return false; 535 536 if (ElementSize != 1) { 537 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT); 538 if (IdxN == 0) 539 // Unhandled operand. Halt "fast" selection and bail. 540 return false; 541 IdxNIsKill = true; 542 } 543 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill); 544 if (N == 0) 545 // Unhandled operand. Halt "fast" selection and bail. 546 return false; 547 } 548 } 549 if (TotalOffs) { 550 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 551 if (N == 0) 552 // Unhandled operand. Halt "fast" selection and bail. 553 return false; 554 } 555 556 // We successfully emitted code for the given LLVM Instruction. 557 UpdateValueMap(I, N); 558 return true; 559 } 560 561 bool FastISel::SelectCall(const User *I) { 562 const CallInst *Call = cast<CallInst>(I); 563 564 // Handle simple inline asms. 565 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) { 566 // Don't attempt to handle constraints. 567 if (!IA->getConstraintString().empty()) 568 return false; 569 570 unsigned ExtraInfo = 0; 571 if (IA->hasSideEffects()) 572 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 573 if (IA->isAlignStack()) 574 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 575 576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 577 TII.get(TargetOpcode::INLINEASM)) 578 .addExternalSymbol(IA->getAsmString().c_str()) 579 .addImm(ExtraInfo); 580 return true; 581 } 582 583 MachineModuleInfo &MMI = FuncInfo.MF->getMMI(); 584 ComputeUsesVAFloatArgument(*Call, &MMI); 585 586 const Function *F = Call->getCalledFunction(); 587 if (!F) return false; 588 589 // Handle selected intrinsic function calls. 590 switch (F->getIntrinsicID()) { 591 default: break; 592 // At -O0 we don't care about the lifetime intrinsics. 593 case Intrinsic::lifetime_start: 594 case Intrinsic::lifetime_end: 595 // The donothing intrinsic does, well, nothing. 596 case Intrinsic::donothing: 597 return true; 598 599 case Intrinsic::dbg_declare: { 600 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call); 601 if (!DIVariable(DI->getVariable()).Verify() || 602 !FuncInfo.MF->getMMI().hasDebugInfo()) { 603 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 604 return true; 605 } 606 607 const Value *Address = DI->getAddress(); 608 if (!Address || isa<UndefValue>(Address)) { 609 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 610 return true; 611 } 612 613 unsigned Reg = 0; 614 unsigned Offset = 0; 615 if (const Argument *Arg = dyn_cast<Argument>(Address)) { 616 // Some arguments' frame index is recorded during argument lowering. 617 Offset = FuncInfo.getArgumentFrameIndex(Arg); 618 if (Offset) 619 Reg = TRI.getFrameRegister(*FuncInfo.MF); 620 } 621 if (!Reg) 622 Reg = lookUpRegForValue(Address); 623 624 // If we have a VLA that has a "use" in a metadata node that's then used 625 // here but it has no other uses, then we have a problem. E.g., 626 // 627 // int foo (const int *x) { 628 // char a[*x]; 629 // return 0; 630 // } 631 // 632 // If we assign 'a' a vreg and fast isel later on has to use the selection 633 // DAG isel, it will want to copy the value to the vreg. However, there are 634 // no uses, which goes counter to what selection DAG isel expects. 635 if (!Reg && !Address->use_empty() && isa<Instruction>(Address) && 636 (!isa<AllocaInst>(Address) || 637 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address)))) 638 Reg = FuncInfo.InitializeRegForValue(Address); 639 640 if (Reg) 641 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 642 TII.get(TargetOpcode::DBG_VALUE)) 643 .addReg(Reg, RegState::Debug).addImm(Offset) 644 .addMetadata(DI->getVariable()); 645 else 646 // We can't yet handle anything else here because it would require 647 // generating code, thus altering codegen because of debug info. 648 DEBUG(dbgs() << "Dropping debug info for " << DI); 649 return true; 650 } 651 case Intrinsic::dbg_value: { 652 // This form of DBG_VALUE is target-independent. 653 const DbgValueInst *DI = cast<DbgValueInst>(Call); 654 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 655 const Value *V = DI->getValue(); 656 if (!V) { 657 // Currently the optimizer can produce this; insert an undef to 658 // help debugging. Probably the optimizer should not do this. 659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 660 .addReg(0U).addImm(DI->getOffset()) 661 .addMetadata(DI->getVariable()); 662 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 663 if (CI->getBitWidth() > 64) 664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 665 .addCImm(CI).addImm(DI->getOffset()) 666 .addMetadata(DI->getVariable()); 667 else 668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 669 .addImm(CI->getZExtValue()).addImm(DI->getOffset()) 670 .addMetadata(DI->getVariable()); 671 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) { 672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 673 .addFPImm(CF).addImm(DI->getOffset()) 674 .addMetadata(DI->getVariable()); 675 } else if (unsigned Reg = lookUpRegForValue(V)) { 676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 677 .addReg(Reg, RegState::Debug).addImm(DI->getOffset()) 678 .addMetadata(DI->getVariable()); 679 } else { 680 // We can't yet handle anything else here because it would require 681 // generating code, thus altering codegen because of debug info. 682 DEBUG(dbgs() << "Dropping debug info for " << DI); 683 } 684 return true; 685 } 686 case Intrinsic::objectsize: { 687 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1)); 688 unsigned long long Res = CI->isZero() ? -1ULL : 0; 689 Constant *ResCI = ConstantInt::get(Call->getType(), Res); 690 unsigned ResultReg = getRegForValue(ResCI); 691 if (ResultReg == 0) 692 return false; 693 UpdateValueMap(Call, ResultReg); 694 return true; 695 } 696 case Intrinsic::expect: { 697 unsigned ResultReg = getRegForValue(Call->getArgOperand(0)); 698 if (ResultReg == 0) 699 return false; 700 UpdateValueMap(Call, ResultReg); 701 return true; 702 } 703 } 704 705 // Usually, it does not make sense to initialize a value, 706 // make an unrelated function call and use the value, because 707 // it tends to be spilled on the stack. So, we move the pointer 708 // to the last local value to the beginning of the block, so that 709 // all the values which have already been materialized, 710 // appear after the call. It also makes sense to skip intrinsics 711 // since they tend to be inlined. 712 if (!isa<IntrinsicInst>(Call)) 713 flushLocalValueMap(); 714 715 // An arbitrary call. Bail. 716 return false; 717 } 718 719 bool FastISel::SelectCast(const User *I, unsigned Opcode) { 720 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 721 EVT DstVT = TLI.getValueType(I->getType()); 722 723 if (SrcVT == MVT::Other || !SrcVT.isSimple() || 724 DstVT == MVT::Other || !DstVT.isSimple()) 725 // Unhandled type. Halt "fast" selection and bail. 726 return false; 727 728 // Check if the destination type is legal. 729 if (!TLI.isTypeLegal(DstVT)) 730 return false; 731 732 // Check if the source operand is legal. 733 if (!TLI.isTypeLegal(SrcVT)) 734 return false; 735 736 unsigned InputReg = getRegForValue(I->getOperand(0)); 737 if (!InputReg) 738 // Unhandled operand. Halt "fast" selection and bail. 739 return false; 740 741 bool InputRegIsKill = hasTrivialKill(I->getOperand(0)); 742 743 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(), 744 DstVT.getSimpleVT(), 745 Opcode, 746 InputReg, InputRegIsKill); 747 if (!ResultReg) 748 return false; 749 750 UpdateValueMap(I, ResultReg); 751 return true; 752 } 753 754 bool FastISel::SelectBitCast(const User *I) { 755 // If the bitcast doesn't change the type, just use the operand value. 756 if (I->getType() == I->getOperand(0)->getType()) { 757 unsigned Reg = getRegForValue(I->getOperand(0)); 758 if (Reg == 0) 759 return false; 760 UpdateValueMap(I, Reg); 761 return true; 762 } 763 764 // Bitcasts of other values become reg-reg copies or BITCAST operators. 765 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType()); 766 EVT DstEVT = TLI.getValueType(I->getType()); 767 if (SrcEVT == MVT::Other || DstEVT == MVT::Other || 768 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT)) 769 // Unhandled type. Halt "fast" selection and bail. 770 return false; 771 772 MVT SrcVT = SrcEVT.getSimpleVT(); 773 MVT DstVT = DstEVT.getSimpleVT(); 774 unsigned Op0 = getRegForValue(I->getOperand(0)); 775 if (Op0 == 0) 776 // Unhandled operand. Halt "fast" selection and bail. 777 return false; 778 779 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 780 781 // First, try to perform the bitcast by inserting a reg-reg copy. 782 unsigned ResultReg = 0; 783 if (SrcVT == DstVT) { 784 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT); 785 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT); 786 // Don't attempt a cross-class copy. It will likely fail. 787 if (SrcClass == DstClass) { 788 ResultReg = createResultReg(DstClass); 789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 790 ResultReg).addReg(Op0); 791 } 792 } 793 794 // If the reg-reg copy failed, select a BITCAST opcode. 795 if (!ResultReg) 796 ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill); 797 798 if (!ResultReg) 799 return false; 800 801 UpdateValueMap(I, ResultReg); 802 return true; 803 } 804 805 bool 806 FastISel::SelectInstruction(const Instruction *I) { 807 // Just before the terminator instruction, insert instructions to 808 // feed PHI nodes in successor blocks. 809 if (isa<TerminatorInst>(I)) 810 if (!HandlePHINodesInSuccessorBlocks(I->getParent())) 811 return false; 812 813 DL = I->getDebugLoc(); 814 815 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt; 816 817 // As a special case, don't handle calls to builtin library functions that 818 // may be translated directly to target instructions. 819 if (const CallInst *Call = dyn_cast<CallInst>(I)) { 820 const Function *F = Call->getCalledFunction(); 821 LibFunc::Func Func; 822 if (F && !F->hasLocalLinkage() && F->hasName() && 823 LibInfo->getLibFunc(F->getName(), Func) && 824 LibInfo->hasOptimizedCodeGen(Func)) 825 return false; 826 } 827 828 // First, try doing target-independent selection. 829 if (SelectOperator(I, I->getOpcode())) { 830 ++NumFastIselSuccessIndependent; 831 DL = DebugLoc(); 832 return true; 833 } 834 // Remove dead code. However, ignore call instructions since we've flushed 835 // the local value map and recomputed the insert point. 836 if (!isa<CallInst>(I)) { 837 recomputeInsertPt(); 838 if (SavedInsertPt != FuncInfo.InsertPt) 839 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 840 } 841 842 // Next, try calling the target to attempt to handle the instruction. 843 SavedInsertPt = FuncInfo.InsertPt; 844 if (TargetSelectInstruction(I)) { 845 ++NumFastIselSuccessTarget; 846 DL = DebugLoc(); 847 return true; 848 } 849 // Check for dead code and remove as necessary. 850 recomputeInsertPt(); 851 if (SavedInsertPt != FuncInfo.InsertPt) 852 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 853 854 DL = DebugLoc(); 855 return false; 856 } 857 858 /// FastEmitBranch - Emit an unconditional branch to the given block, 859 /// unless it is the immediate (fall-through) successor, and update 860 /// the CFG. 861 void 862 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) { 863 864 if (FuncInfo.MBB->getBasicBlock()->size() > 1 && 865 FuncInfo.MBB->isLayoutSuccessor(MSucc)) { 866 // For more accurate line information if this is the only instruction 867 // in the block then emit it, otherwise we have the unconditional 868 // fall-through case, which needs no instructions. 869 } else { 870 // The unconditional branch case. 871 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL, 872 SmallVector<MachineOperand, 0>(), DL); 873 } 874 FuncInfo.MBB->addSuccessor(MSucc); 875 } 876 877 /// SelectFNeg - Emit an FNeg operation. 878 /// 879 bool 880 FastISel::SelectFNeg(const User *I) { 881 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I)); 882 if (OpReg == 0) return false; 883 884 bool OpRegIsKill = hasTrivialKill(I); 885 886 // If the target has ISD::FNEG, use it. 887 EVT VT = TLI.getValueType(I->getType()); 888 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), 889 ISD::FNEG, OpReg, OpRegIsKill); 890 if (ResultReg != 0) { 891 UpdateValueMap(I, ResultReg); 892 return true; 893 } 894 895 // Bitcast the value to integer, twiddle the sign bit with xor, 896 // and then bitcast it back to floating-point. 897 if (VT.getSizeInBits() > 64) return false; 898 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits()); 899 if (!TLI.isTypeLegal(IntVT)) 900 return false; 901 902 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(), 903 ISD::BITCAST, OpReg, OpRegIsKill); 904 if (IntReg == 0) 905 return false; 906 907 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR, 908 IntReg, /*Kill=*/true, 909 UINT64_C(1) << (VT.getSizeInBits()-1), 910 IntVT.getSimpleVT()); 911 if (IntResultReg == 0) 912 return false; 913 914 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), 915 ISD::BITCAST, IntResultReg, /*Kill=*/true); 916 if (ResultReg == 0) 917 return false; 918 919 UpdateValueMap(I, ResultReg); 920 return true; 921 } 922 923 bool 924 FastISel::SelectExtractValue(const User *U) { 925 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U); 926 if (!EVI) 927 return false; 928 929 // Make sure we only try to handle extracts with a legal result. But also 930 // allow i1 because it's easy. 931 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true); 932 if (!RealVT.isSimple()) 933 return false; 934 MVT VT = RealVT.getSimpleVT(); 935 if (!TLI.isTypeLegal(VT) && VT != MVT::i1) 936 return false; 937 938 const Value *Op0 = EVI->getOperand(0); 939 Type *AggTy = Op0->getType(); 940 941 // Get the base result register. 942 unsigned ResultReg; 943 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0); 944 if (I != FuncInfo.ValueMap.end()) 945 ResultReg = I->second; 946 else if (isa<Instruction>(Op0)) 947 ResultReg = FuncInfo.InitializeRegForValue(Op0); 948 else 949 return false; // fast-isel can't handle aggregate constants at the moment 950 951 // Get the actual result register, which is an offset from the base register. 952 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices()); 953 954 SmallVector<EVT, 4> AggValueVTs; 955 ComputeValueVTs(TLI, AggTy, AggValueVTs); 956 957 for (unsigned i = 0; i < VTIndex; i++) 958 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]); 959 960 UpdateValueMap(EVI, ResultReg); 961 return true; 962 } 963 964 bool 965 FastISel::SelectOperator(const User *I, unsigned Opcode) { 966 switch (Opcode) { 967 case Instruction::Add: 968 return SelectBinaryOp(I, ISD::ADD); 969 case Instruction::FAdd: 970 return SelectBinaryOp(I, ISD::FADD); 971 case Instruction::Sub: 972 return SelectBinaryOp(I, ISD::SUB); 973 case Instruction::FSub: 974 // FNeg is currently represented in LLVM IR as a special case of FSub. 975 if (BinaryOperator::isFNeg(I)) 976 return SelectFNeg(I); 977 return SelectBinaryOp(I, ISD::FSUB); 978 case Instruction::Mul: 979 return SelectBinaryOp(I, ISD::MUL); 980 case Instruction::FMul: 981 return SelectBinaryOp(I, ISD::FMUL); 982 case Instruction::SDiv: 983 return SelectBinaryOp(I, ISD::SDIV); 984 case Instruction::UDiv: 985 return SelectBinaryOp(I, ISD::UDIV); 986 case Instruction::FDiv: 987 return SelectBinaryOp(I, ISD::FDIV); 988 case Instruction::SRem: 989 return SelectBinaryOp(I, ISD::SREM); 990 case Instruction::URem: 991 return SelectBinaryOp(I, ISD::UREM); 992 case Instruction::FRem: 993 return SelectBinaryOp(I, ISD::FREM); 994 case Instruction::Shl: 995 return SelectBinaryOp(I, ISD::SHL); 996 case Instruction::LShr: 997 return SelectBinaryOp(I, ISD::SRL); 998 case Instruction::AShr: 999 return SelectBinaryOp(I, ISD::SRA); 1000 case Instruction::And: 1001 return SelectBinaryOp(I, ISD::AND); 1002 case Instruction::Or: 1003 return SelectBinaryOp(I, ISD::OR); 1004 case Instruction::Xor: 1005 return SelectBinaryOp(I, ISD::XOR); 1006 1007 case Instruction::GetElementPtr: 1008 return SelectGetElementPtr(I); 1009 1010 case Instruction::Br: { 1011 const BranchInst *BI = cast<BranchInst>(I); 1012 1013 if (BI->isUnconditional()) { 1014 const BasicBlock *LLVMSucc = BI->getSuccessor(0); 1015 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc]; 1016 FastEmitBranch(MSucc, BI->getDebugLoc()); 1017 return true; 1018 } 1019 1020 // Conditional branches are not handed yet. 1021 // Halt "fast" selection and bail. 1022 return false; 1023 } 1024 1025 case Instruction::Unreachable: 1026 // Nothing to emit. 1027 return true; 1028 1029 case Instruction::Alloca: 1030 // FunctionLowering has the static-sized case covered. 1031 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I))) 1032 return true; 1033 1034 // Dynamic-sized alloca is not handled yet. 1035 return false; 1036 1037 case Instruction::Call: 1038 return SelectCall(I); 1039 1040 case Instruction::BitCast: 1041 return SelectBitCast(I); 1042 1043 case Instruction::FPToSI: 1044 return SelectCast(I, ISD::FP_TO_SINT); 1045 case Instruction::ZExt: 1046 return SelectCast(I, ISD::ZERO_EXTEND); 1047 case Instruction::SExt: 1048 return SelectCast(I, ISD::SIGN_EXTEND); 1049 case Instruction::Trunc: 1050 return SelectCast(I, ISD::TRUNCATE); 1051 case Instruction::SIToFP: 1052 return SelectCast(I, ISD::SINT_TO_FP); 1053 1054 case Instruction::IntToPtr: // Deliberate fall-through. 1055 case Instruction::PtrToInt: { 1056 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 1057 EVT DstVT = TLI.getValueType(I->getType()); 1058 if (DstVT.bitsGT(SrcVT)) 1059 return SelectCast(I, ISD::ZERO_EXTEND); 1060 if (DstVT.bitsLT(SrcVT)) 1061 return SelectCast(I, ISD::TRUNCATE); 1062 unsigned Reg = getRegForValue(I->getOperand(0)); 1063 if (Reg == 0) return false; 1064 UpdateValueMap(I, Reg); 1065 return true; 1066 } 1067 1068 case Instruction::ExtractValue: 1069 return SelectExtractValue(I); 1070 1071 case Instruction::PHI: 1072 llvm_unreachable("FastISel shouldn't visit PHI nodes!"); 1073 1074 default: 1075 // Unhandled instruction. Halt "fast" selection and bail. 1076 return false; 1077 } 1078 } 1079 1080 FastISel::FastISel(FunctionLoweringInfo &funcInfo, 1081 const TargetLibraryInfo *libInfo) 1082 : FuncInfo(funcInfo), 1083 MRI(FuncInfo.MF->getRegInfo()), 1084 MFI(*FuncInfo.MF->getFrameInfo()), 1085 MCP(*FuncInfo.MF->getConstantPool()), 1086 TM(FuncInfo.MF->getTarget()), 1087 TD(*TM.getDataLayout()), 1088 TII(*TM.getInstrInfo()), 1089 TLI(*TM.getTargetLowering()), 1090 TRI(*TM.getRegisterInfo()), 1091 LibInfo(libInfo) { 1092 } 1093 1094 FastISel::~FastISel() {} 1095 1096 bool FastISel::FastLowerArguments() { 1097 return false; 1098 } 1099 1100 unsigned FastISel::FastEmit_(MVT, MVT, 1101 unsigned) { 1102 return 0; 1103 } 1104 1105 unsigned FastISel::FastEmit_r(MVT, MVT, 1106 unsigned, 1107 unsigned /*Op0*/, bool /*Op0IsKill*/) { 1108 return 0; 1109 } 1110 1111 unsigned FastISel::FastEmit_rr(MVT, MVT, 1112 unsigned, 1113 unsigned /*Op0*/, bool /*Op0IsKill*/, 1114 unsigned /*Op1*/, bool /*Op1IsKill*/) { 1115 return 0; 1116 } 1117 1118 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) { 1119 return 0; 1120 } 1121 1122 unsigned FastISel::FastEmit_f(MVT, MVT, 1123 unsigned, const ConstantFP * /*FPImm*/) { 1124 return 0; 1125 } 1126 1127 unsigned FastISel::FastEmit_ri(MVT, MVT, 1128 unsigned, 1129 unsigned /*Op0*/, bool /*Op0IsKill*/, 1130 uint64_t /*Imm*/) { 1131 return 0; 1132 } 1133 1134 unsigned FastISel::FastEmit_rf(MVT, MVT, 1135 unsigned, 1136 unsigned /*Op0*/, bool /*Op0IsKill*/, 1137 const ConstantFP * /*FPImm*/) { 1138 return 0; 1139 } 1140 1141 unsigned FastISel::FastEmit_rri(MVT, MVT, 1142 unsigned, 1143 unsigned /*Op0*/, bool /*Op0IsKill*/, 1144 unsigned /*Op1*/, bool /*Op1IsKill*/, 1145 uint64_t /*Imm*/) { 1146 return 0; 1147 } 1148 1149 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries 1150 /// to emit an instruction with an immediate operand using FastEmit_ri. 1151 /// If that fails, it materializes the immediate into a register and try 1152 /// FastEmit_rr instead. 1153 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode, 1154 unsigned Op0, bool Op0IsKill, 1155 uint64_t Imm, MVT ImmType) { 1156 // If this is a multiply by a power of two, emit this as a shift left. 1157 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) { 1158 Opcode = ISD::SHL; 1159 Imm = Log2_64(Imm); 1160 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) { 1161 // div x, 8 -> srl x, 3 1162 Opcode = ISD::SRL; 1163 Imm = Log2_64(Imm); 1164 } 1165 1166 // Horrible hack (to be removed), check to make sure shift amounts are 1167 // in-range. 1168 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) && 1169 Imm >= VT.getSizeInBits()) 1170 return 0; 1171 1172 // First check if immediate type is legal. If not, we can't use the ri form. 1173 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm); 1174 if (ResultReg != 0) 1175 return ResultReg; 1176 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm); 1177 if (MaterialReg == 0) { 1178 // This is a bit ugly/slow, but failing here means falling out of 1179 // fast-isel, which would be very slow. 1180 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(), 1181 VT.getSizeInBits()); 1182 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm)); 1183 assert (MaterialReg != 0 && "Unable to materialize imm."); 1184 if (MaterialReg == 0) return 0; 1185 } 1186 return FastEmit_rr(VT, VT, Opcode, 1187 Op0, Op0IsKill, 1188 MaterialReg, /*Kill=*/true); 1189 } 1190 1191 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) { 1192 return MRI.createVirtualRegister(RC); 1193 } 1194 1195 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode, 1196 const TargetRegisterClass* RC) { 1197 unsigned ResultReg = createResultReg(RC); 1198 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1199 1200 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg); 1201 return ResultReg; 1202 } 1203 1204 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode, 1205 const TargetRegisterClass *RC, 1206 unsigned Op0, bool Op0IsKill) { 1207 unsigned ResultReg = createResultReg(RC); 1208 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1209 1210 if (II.getNumDefs() >= 1) 1211 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1212 .addReg(Op0, Op0IsKill * RegState::Kill); 1213 else { 1214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1215 .addReg(Op0, Op0IsKill * RegState::Kill); 1216 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1217 ResultReg).addReg(II.ImplicitDefs[0]); 1218 } 1219 1220 return ResultReg; 1221 } 1222 1223 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode, 1224 const TargetRegisterClass *RC, 1225 unsigned Op0, bool Op0IsKill, 1226 unsigned Op1, bool Op1IsKill) { 1227 unsigned ResultReg = createResultReg(RC); 1228 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1229 1230 if (II.getNumDefs() >= 1) 1231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1232 .addReg(Op0, Op0IsKill * RegState::Kill) 1233 .addReg(Op1, Op1IsKill * RegState::Kill); 1234 else { 1235 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1236 .addReg(Op0, Op0IsKill * RegState::Kill) 1237 .addReg(Op1, Op1IsKill * RegState::Kill); 1238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1239 ResultReg).addReg(II.ImplicitDefs[0]); 1240 } 1241 return ResultReg; 1242 } 1243 1244 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode, 1245 const TargetRegisterClass *RC, 1246 unsigned Op0, bool Op0IsKill, 1247 unsigned Op1, bool Op1IsKill, 1248 unsigned Op2, bool Op2IsKill) { 1249 unsigned ResultReg = createResultReg(RC); 1250 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1251 1252 if (II.getNumDefs() >= 1) 1253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1254 .addReg(Op0, Op0IsKill * RegState::Kill) 1255 .addReg(Op1, Op1IsKill * RegState::Kill) 1256 .addReg(Op2, Op2IsKill * RegState::Kill); 1257 else { 1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1259 .addReg(Op0, Op0IsKill * RegState::Kill) 1260 .addReg(Op1, Op1IsKill * RegState::Kill) 1261 .addReg(Op2, Op2IsKill * RegState::Kill); 1262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1263 ResultReg).addReg(II.ImplicitDefs[0]); 1264 } 1265 return ResultReg; 1266 } 1267 1268 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode, 1269 const TargetRegisterClass *RC, 1270 unsigned Op0, bool Op0IsKill, 1271 uint64_t Imm) { 1272 unsigned ResultReg = createResultReg(RC); 1273 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1274 1275 if (II.getNumDefs() >= 1) 1276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1277 .addReg(Op0, Op0IsKill * RegState::Kill) 1278 .addImm(Imm); 1279 else { 1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1281 .addReg(Op0, Op0IsKill * RegState::Kill) 1282 .addImm(Imm); 1283 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1284 ResultReg).addReg(II.ImplicitDefs[0]); 1285 } 1286 return ResultReg; 1287 } 1288 1289 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode, 1290 const TargetRegisterClass *RC, 1291 unsigned Op0, bool Op0IsKill, 1292 uint64_t Imm1, uint64_t Imm2) { 1293 unsigned ResultReg = createResultReg(RC); 1294 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1295 1296 if (II.getNumDefs() >= 1) 1297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1298 .addReg(Op0, Op0IsKill * RegState::Kill) 1299 .addImm(Imm1) 1300 .addImm(Imm2); 1301 else { 1302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1303 .addReg(Op0, Op0IsKill * RegState::Kill) 1304 .addImm(Imm1) 1305 .addImm(Imm2); 1306 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1307 ResultReg).addReg(II.ImplicitDefs[0]); 1308 } 1309 return ResultReg; 1310 } 1311 1312 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode, 1313 const TargetRegisterClass *RC, 1314 unsigned Op0, bool Op0IsKill, 1315 const ConstantFP *FPImm) { 1316 unsigned ResultReg = createResultReg(RC); 1317 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1318 1319 if (II.getNumDefs() >= 1) 1320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1321 .addReg(Op0, Op0IsKill * RegState::Kill) 1322 .addFPImm(FPImm); 1323 else { 1324 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1325 .addReg(Op0, Op0IsKill * RegState::Kill) 1326 .addFPImm(FPImm); 1327 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1328 ResultReg).addReg(II.ImplicitDefs[0]); 1329 } 1330 return ResultReg; 1331 } 1332 1333 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode, 1334 const TargetRegisterClass *RC, 1335 unsigned Op0, bool Op0IsKill, 1336 unsigned Op1, bool Op1IsKill, 1337 uint64_t Imm) { 1338 unsigned ResultReg = createResultReg(RC); 1339 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1340 1341 if (II.getNumDefs() >= 1) 1342 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1343 .addReg(Op0, Op0IsKill * RegState::Kill) 1344 .addReg(Op1, Op1IsKill * RegState::Kill) 1345 .addImm(Imm); 1346 else { 1347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1348 .addReg(Op0, Op0IsKill * RegState::Kill) 1349 .addReg(Op1, Op1IsKill * RegState::Kill) 1350 .addImm(Imm); 1351 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1352 ResultReg).addReg(II.ImplicitDefs[0]); 1353 } 1354 return ResultReg; 1355 } 1356 1357 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode, 1358 const TargetRegisterClass *RC, 1359 unsigned Op0, bool Op0IsKill, 1360 unsigned Op1, bool Op1IsKill, 1361 uint64_t Imm1, uint64_t Imm2) { 1362 unsigned ResultReg = createResultReg(RC); 1363 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1364 1365 if (II.getNumDefs() >= 1) 1366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1367 .addReg(Op0, Op0IsKill * RegState::Kill) 1368 .addReg(Op1, Op1IsKill * RegState::Kill) 1369 .addImm(Imm1).addImm(Imm2); 1370 else { 1371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II) 1372 .addReg(Op0, Op0IsKill * RegState::Kill) 1373 .addReg(Op1, Op1IsKill * RegState::Kill) 1374 .addImm(Imm1).addImm(Imm2); 1375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1376 ResultReg).addReg(II.ImplicitDefs[0]); 1377 } 1378 return ResultReg; 1379 } 1380 1381 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode, 1382 const TargetRegisterClass *RC, 1383 uint64_t Imm) { 1384 unsigned ResultReg = createResultReg(RC); 1385 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1386 1387 if (II.getNumDefs() >= 1) 1388 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm); 1389 else { 1390 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm); 1391 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1392 ResultReg).addReg(II.ImplicitDefs[0]); 1393 } 1394 return ResultReg; 1395 } 1396 1397 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode, 1398 const TargetRegisterClass *RC, 1399 uint64_t Imm1, uint64_t Imm2) { 1400 unsigned ResultReg = createResultReg(RC); 1401 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1402 1403 if (II.getNumDefs() >= 1) 1404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg) 1405 .addImm(Imm1).addImm(Imm2); 1406 else { 1407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2); 1408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1409 ResultReg).addReg(II.ImplicitDefs[0]); 1410 } 1411 return ResultReg; 1412 } 1413 1414 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT, 1415 unsigned Op0, bool Op0IsKill, 1416 uint32_t Idx) { 1417 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT)); 1418 assert(TargetRegisterInfo::isVirtualRegister(Op0) && 1419 "Cannot yet extract from physregs"); 1420 const TargetRegisterClass *RC = MRI.getRegClass(Op0); 1421 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx)); 1422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, 1423 DL, TII.get(TargetOpcode::COPY), ResultReg) 1424 .addReg(Op0, getKillRegState(Op0IsKill), Idx); 1425 return ResultReg; 1426 } 1427 1428 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op 1429 /// with all but the least significant bit set to zero. 1430 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) { 1431 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1); 1432 } 1433 1434 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks. 1435 /// Emit code to ensure constants are copied into registers when needed. 1436 /// Remember the virtual registers that need to be added to the Machine PHI 1437 /// nodes as input. We cannot just directly add them, because expansion 1438 /// might result in multiple MBB's for one BB. As such, the start of the 1439 /// BB might correspond to a different MBB than the end. 1440 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 1441 const TerminatorInst *TI = LLVMBB->getTerminator(); 1442 1443 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 1444 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size(); 1445 1446 // Check successor nodes' PHI nodes that expect a constant to be available 1447 // from this block. 1448 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 1449 const BasicBlock *SuccBB = TI->getSuccessor(succ); 1450 if (!isa<PHINode>(SuccBB->begin())) continue; 1451 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 1452 1453 // If this terminator has multiple identical successors (common for 1454 // switches), only handle each succ once. 1455 if (!SuccsHandled.insert(SuccMBB)) continue; 1456 1457 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 1458 1459 // At this point we know that there is a 1-1 correspondence between LLVM PHI 1460 // nodes and Machine PHI nodes, but the incoming operands have not been 1461 // emitted yet. 1462 for (BasicBlock::const_iterator I = SuccBB->begin(); 1463 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 1464 1465 // Ignore dead phi's. 1466 if (PN->use_empty()) continue; 1467 1468 // Only handle legal types. Two interesting things to note here. First, 1469 // by bailing out early, we may leave behind some dead instructions, 1470 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 1471 // own moves. Second, this check is necessary because FastISel doesn't 1472 // use CreateRegs to create registers, so it always creates 1473 // exactly one register for each non-void instruction. 1474 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true); 1475 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 1476 // Handle integer promotions, though, because they're common and easy. 1477 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16) 1478 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT); 1479 else { 1480 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 1481 return false; 1482 } 1483 } 1484 1485 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 1486 1487 // Set the DebugLoc for the copy. Prefer the location of the operand 1488 // if there is one; use the location of the PHI otherwise. 1489 DL = PN->getDebugLoc(); 1490 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp)) 1491 DL = Inst->getDebugLoc(); 1492 1493 unsigned Reg = getRegForValue(PHIOp); 1494 if (Reg == 0) { 1495 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 1496 return false; 1497 } 1498 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg)); 1499 DL = DebugLoc(); 1500 } 1501 } 1502 1503 return true; 1504 } 1505 1506 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) { 1507 assert(LI->hasOneUse() && 1508 "tryToFoldLoad expected a LoadInst with a single use"); 1509 // We know that the load has a single use, but don't know what it is. If it 1510 // isn't one of the folded instructions, then we can't succeed here. Handle 1511 // this by scanning the single-use users of the load until we get to FoldInst. 1512 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs. 1513 1514 const Instruction *TheUser = LI->use_back(); 1515 while (TheUser != FoldInst && // Scan up until we find FoldInst. 1516 // Stay in the right block. 1517 TheUser->getParent() == FoldInst->getParent() && 1518 --MaxUsers) { // Don't scan too far. 1519 // If there are multiple or no uses of this instruction, then bail out. 1520 if (!TheUser->hasOneUse()) 1521 return false; 1522 1523 TheUser = TheUser->use_back(); 1524 } 1525 1526 // If we didn't find the fold instruction, then we failed to collapse the 1527 // sequence. 1528 if (TheUser != FoldInst) 1529 return false; 1530 1531 // Don't try to fold volatile loads. Target has to deal with alignment 1532 // constraints. 1533 if (LI->isVolatile()) 1534 return false; 1535 1536 // Figure out which vreg this is going into. If there is no assigned vreg yet 1537 // then there actually was no reference to it. Perhaps the load is referenced 1538 // by a dead instruction. 1539 unsigned LoadReg = getRegForValue(LI); 1540 if (LoadReg == 0) 1541 return false; 1542 1543 // We can't fold if this vreg has no uses or more than one use. Multiple uses 1544 // may mean that the instruction got lowered to multiple MIs, or the use of 1545 // the loaded value ended up being multiple operands of the result. 1546 if (!MRI.hasOneUse(LoadReg)) 1547 return false; 1548 1549 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg); 1550 MachineInstr *User = &*RI; 1551 1552 // Set the insertion point properly. Folding the load can cause generation of 1553 // other random instructions (like sign extends) for addressing modes; make 1554 // sure they get inserted in a logical place before the new instruction. 1555 FuncInfo.InsertPt = User; 1556 FuncInfo.MBB = User->getParent(); 1557 1558 // Ask the target to try folding the load. 1559 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI); 1560 } 1561 1562 1563