1 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the FastISel class.
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.
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.
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
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.
40 //===----------------------------------------------------------------------===//
42 #define DEBUG_TYPE "isel"
43 #include "llvm/DebugInfo.h"
44 #include "llvm/Function.h"
45 #include "llvm/GlobalVariable.h"
46 #include "llvm/Instructions.h"
47 #include "llvm/IntrinsicInst.h"
48 #include "llvm/Operator.h"
49 #include "llvm/CodeGen/Analysis.h"
50 #include "llvm/CodeGen/FastISel.h"
51 #include "llvm/CodeGen/FunctionLoweringInfo.h"
52 #include "llvm/CodeGen/MachineInstrBuilder.h"
53 #include "llvm/CodeGen/MachineModuleInfo.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/Analysis/Loads.h"
56 #include "llvm/Target/TargetData.h"
57 #include "llvm/Target/TargetInstrInfo.h"
58 #include "llvm/Target/TargetLibraryInfo.h"
59 #include "llvm/Target/TargetLowering.h"
60 #include "llvm/Target/TargetMachine.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/ADT/Statistic.h"
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");
72 /// startNewBlock - Set the current block to which generated machine
73 /// instructions will be appended, and clear the local CSE map.
75 void FastISel::startNewBlock() {
76 LocalValueMap.clear();
80 // Advance the emit start point past any EH_LABEL instructions.
81 MachineBasicBlock::iterator
82 I = FuncInfo.MBB->begin(), E = FuncInfo.MBB->end();
83 while (I != E && I->getOpcode() == TargetOpcode::EH_LABEL) {
87 LastLocalValue = EmitStartPt;
90 void FastISel::flushLocalValueMap() {
91 LocalValueMap.clear();
92 LastLocalValue = EmitStartPt;
96 bool FastISel::hasTrivialKill(const Value *V) const {
97 // Don't consider constants or arguments to have trivial kills.
98 const Instruction *I = dyn_cast<Instruction>(V);
102 // No-op casts are trivially coalesced by fast-isel.
103 if (const CastInst *Cast = dyn_cast<CastInst>(I))
104 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
105 !hasTrivialKill(Cast->getOperand(0)))
108 // GEPs with all zero indices are trivially coalesced by fast-isel.
109 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
110 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
113 // Only instructions with a single use in the same basic block are considered
114 // to have trivial kills.
115 return I->hasOneUse() &&
116 !(I->getOpcode() == Instruction::BitCast ||
117 I->getOpcode() == Instruction::PtrToInt ||
118 I->getOpcode() == Instruction::IntToPtr) &&
119 cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
122 unsigned FastISel::getRegForValue(const Value *V) {
123 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
124 // Don't handle non-simple values in FastISel.
125 if (!RealVT.isSimple())
128 // Ignore illegal types. We must do this before looking up the value
129 // in ValueMap because Arguments are given virtual registers regardless
130 // of whether FastISel can handle them.
131 MVT VT = RealVT.getSimpleVT();
132 if (!TLI.isTypeLegal(VT)) {
133 // Handle integer promotions, though, because they're common and easy.
134 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
135 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
140 // Look up the value to see if we already have a register for it.
141 unsigned Reg = lookUpRegForValue(V);
145 // In bottom-up mode, just create the virtual register which will be used
146 // to hold the value. It will be materialized later.
147 if (isa<Instruction>(V) &&
148 (!isa<AllocaInst>(V) ||
149 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
150 return FuncInfo.InitializeRegForValue(V);
152 MachineBasicBlock::iterator SaveIter = enterLocalValueArea();
154 // Materialize the value in a register. Emit any instructions in the
156 Reg = materializeRegForValue(V, VT);
158 leaveLocalValueArea(SaveIter);
163 /// materializeRegForValue - Helper for getRegForValue. This function is
164 /// called when the value isn't already available in a register and must
165 /// be materialized with new instructions.
166 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
169 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
170 if (CI->getValue().getActiveBits() <= 64)
171 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
172 } else if (isa<AllocaInst>(V)) {
173 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
174 } else if (isa<ConstantPointerNull>(V)) {
175 // Translate this as an integer zero so that it can be
176 // local-CSE'd with actual integer zeros.
178 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
179 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
180 if (CF->isNullValue()) {
181 Reg = TargetMaterializeFloatZero(CF);
183 // Try to emit the constant directly.
184 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
188 // Try to emit the constant by using an integer constant with a cast.
189 const APFloat &Flt = CF->getValueAPF();
190 EVT IntVT = TLI.getPointerTy();
193 uint32_t IntBitWidth = IntVT.getSizeInBits();
195 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
196 APFloat::rmTowardZero, &isExact);
198 APInt IntVal(IntBitWidth, x);
200 unsigned IntegerReg =
201 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
203 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
204 IntegerReg, /*Kill=*/false);
207 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
208 if (!SelectOperator(Op, Op->getOpcode()))
209 if (!isa<Instruction>(Op) ||
210 !TargetSelectInstruction(cast<Instruction>(Op)))
212 Reg = lookUpRegForValue(Op);
213 } else if (isa<UndefValue>(V)) {
214 Reg = createResultReg(TLI.getRegClassFor(VT));
215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
216 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
219 // If target-independent code couldn't handle the value, give target-specific
221 if (!Reg && isa<Constant>(V))
222 Reg = TargetMaterializeConstant(cast<Constant>(V));
224 // Don't cache constant materializations in the general ValueMap.
225 // To do so would require tracking what uses they dominate.
227 LocalValueMap[V] = Reg;
228 LastLocalValue = MRI.getVRegDef(Reg);
233 unsigned FastISel::lookUpRegForValue(const Value *V) {
234 // Look up the value to see if we already have a register for it. We
235 // cache values defined by Instructions across blocks, and other values
236 // only locally. This is because Instructions already have the SSA
237 // def-dominates-use requirement enforced.
238 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
239 if (I != FuncInfo.ValueMap.end())
241 unsigned Reg = LocalValueMap[V];
243 // If we managed to find a register here then go ahead and replace the
244 // current location with the location we're currently emitted for,
245 // 'moving' the value to a place that's closer to where it originally
248 MRI.getVRegDef(Reg)->setDebugLoc(DL);
253 /// UpdateValueMap - Update the value map to include the new mapping for this
254 /// instruction, or insert an extra copy to get the result in a previous
255 /// determined register.
256 /// NOTE: This is only necessary because we might select a block that uses
257 /// a value before we select the block that defines the value. It might be
258 /// possible to fix this by selecting blocks in reverse postorder.
259 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
260 if (!isa<Instruction>(I)) {
261 LocalValueMap[I] = Reg;
265 unsigned &AssignedReg = FuncInfo.ValueMap[I];
266 if (AssignedReg == 0)
267 // Use the new register.
269 else if (Reg != AssignedReg) {
270 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
271 for (unsigned i = 0; i < NumRegs; i++)
272 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
278 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
279 unsigned IdxN = getRegForValue(Idx);
281 // Unhandled operand. Halt "fast" selection and bail.
282 return std::pair<unsigned, bool>(0, false);
284 bool IdxNIsKill = hasTrivialKill(Idx);
286 // If the index is smaller or larger than intptr_t, truncate or extend it.
287 MVT PtrVT = TLI.getPointerTy();
288 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
289 if (IdxVT.bitsLT(PtrVT)) {
290 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
294 else if (IdxVT.bitsGT(PtrVT)) {
295 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
299 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
302 void FastISel::recomputeInsertPt() {
303 if (getLastLocalValue()) {
304 FuncInfo.InsertPt = getLastLocalValue();
305 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
308 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
310 // Now skip past any EH_LABELs, which must remain at the beginning.
311 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
312 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
316 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
317 MachineBasicBlock::iterator E) {
318 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
320 MachineInstr *Dead = &*I;
322 Dead->eraseFromParent();
328 MachineBasicBlock::iterator FastISel::enterLocalValueArea() {
329 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
334 void FastISel::leaveLocalValueArea(MachineBasicBlock::iterator I) {
335 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
336 LastLocalValue = llvm::prior(FuncInfo.InsertPt);
338 // Restore the previous insert position.
339 FuncInfo.InsertPt = I;
342 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
343 /// which has an opcode which directly corresponds to the given ISD opcode.
345 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
346 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
347 if (VT == MVT::Other || !VT.isSimple())
348 // Unhandled type. Halt "fast" selection and bail.
351 // We only handle legal types. For example, on x86-32 the instruction
352 // selector contains all of the 64-bit instructions from x86-64,
353 // under the assumption that i64 won't be used if the target doesn't
355 if (!TLI.isTypeLegal(VT)) {
356 // MVT::i1 is special. Allow AND, OR, or XOR because they
357 // don't require additional zeroing, which makes them easy.
359 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
360 ISDOpcode == ISD::XOR))
361 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
366 // Check if the first operand is a constant, and handle it as "ri". At -O0,
367 // we don't have anything that canonicalizes operand order.
368 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
369 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
370 unsigned Op1 = getRegForValue(I->getOperand(1));
371 if (Op1 == 0) return false;
373 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
375 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
376 Op1IsKill, CI->getZExtValue(),
378 if (ResultReg == 0) return false;
380 // We successfully emitted code for the given LLVM Instruction.
381 UpdateValueMap(I, ResultReg);
386 unsigned Op0 = getRegForValue(I->getOperand(0));
387 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
390 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
392 // Check if the second operand is a constant and handle it appropriately.
393 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
394 uint64_t Imm = CI->getZExtValue();
396 // Transform "sdiv exact X, 8" -> "sra X, 3".
397 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
398 cast<BinaryOperator>(I)->isExact() &&
399 isPowerOf2_64(Imm)) {
401 ISDOpcode = ISD::SRA;
404 // Transform "urem x, pow2" -> "and x, pow2-1".
405 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
406 isPowerOf2_64(Imm)) {
408 ISDOpcode = ISD::AND;
411 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
412 Op0IsKill, Imm, VT.getSimpleVT());
413 if (ResultReg == 0) return false;
415 // We successfully emitted code for the given LLVM Instruction.
416 UpdateValueMap(I, ResultReg);
420 // Check if the second operand is a constant float.
421 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
422 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
423 ISDOpcode, Op0, Op0IsKill, CF);
424 if (ResultReg != 0) {
425 // We successfully emitted code for the given LLVM Instruction.
426 UpdateValueMap(I, ResultReg);
431 unsigned Op1 = getRegForValue(I->getOperand(1));
433 // Unhandled operand. Halt "fast" selection and bail.
436 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
438 // Now we have both operands in registers. Emit the instruction.
439 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
444 // Target-specific code wasn't able to find a machine opcode for
445 // the given ISD opcode and type. Halt "fast" selection and bail.
448 // We successfully emitted code for the given LLVM Instruction.
449 UpdateValueMap(I, ResultReg);
453 bool FastISel::SelectGetElementPtr(const User *I) {
454 unsigned N = getRegForValue(I->getOperand(0));
456 // Unhandled operand. Halt "fast" selection and bail.
459 bool NIsKill = hasTrivialKill(I->getOperand(0));
461 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
462 // into a single N = N + TotalOffset.
463 uint64_t TotalOffs = 0;
464 // FIXME: What's a good SWAG number for MaxOffs?
465 uint64_t MaxOffs = 2048;
466 Type *Ty = I->getOperand(0)->getType();
467 MVT VT = TLI.getPointerTy();
468 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
469 E = I->op_end(); OI != E; ++OI) {
470 const Value *Idx = *OI;
471 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
472 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
475 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
476 if (TotalOffs >= MaxOffs) {
477 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
479 // Unhandled operand. Halt "fast" selection and bail.
485 Ty = StTy->getElementType(Field);
487 Ty = cast<SequentialType>(Ty)->getElementType();
489 // If this is a constant subscript, handle it quickly.
490 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
491 if (CI->isZero()) continue;
494 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
495 if (TotalOffs >= MaxOffs) {
496 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
498 // Unhandled operand. Halt "fast" selection and bail.
506 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
508 // Unhandled operand. Halt "fast" selection and bail.
514 // N = N + Idx * ElementSize;
515 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
516 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
517 unsigned IdxN = Pair.first;
518 bool IdxNIsKill = Pair.second;
520 // Unhandled operand. Halt "fast" selection and bail.
523 if (ElementSize != 1) {
524 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
526 // Unhandled operand. Halt "fast" selection and bail.
530 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
532 // Unhandled operand. Halt "fast" selection and bail.
537 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
539 // Unhandled operand. Halt "fast" selection and bail.
543 // We successfully emitted code for the given LLVM Instruction.
544 UpdateValueMap(I, N);
548 bool FastISel::SelectCall(const User *I) {
549 const CallInst *Call = cast<CallInst>(I);
551 // Handle simple inline asms.
552 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
553 // Don't attempt to handle constraints.
554 if (!IA->getConstraintString().empty())
557 unsigned ExtraInfo = 0;
558 if (IA->hasSideEffects())
559 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
560 if (IA->isAlignStack())
561 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
563 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
564 TII.get(TargetOpcode::INLINEASM))
565 .addExternalSymbol(IA->getAsmString().c_str())
570 MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
571 ComputeUsesVAFloatArgument(*Call, &MMI);
573 const Function *F = Call->getCalledFunction();
574 if (!F) return false;
576 // Handle selected intrinsic function calls.
577 switch (F->getIntrinsicID()) {
579 // At -O0 we don't care about the lifetime intrinsics.
580 case Intrinsic::lifetime_start:
581 case Intrinsic::lifetime_end:
582 // The donothing intrinsic does, well, nothing.
583 case Intrinsic::donothing:
586 case Intrinsic::dbg_declare: {
587 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
588 if (!DIVariable(DI->getVariable()).Verify() ||
589 !FuncInfo.MF->getMMI().hasDebugInfo()) {
590 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
594 const Value *Address = DI->getAddress();
595 if (!Address || isa<UndefValue>(Address)) {
596 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
602 if (const Argument *Arg = dyn_cast<Argument>(Address)) {
603 // Some arguments' frame index is recorded during argument lowering.
604 Offset = FuncInfo.getArgumentFrameIndex(Arg);
606 Reg = TRI.getFrameRegister(*FuncInfo.MF);
609 Reg = lookUpRegForValue(Address);
611 // If we have a VLA that has a "use" in a metadata node that's then used
612 // here but it has no other uses, then we have a problem. E.g.,
614 // int foo (const int *x) {
619 // If we assign 'a' a vreg and fast isel later on has to use the selection
620 // DAG isel, it will want to copy the value to the vreg. However, there are
621 // no uses, which goes counter to what selection DAG isel expects.
622 if (!Reg && !Address->use_empty() && isa<Instruction>(Address) &&
623 (!isa<AllocaInst>(Address) ||
624 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
625 Reg = FuncInfo.InitializeRegForValue(Address);
628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
629 TII.get(TargetOpcode::DBG_VALUE))
630 .addReg(Reg, RegState::Debug).addImm(Offset)
631 .addMetadata(DI->getVariable());
633 // We can't yet handle anything else here because it would require
634 // generating code, thus altering codegen because of debug info.
635 DEBUG(dbgs() << "Dropping debug info for " << DI);
638 case Intrinsic::dbg_value: {
639 // This form of DBG_VALUE is target-independent.
640 const DbgValueInst *DI = cast<DbgValueInst>(Call);
641 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
642 const Value *V = DI->getValue();
644 // Currently the optimizer can produce this; insert an undef to
645 // help debugging. Probably the optimizer should not do this.
646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
647 .addReg(0U).addImm(DI->getOffset())
648 .addMetadata(DI->getVariable());
649 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
650 if (CI->getBitWidth() > 64)
651 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
652 .addCImm(CI).addImm(DI->getOffset())
653 .addMetadata(DI->getVariable());
655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
656 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
657 .addMetadata(DI->getVariable());
658 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
660 .addFPImm(CF).addImm(DI->getOffset())
661 .addMetadata(DI->getVariable());
662 } else if (unsigned Reg = lookUpRegForValue(V)) {
663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
664 .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
665 .addMetadata(DI->getVariable());
667 // We can't yet handle anything else here because it would require
668 // generating code, thus altering codegen because of debug info.
669 DEBUG(dbgs() << "Dropping debug info for " << DI);
673 case Intrinsic::objectsize: {
674 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
675 unsigned long long Res = CI->isZero() ? -1ULL : 0;
676 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
677 unsigned ResultReg = getRegForValue(ResCI);
680 UpdateValueMap(Call, ResultReg);
685 // Usually, it does not make sense to initialize a value,
686 // make an unrelated function call and use the value, because
687 // it tends to be spilled on the stack. So, we move the pointer
688 // to the last local value to the beginning of the block, so that
689 // all the values which have already been materialized,
690 // appear after the call. It also makes sense to skip intrinsics
691 // since they tend to be inlined.
692 if (!isa<IntrinsicInst>(F))
693 flushLocalValueMap();
695 // An arbitrary call. Bail.
699 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
700 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
701 EVT DstVT = TLI.getValueType(I->getType());
703 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
704 DstVT == MVT::Other || !DstVT.isSimple())
705 // Unhandled type. Halt "fast" selection and bail.
708 // Check if the destination type is legal.
709 if (!TLI.isTypeLegal(DstVT))
712 // Check if the source operand is legal.
713 if (!TLI.isTypeLegal(SrcVT))
716 unsigned InputReg = getRegForValue(I->getOperand(0));
718 // Unhandled operand. Halt "fast" selection and bail.
721 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
723 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
726 InputReg, InputRegIsKill);
730 UpdateValueMap(I, ResultReg);
734 bool FastISel::SelectBitCast(const User *I) {
735 // If the bitcast doesn't change the type, just use the operand value.
736 if (I->getType() == I->getOperand(0)->getType()) {
737 unsigned Reg = getRegForValue(I->getOperand(0));
740 UpdateValueMap(I, Reg);
744 // Bitcasts of other values become reg-reg copies or BITCAST operators.
745 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
746 EVT DstVT = TLI.getValueType(I->getType());
748 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
749 DstVT == MVT::Other || !DstVT.isSimple() ||
750 !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
751 // Unhandled type. Halt "fast" selection and bail.
754 unsigned Op0 = getRegForValue(I->getOperand(0));
756 // Unhandled operand. Halt "fast" selection and bail.
759 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
761 // First, try to perform the bitcast by inserting a reg-reg copy.
762 unsigned ResultReg = 0;
763 if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
764 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
765 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
766 // Don't attempt a cross-class copy. It will likely fail.
767 if (SrcClass == DstClass) {
768 ResultReg = createResultReg(DstClass);
769 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
770 ResultReg).addReg(Op0);
774 // If the reg-reg copy failed, select a BITCAST opcode.
776 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
777 ISD::BITCAST, Op0, Op0IsKill);
782 UpdateValueMap(I, ResultReg);
787 FastISel::SelectInstruction(const Instruction *I) {
788 // Just before the terminator instruction, insert instructions to
789 // feed PHI nodes in successor blocks.
790 if (isa<TerminatorInst>(I))
791 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
794 DL = I->getDebugLoc();
796 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
798 // As a special case, don't handle calls to builtin library functions that
799 // may be translated directly to target instructions.
800 if (const CallInst *Call = dyn_cast<CallInst>(I)) {
801 const Function *F = Call->getCalledFunction();
803 if (F && !F->hasLocalLinkage() && F->hasName() &&
804 LibInfo->getLibFunc(F->getName(), Func) &&
805 LibInfo->hasOptimizedCodeGen(Func))
809 // First, try doing target-independent selection.
810 if (SelectOperator(I, I->getOpcode())) {
811 ++NumFastIselSuccessIndependent;
815 // Remove dead code. However, ignore call instructions since we've flushed
816 // the local value map and recomputed the insert point.
817 if (!isa<CallInst>(I)) {
819 if (SavedInsertPt != FuncInfo.InsertPt)
820 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
823 // Next, try calling the target to attempt to handle the instruction.
824 SavedInsertPt = FuncInfo.InsertPt;
825 if (TargetSelectInstruction(I)) {
826 ++NumFastIselSuccessTarget;
830 // Check for dead code and remove as necessary.
832 if (SavedInsertPt != FuncInfo.InsertPt)
833 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
839 /// FastEmitBranch - Emit an unconditional branch to the given block,
840 /// unless it is the immediate (fall-through) successor, and update
843 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
845 if (FuncInfo.MBB->getBasicBlock()->size() > 1 && FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
846 // For more accurate line information if this is the only instruction
847 // in the block then emit it, otherwise we have the unconditional
848 // fall-through case, which needs no instructions.
850 // The unconditional branch case.
851 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
852 SmallVector<MachineOperand, 0>(), DL);
854 FuncInfo.MBB->addSuccessor(MSucc);
857 /// SelectFNeg - Emit an FNeg operation.
860 FastISel::SelectFNeg(const User *I) {
861 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
862 if (OpReg == 0) return false;
864 bool OpRegIsKill = hasTrivialKill(I);
866 // If the target has ISD::FNEG, use it.
867 EVT VT = TLI.getValueType(I->getType());
868 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
869 ISD::FNEG, OpReg, OpRegIsKill);
870 if (ResultReg != 0) {
871 UpdateValueMap(I, ResultReg);
875 // Bitcast the value to integer, twiddle the sign bit with xor,
876 // and then bitcast it back to floating-point.
877 if (VT.getSizeInBits() > 64) return false;
878 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
879 if (!TLI.isTypeLegal(IntVT))
882 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
883 ISD::BITCAST, OpReg, OpRegIsKill);
887 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
888 IntReg, /*Kill=*/true,
889 UINT64_C(1) << (VT.getSizeInBits()-1),
890 IntVT.getSimpleVT());
891 if (IntResultReg == 0)
894 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
895 ISD::BITCAST, IntResultReg, /*Kill=*/true);
899 UpdateValueMap(I, ResultReg);
904 FastISel::SelectExtractValue(const User *U) {
905 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
909 // Make sure we only try to handle extracts with a legal result. But also
910 // allow i1 because it's easy.
911 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
912 if (!RealVT.isSimple())
914 MVT VT = RealVT.getSimpleVT();
915 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
918 const Value *Op0 = EVI->getOperand(0);
919 Type *AggTy = Op0->getType();
921 // Get the base result register.
923 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
924 if (I != FuncInfo.ValueMap.end())
925 ResultReg = I->second;
926 else if (isa<Instruction>(Op0))
927 ResultReg = FuncInfo.InitializeRegForValue(Op0);
929 return false; // fast-isel can't handle aggregate constants at the moment
931 // Get the actual result register, which is an offset from the base register.
932 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
934 SmallVector<EVT, 4> AggValueVTs;
935 ComputeValueVTs(TLI, AggTy, AggValueVTs);
937 for (unsigned i = 0; i < VTIndex; i++)
938 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
940 UpdateValueMap(EVI, ResultReg);
945 FastISel::SelectOperator(const User *I, unsigned Opcode) {
947 case Instruction::Add:
948 return SelectBinaryOp(I, ISD::ADD);
949 case Instruction::FAdd:
950 return SelectBinaryOp(I, ISD::FADD);
951 case Instruction::Sub:
952 return SelectBinaryOp(I, ISD::SUB);
953 case Instruction::FSub:
954 // FNeg is currently represented in LLVM IR as a special case of FSub.
955 if (BinaryOperator::isFNeg(I))
956 return SelectFNeg(I);
957 return SelectBinaryOp(I, ISD::FSUB);
958 case Instruction::Mul:
959 return SelectBinaryOp(I, ISD::MUL);
960 case Instruction::FMul:
961 return SelectBinaryOp(I, ISD::FMUL);
962 case Instruction::SDiv:
963 return SelectBinaryOp(I, ISD::SDIV);
964 case Instruction::UDiv:
965 return SelectBinaryOp(I, ISD::UDIV);
966 case Instruction::FDiv:
967 return SelectBinaryOp(I, ISD::FDIV);
968 case Instruction::SRem:
969 return SelectBinaryOp(I, ISD::SREM);
970 case Instruction::URem:
971 return SelectBinaryOp(I, ISD::UREM);
972 case Instruction::FRem:
973 return SelectBinaryOp(I, ISD::FREM);
974 case Instruction::Shl:
975 return SelectBinaryOp(I, ISD::SHL);
976 case Instruction::LShr:
977 return SelectBinaryOp(I, ISD::SRL);
978 case Instruction::AShr:
979 return SelectBinaryOp(I, ISD::SRA);
980 case Instruction::And:
981 return SelectBinaryOp(I, ISD::AND);
982 case Instruction::Or:
983 return SelectBinaryOp(I, ISD::OR);
984 case Instruction::Xor:
985 return SelectBinaryOp(I, ISD::XOR);
987 case Instruction::GetElementPtr:
988 return SelectGetElementPtr(I);
990 case Instruction::Br: {
991 const BranchInst *BI = cast<BranchInst>(I);
993 if (BI->isUnconditional()) {
994 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
995 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
996 FastEmitBranch(MSucc, BI->getDebugLoc());
1000 // Conditional branches are not handed yet.
1001 // Halt "fast" selection and bail.
1005 case Instruction::Unreachable:
1009 case Instruction::Alloca:
1010 // FunctionLowering has the static-sized case covered.
1011 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1014 // Dynamic-sized alloca is not handled yet.
1017 case Instruction::Call:
1018 return SelectCall(I);
1020 case Instruction::BitCast:
1021 return SelectBitCast(I);
1023 case Instruction::FPToSI:
1024 return SelectCast(I, ISD::FP_TO_SINT);
1025 case Instruction::ZExt:
1026 return SelectCast(I, ISD::ZERO_EXTEND);
1027 case Instruction::SExt:
1028 return SelectCast(I, ISD::SIGN_EXTEND);
1029 case Instruction::Trunc:
1030 return SelectCast(I, ISD::TRUNCATE);
1031 case Instruction::SIToFP:
1032 return SelectCast(I, ISD::SINT_TO_FP);
1034 case Instruction::IntToPtr: // Deliberate fall-through.
1035 case Instruction::PtrToInt: {
1036 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1037 EVT DstVT = TLI.getValueType(I->getType());
1038 if (DstVT.bitsGT(SrcVT))
1039 return SelectCast(I, ISD::ZERO_EXTEND);
1040 if (DstVT.bitsLT(SrcVT))
1041 return SelectCast(I, ISD::TRUNCATE);
1042 unsigned Reg = getRegForValue(I->getOperand(0));
1043 if (Reg == 0) return false;
1044 UpdateValueMap(I, Reg);
1048 case Instruction::ExtractValue:
1049 return SelectExtractValue(I);
1051 case Instruction::PHI:
1052 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1055 // Unhandled instruction. Halt "fast" selection and bail.
1060 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1061 const TargetLibraryInfo *libInfo)
1062 : FuncInfo(funcInfo),
1063 MRI(FuncInfo.MF->getRegInfo()),
1064 MFI(*FuncInfo.MF->getFrameInfo()),
1065 MCP(*FuncInfo.MF->getConstantPool()),
1066 TM(FuncInfo.MF->getTarget()),
1067 TD(*TM.getTargetData()),
1068 TII(*TM.getInstrInfo()),
1069 TLI(*TM.getTargetLowering()),
1070 TRI(*TM.getRegisterInfo()),
1074 FastISel::~FastISel() {}
1076 unsigned FastISel::FastEmit_(MVT, MVT,
1081 unsigned FastISel::FastEmit_r(MVT, MVT,
1083 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1087 unsigned FastISel::FastEmit_rr(MVT, MVT,
1089 unsigned /*Op0*/, bool /*Op0IsKill*/,
1090 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1094 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1098 unsigned FastISel::FastEmit_f(MVT, MVT,
1099 unsigned, const ConstantFP * /*FPImm*/) {
1103 unsigned FastISel::FastEmit_ri(MVT, MVT,
1105 unsigned /*Op0*/, bool /*Op0IsKill*/,
1110 unsigned FastISel::FastEmit_rf(MVT, MVT,
1112 unsigned /*Op0*/, bool /*Op0IsKill*/,
1113 const ConstantFP * /*FPImm*/) {
1117 unsigned FastISel::FastEmit_rri(MVT, MVT,
1119 unsigned /*Op0*/, bool /*Op0IsKill*/,
1120 unsigned /*Op1*/, bool /*Op1IsKill*/,
1125 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1126 /// to emit an instruction with an immediate operand using FastEmit_ri.
1127 /// If that fails, it materializes the immediate into a register and try
1128 /// FastEmit_rr instead.
1129 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1130 unsigned Op0, bool Op0IsKill,
1131 uint64_t Imm, MVT ImmType) {
1132 // If this is a multiply by a power of two, emit this as a shift left.
1133 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1136 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1137 // div x, 8 -> srl x, 3
1142 // Horrible hack (to be removed), check to make sure shift amounts are
1144 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1145 Imm >= VT.getSizeInBits())
1148 // First check if immediate type is legal. If not, we can't use the ri form.
1149 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1152 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1153 if (MaterialReg == 0) {
1154 // This is a bit ugly/slow, but failing here means falling out of
1155 // fast-isel, which would be very slow.
1156 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1157 VT.getSizeInBits());
1158 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1160 return FastEmit_rr(VT, VT, Opcode,
1162 MaterialReg, /*Kill=*/true);
1165 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1166 return MRI.createVirtualRegister(RC);
1169 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1170 const TargetRegisterClass* RC) {
1171 unsigned ResultReg = createResultReg(RC);
1172 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1178 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1179 const TargetRegisterClass *RC,
1180 unsigned Op0, bool Op0IsKill) {
1181 unsigned ResultReg = createResultReg(RC);
1182 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1184 if (II.getNumDefs() >= 1)
1185 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1186 .addReg(Op0, Op0IsKill * RegState::Kill);
1188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1189 .addReg(Op0, Op0IsKill * RegState::Kill);
1190 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1191 ResultReg).addReg(II.ImplicitDefs[0]);
1197 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1198 const TargetRegisterClass *RC,
1199 unsigned Op0, bool Op0IsKill,
1200 unsigned Op1, bool Op1IsKill) {
1201 unsigned ResultReg = createResultReg(RC);
1202 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1204 if (II.getNumDefs() >= 1)
1205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1206 .addReg(Op0, Op0IsKill * RegState::Kill)
1207 .addReg(Op1, Op1IsKill * RegState::Kill);
1209 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1210 .addReg(Op0, Op0IsKill * RegState::Kill)
1211 .addReg(Op1, Op1IsKill * RegState::Kill);
1212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1213 ResultReg).addReg(II.ImplicitDefs[0]);
1218 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1219 const TargetRegisterClass *RC,
1220 unsigned Op0, bool Op0IsKill,
1221 unsigned Op1, bool Op1IsKill,
1222 unsigned Op2, bool Op2IsKill) {
1223 unsigned ResultReg = createResultReg(RC);
1224 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1226 if (II.getNumDefs() >= 1)
1227 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1228 .addReg(Op0, Op0IsKill * RegState::Kill)
1229 .addReg(Op1, Op1IsKill * RegState::Kill)
1230 .addReg(Op2, Op2IsKill * RegState::Kill);
1232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1233 .addReg(Op0, Op0IsKill * RegState::Kill)
1234 .addReg(Op1, Op1IsKill * RegState::Kill)
1235 .addReg(Op2, Op2IsKill * RegState::Kill);
1236 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1237 ResultReg).addReg(II.ImplicitDefs[0]);
1242 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1243 const TargetRegisterClass *RC,
1244 unsigned Op0, bool Op0IsKill,
1246 unsigned ResultReg = createResultReg(RC);
1247 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1249 if (II.getNumDefs() >= 1)
1250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1251 .addReg(Op0, Op0IsKill * RegState::Kill)
1254 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1255 .addReg(Op0, Op0IsKill * RegState::Kill)
1257 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1258 ResultReg).addReg(II.ImplicitDefs[0]);
1263 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1264 const TargetRegisterClass *RC,
1265 unsigned Op0, bool Op0IsKill,
1266 uint64_t Imm1, uint64_t Imm2) {
1267 unsigned ResultReg = createResultReg(RC);
1268 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1270 if (II.getNumDefs() >= 1)
1271 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1272 .addReg(Op0, Op0IsKill * RegState::Kill)
1276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1277 .addReg(Op0, Op0IsKill * RegState::Kill)
1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1281 ResultReg).addReg(II.ImplicitDefs[0]);
1286 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1287 const TargetRegisterClass *RC,
1288 unsigned Op0, bool Op0IsKill,
1289 const ConstantFP *FPImm) {
1290 unsigned ResultReg = createResultReg(RC);
1291 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1293 if (II.getNumDefs() >= 1)
1294 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1295 .addReg(Op0, Op0IsKill * RegState::Kill)
1298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1299 .addReg(Op0, Op0IsKill * RegState::Kill)
1301 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1302 ResultReg).addReg(II.ImplicitDefs[0]);
1307 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1308 const TargetRegisterClass *RC,
1309 unsigned Op0, bool Op0IsKill,
1310 unsigned Op1, bool Op1IsKill,
1312 unsigned ResultReg = createResultReg(RC);
1313 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1315 if (II.getNumDefs() >= 1)
1316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1317 .addReg(Op0, Op0IsKill * RegState::Kill)
1318 .addReg(Op1, Op1IsKill * RegState::Kill)
1321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1322 .addReg(Op0, Op0IsKill * RegState::Kill)
1323 .addReg(Op1, Op1IsKill * RegState::Kill)
1325 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1326 ResultReg).addReg(II.ImplicitDefs[0]);
1331 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1332 const TargetRegisterClass *RC,
1333 unsigned Op0, bool Op0IsKill,
1334 unsigned Op1, bool Op1IsKill,
1335 uint64_t Imm1, uint64_t Imm2) {
1336 unsigned ResultReg = createResultReg(RC);
1337 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1339 if (II.getNumDefs() >= 1)
1340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1341 .addReg(Op0, Op0IsKill * RegState::Kill)
1342 .addReg(Op1, Op1IsKill * RegState::Kill)
1343 .addImm(Imm1).addImm(Imm2);
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1346 .addReg(Op0, Op0IsKill * RegState::Kill)
1347 .addReg(Op1, Op1IsKill * RegState::Kill)
1348 .addImm(Imm1).addImm(Imm2);
1349 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1350 ResultReg).addReg(II.ImplicitDefs[0]);
1355 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1356 const TargetRegisterClass *RC,
1358 unsigned ResultReg = createResultReg(RC);
1359 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1361 if (II.getNumDefs() >= 1)
1362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1364 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1365 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1366 ResultReg).addReg(II.ImplicitDefs[0]);
1371 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1372 const TargetRegisterClass *RC,
1373 uint64_t Imm1, uint64_t Imm2) {
1374 unsigned ResultReg = createResultReg(RC);
1375 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1377 if (II.getNumDefs() >= 1)
1378 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1379 .addImm(Imm1).addImm(Imm2);
1381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1383 ResultReg).addReg(II.ImplicitDefs[0]);
1388 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1389 unsigned Op0, bool Op0IsKill,
1391 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1392 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1393 "Cannot yet extract from physregs");
1394 const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1395 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1396 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1397 DL, TII.get(TargetOpcode::COPY), ResultReg)
1398 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1402 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1403 /// with all but the least significant bit set to zero.
1404 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1405 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1408 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1409 /// Emit code to ensure constants are copied into registers when needed.
1410 /// Remember the virtual registers that need to be added to the Machine PHI
1411 /// nodes as input. We cannot just directly add them, because expansion
1412 /// might result in multiple MBB's for one BB. As such, the start of the
1413 /// BB might correspond to a different MBB than the end.
1414 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1415 const TerminatorInst *TI = LLVMBB->getTerminator();
1417 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1418 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1420 // Check successor nodes' PHI nodes that expect a constant to be available
1422 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1423 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1424 if (!isa<PHINode>(SuccBB->begin())) continue;
1425 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1427 // If this terminator has multiple identical successors (common for
1428 // switches), only handle each succ once.
1429 if (!SuccsHandled.insert(SuccMBB)) continue;
1431 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1433 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1434 // nodes and Machine PHI nodes, but the incoming operands have not been
1436 for (BasicBlock::const_iterator I = SuccBB->begin();
1437 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1439 // Ignore dead phi's.
1440 if (PN->use_empty()) continue;
1442 // Only handle legal types. Two interesting things to note here. First,
1443 // by bailing out early, we may leave behind some dead instructions,
1444 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1445 // own moves. Second, this check is necessary because FastISel doesn't
1446 // use CreateRegs to create registers, so it always creates
1447 // exactly one register for each non-void instruction.
1448 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1449 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1450 // Handle integer promotions, though, because they're common and easy.
1451 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1452 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1454 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1459 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1461 // Set the DebugLoc for the copy. Prefer the location of the operand
1462 // if there is one; use the location of the PHI otherwise.
1463 DL = PN->getDebugLoc();
1464 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1465 DL = Inst->getDebugLoc();
1467 unsigned Reg = getRegForValue(PHIOp);
1469 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1472 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));