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 #include "llvm/Function.h"
43 #include "llvm/GlobalVariable.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/IntrinsicInst.h"
46 #include "llvm/CodeGen/FastISel.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineModuleInfo.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/Analysis/DebugInfo.h"
51 #include "llvm/Target/TargetData.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetLowering.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "FunctionLoweringInfo.h"
59 unsigned FastISel::getRegForValue(const Value *V) {
60 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
61 // Don't handle non-simple values in FastISel.
62 if (!RealVT.isSimple())
65 // Ignore illegal types. We must do this before looking up the value
66 // in ValueMap because Arguments are given virtual registers regardless
67 // of whether FastISel can handle them.
68 MVT VT = RealVT.getSimpleVT();
69 if (!TLI.isTypeLegal(VT)) {
70 // Promote MVT::i1 to a legal type though, because it's common and easy.
72 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
77 // Look up the value to see if we already have a register for it. We
78 // cache values defined by Instructions across blocks, and other values
79 // only locally. This is because Instructions already have the SSA
80 // def-dominates-use requirement enforced.
81 if (ValueMap.count(V))
83 unsigned Reg = LocalValueMap[V];
87 return materializeRegForValue(V, VT);
90 /// materializeRegForValue - Helper for getRegForVale. This function is
91 /// called when the value isn't already available in a register and must
92 /// be materialized with new instructions.
93 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
96 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
97 if (CI->getValue().getActiveBits() <= 64)
98 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
99 } else if (isa<AllocaInst>(V)) {
100 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
101 } else if (isa<ConstantPointerNull>(V)) {
102 // Translate this as an integer zero so that it can be
103 // local-CSE'd with actual integer zeros.
105 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
106 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
107 // Try to emit the constant directly.
108 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
111 // Try to emit the constant by using an integer constant with a cast.
112 const APFloat &Flt = CF->getValueAPF();
113 EVT IntVT = TLI.getPointerTy();
116 uint32_t IntBitWidth = IntVT.getSizeInBits();
118 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
119 APFloat::rmTowardZero, &isExact);
121 APInt IntVal(IntBitWidth, 2, x);
123 unsigned IntegerReg =
124 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
126 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg);
129 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
130 if (!SelectOperator(Op, Op->getOpcode())) return 0;
131 Reg = LocalValueMap[Op];
132 } else if (isa<UndefValue>(V)) {
133 Reg = createResultReg(TLI.getRegClassFor(VT));
134 BuildMI(MBB, DL, TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
137 // If target-independent code couldn't handle the value, give target-specific
139 if (!Reg && isa<Constant>(V))
140 Reg = TargetMaterializeConstant(cast<Constant>(V));
142 // Don't cache constant materializations in the general ValueMap.
143 // To do so would require tracking what uses they dominate.
145 LocalValueMap[V] = Reg;
149 unsigned FastISel::lookUpRegForValue(const Value *V) {
150 // Look up the value to see if we already have a register for it. We
151 // cache values defined by Instructions across blocks, and other values
152 // only locally. This is because Instructions already have the SSA
153 // def-dominates-use requirement enforced.
154 if (ValueMap.count(V))
156 return LocalValueMap[V];
159 /// UpdateValueMap - Update the value map to include the new mapping for this
160 /// instruction, or insert an extra copy to get the result in a previous
161 /// determined register.
162 /// NOTE: This is only necessary because we might select a block that uses
163 /// a value before we select the block that defines the value. It might be
164 /// possible to fix this by selecting blocks in reverse postorder.
165 unsigned FastISel::UpdateValueMap(const Value *I, unsigned Reg) {
166 if (!isa<Instruction>(I)) {
167 LocalValueMap[I] = Reg;
171 unsigned &AssignedReg = ValueMap[I];
172 if (AssignedReg == 0)
174 else if (Reg != AssignedReg) {
175 const TargetRegisterClass *RegClass = MRI.getRegClass(Reg);
176 TII.copyRegToReg(*MBB, MBB->end(), AssignedReg,
177 Reg, RegClass, RegClass);
182 unsigned FastISel::getRegForGEPIndex(const Value *Idx) {
183 unsigned IdxN = getRegForValue(Idx);
185 // Unhandled operand. Halt "fast" selection and bail.
188 // If the index is smaller or larger than intptr_t, truncate or extend it.
189 MVT PtrVT = TLI.getPointerTy();
190 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
191 if (IdxVT.bitsLT(PtrVT))
192 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN);
193 else if (IdxVT.bitsGT(PtrVT))
194 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN);
198 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
199 /// which has an opcode which directly corresponds to the given ISD opcode.
201 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
202 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
203 if (VT == MVT::Other || !VT.isSimple())
204 // Unhandled type. Halt "fast" selection and bail.
207 // We only handle legal types. For example, on x86-32 the instruction
208 // selector contains all of the 64-bit instructions from x86-64,
209 // under the assumption that i64 won't be used if the target doesn't
211 if (!TLI.isTypeLegal(VT)) {
212 // MVT::i1 is special. Allow AND, OR, or XOR because they
213 // don't require additional zeroing, which makes them easy.
215 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
216 ISDOpcode == ISD::XOR))
217 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
222 unsigned Op0 = getRegForValue(I->getOperand(0));
224 // Unhandled operand. Halt "fast" selection and bail.
227 // Check if the second operand is a constant and handle it appropriately.
228 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
229 unsigned ResultReg = FastEmit_ri(VT.getSimpleVT(), VT.getSimpleVT(),
230 ISDOpcode, Op0, CI->getZExtValue());
231 if (ResultReg != 0) {
232 // We successfully emitted code for the given LLVM Instruction.
233 UpdateValueMap(I, ResultReg);
238 // Check if the second operand is a constant float.
239 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
240 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
242 if (ResultReg != 0) {
243 // We successfully emitted code for the given LLVM Instruction.
244 UpdateValueMap(I, ResultReg);
249 unsigned Op1 = getRegForValue(I->getOperand(1));
251 // Unhandled operand. Halt "fast" selection and bail.
254 // Now we have both operands in registers. Emit the instruction.
255 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
256 ISDOpcode, Op0, Op1);
258 // Target-specific code wasn't able to find a machine opcode for
259 // the given ISD opcode and type. Halt "fast" selection and bail.
262 // We successfully emitted code for the given LLVM Instruction.
263 UpdateValueMap(I, ResultReg);
267 bool FastISel::SelectGetElementPtr(const User *I) {
268 unsigned N = getRegForValue(I->getOperand(0));
270 // Unhandled operand. Halt "fast" selection and bail.
273 const Type *Ty = I->getOperand(0)->getType();
274 MVT VT = TLI.getPointerTy();
275 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
276 E = I->op_end(); OI != E; ++OI) {
277 const Value *Idx = *OI;
278 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
279 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
282 uint64_t Offs = TD.getStructLayout(StTy)->getElementOffset(Field);
283 // FIXME: This can be optimized by combining the add with a
285 N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
287 // Unhandled operand. Halt "fast" selection and bail.
290 Ty = StTy->getElementType(Field);
292 Ty = cast<SequentialType>(Ty)->getElementType();
294 // If this is a constant subscript, handle it quickly.
295 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
296 if (CI->getZExtValue() == 0) continue;
298 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
299 N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
301 // Unhandled operand. Halt "fast" selection and bail.
306 // N = N + Idx * ElementSize;
307 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
308 unsigned IdxN = getRegForGEPIndex(Idx);
310 // Unhandled operand. Halt "fast" selection and bail.
313 if (ElementSize != 1) {
314 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT);
316 // Unhandled operand. Halt "fast" selection and bail.
319 N = FastEmit_rr(VT, VT, ISD::ADD, N, IdxN);
321 // Unhandled operand. Halt "fast" selection and bail.
326 // We successfully emitted code for the given LLVM Instruction.
327 UpdateValueMap(I, N);
331 bool FastISel::SelectCall(const User *I) {
332 const Function *F = cast<CallInst>(I)->getCalledFunction();
333 if (!F) return false;
335 // Handle selected intrinsic function calls.
336 unsigned IID = F->getIntrinsicID();
339 case Intrinsic::dbg_declare: {
340 const DbgDeclareInst *DI = cast<DbgDeclareInst>(I);
341 if (!DIDescriptor::ValidDebugInfo(DI->getVariable(), CodeGenOpt::None) ||
342 !MF.getMMI().hasDebugInfo())
345 const Value *Address = DI->getAddress();
348 if (isa<UndefValue>(Address))
350 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
351 // Don't handle byval struct arguments or VLAs, for example.
352 // Note that if we have a byval struct argument, fast ISel is turned off;
353 // those are handled in SelectionDAGBuilder.
355 DenseMap<const AllocaInst*, int>::iterator SI =
356 StaticAllocaMap.find(AI);
357 if (SI == StaticAllocaMap.end()) break; // VLAs.
359 if (!DI->getDebugLoc().isUnknown())
360 MF.getMMI().setVariableDbgInfo(DI->getVariable(), FI, DI->getDebugLoc());
362 // Building the map above is target independent. Generating DBG_VALUE
363 // inline is target dependent; do this now.
364 (void)TargetSelectInstruction(cast<Instruction>(I));
367 case Intrinsic::dbg_value: {
368 // This form of DBG_VALUE is target-independent.
369 const DbgValueInst *DI = cast<DbgValueInst>(I);
370 const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
371 const Value *V = DI->getValue();
373 // Currently the optimizer can produce this; insert an undef to
374 // help debugging. Probably the optimizer should not do this.
375 BuildMI(MBB, DL, II).addReg(0U).addImm(DI->getOffset()).
376 addMetadata(DI->getVariable());
377 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
378 BuildMI(MBB, DL, II).addImm(CI->getZExtValue()).addImm(DI->getOffset()).
379 addMetadata(DI->getVariable());
380 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
381 BuildMI(MBB, DL, II).addFPImm(CF).addImm(DI->getOffset()).
382 addMetadata(DI->getVariable());
383 } else if (unsigned Reg = lookUpRegForValue(V)) {
384 BuildMI(MBB, DL, II).addReg(Reg, RegState::Debug).addImm(DI->getOffset()).
385 addMetadata(DI->getVariable());
387 // We can't yet handle anything else here because it would require
388 // generating code, thus altering codegen because of debug info.
389 // Insert an undef so we can see what we dropped.
390 BuildMI(MBB, DL, II).addReg(0U).addImm(DI->getOffset()).
391 addMetadata(DI->getVariable());
395 case Intrinsic::eh_exception: {
396 EVT VT = TLI.getValueType(I->getType());
397 switch (TLI.getOperationAction(ISD::EXCEPTIONADDR, VT)) {
399 case TargetLowering::Expand: {
400 assert(MBB->isLandingPad() && "Call to eh.exception not in landing pad!");
401 unsigned Reg = TLI.getExceptionAddressRegister();
402 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
403 unsigned ResultReg = createResultReg(RC);
404 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
406 assert(InsertedCopy && "Can't copy address registers!");
407 InsertedCopy = InsertedCopy;
408 UpdateValueMap(I, ResultReg);
414 case Intrinsic::eh_selector: {
415 EVT VT = TLI.getValueType(I->getType());
416 switch (TLI.getOperationAction(ISD::EHSELECTION, VT)) {
418 case TargetLowering::Expand: {
419 if (MBB->isLandingPad())
420 AddCatchInfo(*cast<CallInst>(I), &MF.getMMI(), MBB);
423 CatchInfoLost.insert(cast<CallInst>(I));
425 // FIXME: Mark exception selector register as live in. Hack for PR1508.
426 unsigned Reg = TLI.getExceptionSelectorRegister();
427 if (Reg) MBB->addLiveIn(Reg);
430 unsigned Reg = TLI.getExceptionSelectorRegister();
431 EVT SrcVT = TLI.getPointerTy();
432 const TargetRegisterClass *RC = TLI.getRegClassFor(SrcVT);
433 unsigned ResultReg = createResultReg(RC);
434 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, Reg,
436 assert(InsertedCopy && "Can't copy address registers!");
437 InsertedCopy = InsertedCopy;
439 // Cast the register to the type of the selector.
440 if (SrcVT.bitsGT(MVT::i32))
441 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32, ISD::TRUNCATE,
443 else if (SrcVT.bitsLT(MVT::i32))
444 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32,
445 ISD::SIGN_EXTEND, ResultReg);
447 // Unhandled operand. Halt "fast" selection and bail.
450 UpdateValueMap(I, ResultReg);
459 // An arbitrary call. Bail.
463 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
464 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
465 EVT DstVT = TLI.getValueType(I->getType());
467 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
468 DstVT == MVT::Other || !DstVT.isSimple())
469 // Unhandled type. Halt "fast" selection and bail.
472 // Check if the destination type is legal. Or as a special case,
473 // it may be i1 if we're doing a truncate because that's
474 // easy and somewhat common.
475 if (!TLI.isTypeLegal(DstVT))
476 if (DstVT != MVT::i1 || Opcode != ISD::TRUNCATE)
477 // Unhandled type. Halt "fast" selection and bail.
480 // Check if the source operand is legal. Or as a special case,
481 // it may be i1 if we're doing zero-extension because that's
482 // easy and somewhat common.
483 if (!TLI.isTypeLegal(SrcVT))
484 if (SrcVT != MVT::i1 || Opcode != ISD::ZERO_EXTEND)
485 // Unhandled type. Halt "fast" selection and bail.
488 unsigned InputReg = getRegForValue(I->getOperand(0));
490 // Unhandled operand. Halt "fast" selection and bail.
493 // If the operand is i1, arrange for the high bits in the register to be zero.
494 if (SrcVT == MVT::i1) {
495 SrcVT = TLI.getTypeToTransformTo(I->getContext(), SrcVT);
496 InputReg = FastEmitZExtFromI1(SrcVT.getSimpleVT(), InputReg);
500 // If the result is i1, truncate to the target's type for i1 first.
501 if (DstVT == MVT::i1)
502 DstVT = TLI.getTypeToTransformTo(I->getContext(), DstVT);
504 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
511 UpdateValueMap(I, ResultReg);
515 bool FastISel::SelectBitCast(const User *I) {
516 // If the bitcast doesn't change the type, just use the operand value.
517 if (I->getType() == I->getOperand(0)->getType()) {
518 unsigned Reg = getRegForValue(I->getOperand(0));
521 UpdateValueMap(I, Reg);
525 // Bitcasts of other values become reg-reg copies or BIT_CONVERT operators.
526 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
527 EVT DstVT = TLI.getValueType(I->getType());
529 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
530 DstVT == MVT::Other || !DstVT.isSimple() ||
531 !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
532 // Unhandled type. Halt "fast" selection and bail.
535 unsigned Op0 = getRegForValue(I->getOperand(0));
537 // Unhandled operand. Halt "fast" selection and bail.
540 // First, try to perform the bitcast by inserting a reg-reg copy.
541 unsigned ResultReg = 0;
542 if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
543 TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
544 TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
545 ResultReg = createResultReg(DstClass);
547 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
548 Op0, DstClass, SrcClass);
553 // If the reg-reg copy failed, select a BIT_CONVERT opcode.
555 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
556 ISD::BIT_CONVERT, Op0);
561 UpdateValueMap(I, ResultReg);
566 FastISel::SelectInstruction(const Instruction *I) {
567 // Just before the terminator instruction, insert instructions to
568 // feed PHI nodes in successor blocks.
569 if (isa<TerminatorInst>(I))
570 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
573 DL = I->getDebugLoc();
575 // First, try doing target-independent selection.
576 if (SelectOperator(I, I->getOpcode())) {
581 // Next, try calling the target to attempt to handle the instruction.
582 if (TargetSelectInstruction(I)) {
591 /// FastEmitBranch - Emit an unconditional branch to the given block,
592 /// unless it is the immediate (fall-through) successor, and update
595 FastISel::FastEmitBranch(MachineBasicBlock *MSucc) {
596 if (MBB->isLayoutSuccessor(MSucc)) {
597 // The unconditional fall-through case, which needs no instructions.
599 // The unconditional branch case.
600 TII.InsertBranch(*MBB, MSucc, NULL, SmallVector<MachineOperand, 0>());
602 MBB->addSuccessor(MSucc);
605 /// SelectFNeg - Emit an FNeg operation.
608 FastISel::SelectFNeg(const User *I) {
609 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
610 if (OpReg == 0) return false;
612 // If the target has ISD::FNEG, use it.
613 EVT VT = TLI.getValueType(I->getType());
614 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
616 if (ResultReg != 0) {
617 UpdateValueMap(I, ResultReg);
621 // Bitcast the value to integer, twiddle the sign bit with xor,
622 // and then bitcast it back to floating-point.
623 if (VT.getSizeInBits() > 64) return false;
624 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
625 if (!TLI.isTypeLegal(IntVT))
628 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
629 ISD::BIT_CONVERT, OpReg);
633 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR, IntReg,
634 UINT64_C(1) << (VT.getSizeInBits()-1),
635 IntVT.getSimpleVT());
636 if (IntResultReg == 0)
639 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
640 ISD::BIT_CONVERT, IntResultReg);
644 UpdateValueMap(I, ResultReg);
649 FastISel::SelectOperator(const User *I, unsigned Opcode) {
651 case Instruction::Add:
652 return SelectBinaryOp(I, ISD::ADD);
653 case Instruction::FAdd:
654 return SelectBinaryOp(I, ISD::FADD);
655 case Instruction::Sub:
656 return SelectBinaryOp(I, ISD::SUB);
657 case Instruction::FSub:
658 // FNeg is currently represented in LLVM IR as a special case of FSub.
659 if (BinaryOperator::isFNeg(I))
660 return SelectFNeg(I);
661 return SelectBinaryOp(I, ISD::FSUB);
662 case Instruction::Mul:
663 return SelectBinaryOp(I, ISD::MUL);
664 case Instruction::FMul:
665 return SelectBinaryOp(I, ISD::FMUL);
666 case Instruction::SDiv:
667 return SelectBinaryOp(I, ISD::SDIV);
668 case Instruction::UDiv:
669 return SelectBinaryOp(I, ISD::UDIV);
670 case Instruction::FDiv:
671 return SelectBinaryOp(I, ISD::FDIV);
672 case Instruction::SRem:
673 return SelectBinaryOp(I, ISD::SREM);
674 case Instruction::URem:
675 return SelectBinaryOp(I, ISD::UREM);
676 case Instruction::FRem:
677 return SelectBinaryOp(I, ISD::FREM);
678 case Instruction::Shl:
679 return SelectBinaryOp(I, ISD::SHL);
680 case Instruction::LShr:
681 return SelectBinaryOp(I, ISD::SRL);
682 case Instruction::AShr:
683 return SelectBinaryOp(I, ISD::SRA);
684 case Instruction::And:
685 return SelectBinaryOp(I, ISD::AND);
686 case Instruction::Or:
687 return SelectBinaryOp(I, ISD::OR);
688 case Instruction::Xor:
689 return SelectBinaryOp(I, ISD::XOR);
691 case Instruction::GetElementPtr:
692 return SelectGetElementPtr(I);
694 case Instruction::Br: {
695 const BranchInst *BI = cast<BranchInst>(I);
697 if (BI->isUnconditional()) {
698 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
699 MachineBasicBlock *MSucc = MBBMap[LLVMSucc];
700 FastEmitBranch(MSucc);
704 // Conditional branches are not handed yet.
705 // Halt "fast" selection and bail.
709 case Instruction::Unreachable:
713 case Instruction::Alloca:
714 // FunctionLowering has the static-sized case covered.
715 if (StaticAllocaMap.count(cast<AllocaInst>(I)))
718 // Dynamic-sized alloca is not handled yet.
721 case Instruction::Call:
722 return SelectCall(I);
724 case Instruction::BitCast:
725 return SelectBitCast(I);
727 case Instruction::FPToSI:
728 return SelectCast(I, ISD::FP_TO_SINT);
729 case Instruction::ZExt:
730 return SelectCast(I, ISD::ZERO_EXTEND);
731 case Instruction::SExt:
732 return SelectCast(I, ISD::SIGN_EXTEND);
733 case Instruction::Trunc:
734 return SelectCast(I, ISD::TRUNCATE);
735 case Instruction::SIToFP:
736 return SelectCast(I, ISD::SINT_TO_FP);
738 case Instruction::IntToPtr: // Deliberate fall-through.
739 case Instruction::PtrToInt: {
740 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
741 EVT DstVT = TLI.getValueType(I->getType());
742 if (DstVT.bitsGT(SrcVT))
743 return SelectCast(I, ISD::ZERO_EXTEND);
744 if (DstVT.bitsLT(SrcVT))
745 return SelectCast(I, ISD::TRUNCATE);
746 unsigned Reg = getRegForValue(I->getOperand(0));
747 if (Reg == 0) return false;
748 UpdateValueMap(I, Reg);
752 case Instruction::PHI:
753 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
756 // Unhandled instruction. Halt "fast" selection and bail.
761 FastISel::FastISel(MachineFunction &mf,
762 DenseMap<const Value *, unsigned> &vm,
763 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm,
764 DenseMap<const AllocaInst *, int> &am,
765 std::vector<std::pair<MachineInstr*, unsigned> > &pn
767 , SmallSet<const Instruction *, 8> &cil
774 PHINodesToUpdate(pn),
779 MRI(MF.getRegInfo()),
780 MFI(*MF.getFrameInfo()),
781 MCP(*MF.getConstantPool()),
783 TD(*TM.getTargetData()),
784 TII(*TM.getInstrInfo()),
785 TLI(*TM.getTargetLowering()),
789 FastISel::~FastISel() {}
791 unsigned FastISel::FastEmit_(MVT, MVT,
796 unsigned FastISel::FastEmit_r(MVT, MVT,
797 unsigned, unsigned /*Op0*/) {
801 unsigned FastISel::FastEmit_rr(MVT, MVT,
802 unsigned, unsigned /*Op0*/,
807 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
811 unsigned FastISel::FastEmit_f(MVT, MVT,
812 unsigned, const ConstantFP * /*FPImm*/) {
816 unsigned FastISel::FastEmit_ri(MVT, MVT,
817 unsigned, unsigned /*Op0*/,
822 unsigned FastISel::FastEmit_rf(MVT, MVT,
823 unsigned, unsigned /*Op0*/,
824 const ConstantFP * /*FPImm*/) {
828 unsigned FastISel::FastEmit_rri(MVT, MVT,
830 unsigned /*Op0*/, unsigned /*Op1*/,
835 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
836 /// to emit an instruction with an immediate operand using FastEmit_ri.
837 /// If that fails, it materializes the immediate into a register and try
838 /// FastEmit_rr instead.
839 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
840 unsigned Op0, uint64_t Imm,
842 // First check if immediate type is legal. If not, we can't use the ri form.
843 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Imm);
846 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
847 if (MaterialReg == 0)
849 return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
852 /// FastEmit_rf_ - This method is a wrapper of FastEmit_ri. It first tries
853 /// to emit an instruction with a floating-point immediate operand using
854 /// FastEmit_rf. If that fails, it materializes the immediate into a register
855 /// and try FastEmit_rr instead.
856 unsigned FastISel::FastEmit_rf_(MVT VT, unsigned Opcode,
857 unsigned Op0, const ConstantFP *FPImm,
859 // First check if immediate type is legal. If not, we can't use the rf form.
860 unsigned ResultReg = FastEmit_rf(VT, VT, Opcode, Op0, FPImm);
864 // Materialize the constant in a register.
865 unsigned MaterialReg = FastEmit_f(ImmType, ImmType, ISD::ConstantFP, FPImm);
866 if (MaterialReg == 0) {
867 // If the target doesn't have a way to directly enter a floating-point
868 // value into a register, use an alternate approach.
869 // TODO: The current approach only supports floating-point constants
870 // that can be constructed by conversion from integer values. This should
871 // be replaced by code that creates a load from a constant-pool entry,
872 // which will require some target-specific work.
873 const APFloat &Flt = FPImm->getValueAPF();
874 EVT IntVT = TLI.getPointerTy();
877 uint32_t IntBitWidth = IntVT.getSizeInBits();
879 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
880 APFloat::rmTowardZero, &isExact);
883 APInt IntVal(IntBitWidth, 2, x);
885 unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(),
886 ISD::Constant, IntVal.getZExtValue());
889 MaterialReg = FastEmit_r(IntVT.getSimpleVT(), VT,
890 ISD::SINT_TO_FP, IntegerReg);
891 if (MaterialReg == 0)
894 return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
897 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
898 return MRI.createVirtualRegister(RC);
901 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
902 const TargetRegisterClass* RC) {
903 unsigned ResultReg = createResultReg(RC);
904 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
906 BuildMI(MBB, DL, II, ResultReg);
910 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
911 const TargetRegisterClass *RC,
913 unsigned ResultReg = createResultReg(RC);
914 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
916 if (II.getNumDefs() >= 1)
917 BuildMI(MBB, DL, II, ResultReg).addReg(Op0);
919 BuildMI(MBB, DL, II).addReg(Op0);
920 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
921 II.ImplicitDefs[0], RC, RC);
929 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
930 const TargetRegisterClass *RC,
931 unsigned Op0, unsigned Op1) {
932 unsigned ResultReg = createResultReg(RC);
933 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
935 if (II.getNumDefs() >= 1)
936 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addReg(Op1);
938 BuildMI(MBB, DL, II).addReg(Op0).addReg(Op1);
939 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
940 II.ImplicitDefs[0], RC, RC);
947 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
948 const TargetRegisterClass *RC,
949 unsigned Op0, uint64_t Imm) {
950 unsigned ResultReg = createResultReg(RC);
951 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
953 if (II.getNumDefs() >= 1)
954 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addImm(Imm);
956 BuildMI(MBB, DL, II).addReg(Op0).addImm(Imm);
957 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
958 II.ImplicitDefs[0], RC, RC);
965 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
966 const TargetRegisterClass *RC,
967 unsigned Op0, const ConstantFP *FPImm) {
968 unsigned ResultReg = createResultReg(RC);
969 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
971 if (II.getNumDefs() >= 1)
972 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addFPImm(FPImm);
974 BuildMI(MBB, DL, II).addReg(Op0).addFPImm(FPImm);
975 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
976 II.ImplicitDefs[0], RC, RC);
983 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
984 const TargetRegisterClass *RC,
985 unsigned Op0, unsigned Op1, uint64_t Imm) {
986 unsigned ResultReg = createResultReg(RC);
987 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
989 if (II.getNumDefs() >= 1)
990 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addReg(Op1).addImm(Imm);
992 BuildMI(MBB, DL, II).addReg(Op0).addReg(Op1).addImm(Imm);
993 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
994 II.ImplicitDefs[0], RC, RC);
1001 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1002 const TargetRegisterClass *RC,
1004 unsigned ResultReg = createResultReg(RC);
1005 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1007 if (II.getNumDefs() >= 1)
1008 BuildMI(MBB, DL, II, ResultReg).addImm(Imm);
1010 BuildMI(MBB, DL, II).addImm(Imm);
1011 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1012 II.ImplicitDefs[0], RC, RC);
1019 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1020 unsigned Op0, uint32_t Idx) {
1021 const TargetRegisterClass* RC = MRI.getRegClass(Op0);
1023 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1024 const TargetInstrDesc &II = TII.get(TargetOpcode::EXTRACT_SUBREG);
1026 if (II.getNumDefs() >= 1)
1027 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addImm(Idx);
1029 BuildMI(MBB, DL, II).addReg(Op0).addImm(Idx);
1030 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
1031 II.ImplicitDefs[0], RC, RC);
1038 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1039 /// with all but the least significant bit set to zero.
1040 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op) {
1041 return FastEmit_ri(VT, VT, ISD::AND, Op, 1);
1044 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1045 /// Emit code to ensure constants are copied into registers when needed.
1046 /// Remember the virtual registers that need to be added to the Machine PHI
1047 /// nodes as input. We cannot just directly add them, because expansion
1048 /// might result in multiple MBB's for one BB. As such, the start of the
1049 /// BB might correspond to a different MBB than the end.
1050 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1051 const TerminatorInst *TI = LLVMBB->getTerminator();
1053 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1054 unsigned OrigNumPHINodesToUpdate = PHINodesToUpdate.size();
1056 // Check successor nodes' PHI nodes that expect a constant to be available
1058 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1059 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1060 if (!isa<PHINode>(SuccBB->begin())) continue;
1061 MachineBasicBlock *SuccMBB = MBBMap[SuccBB];
1063 // If this terminator has multiple identical successors (common for
1064 // switches), only handle each succ once.
1065 if (!SuccsHandled.insert(SuccMBB)) continue;
1067 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1069 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1070 // nodes and Machine PHI nodes, but the incoming operands have not been
1072 for (BasicBlock::const_iterator I = SuccBB->begin();
1073 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1074 // Ignore dead phi's.
1075 if (PN->use_empty()) continue;
1077 // Only handle legal types. Two interesting things to note here. First,
1078 // by bailing out early, we may leave behind some dead instructions,
1079 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1080 // own moves. Second, this check is necessary becuase FastISel doesn't
1081 // use CreateRegForValue to create registers, so it always creates
1082 // exactly one register for each non-void instruction.
1083 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1084 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1087 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1089 PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1094 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1096 unsigned Reg = getRegForValue(PHIOp);
1098 PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1101 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));