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/FunctionLoweringInfo.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/Analysis/DebugInfo.h"
52 #include "llvm/Analysis/Loads.h"
53 #include "llvm/Target/TargetData.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetLowering.h"
56 #include "llvm/Target/TargetMachine.h"
57 #include "llvm/Support/ErrorHandling.h"
60 /// startNewBlock - Set the current block to which generated machine
61 /// instructions will be appended, and clear the local CSE map.
63 void FastISel::startNewBlock() {
64 LocalValueMap.clear();
66 // Start out as end(), meaining no local-value instructions have
68 LastLocalValue = FuncInfo.MBB->end();
71 bool FastISel::hasTrivialKill(const Value *V) const {
72 // Don't consider constants or arguments to have trivial kills.
73 const Instruction *I = dyn_cast<Instruction>(V);
77 // No-op casts are trivially coalesced by fast-isel.
78 if (const CastInst *Cast = dyn_cast<CastInst>(I))
79 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
80 !hasTrivialKill(Cast->getOperand(0)))
83 // Only instructions with a single use in the same basic block are considered
84 // to have trivial kills.
85 return I->hasOneUse() &&
86 !(I->getOpcode() == Instruction::BitCast ||
87 I->getOpcode() == Instruction::PtrToInt ||
88 I->getOpcode() == Instruction::IntToPtr) &&
89 cast<Instruction>(I->use_begin())->getParent() == I->getParent();
92 unsigned FastISel::getRegForValue(const Value *V) {
93 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
94 // Don't handle non-simple values in FastISel.
95 if (!RealVT.isSimple())
98 // Ignore illegal types. We must do this before looking up the value
99 // in ValueMap because Arguments are given virtual registers regardless
100 // of whether FastISel can handle them.
101 MVT VT = RealVT.getSimpleVT();
102 if (!TLI.isTypeLegal(VT)) {
103 // Promote MVT::i1 to a legal type though, because it's common and easy.
105 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
110 // Look up the value to see if we already have a register for it. We
111 // cache values defined by Instructions across blocks, and other values
112 // only locally. This is because Instructions already have the SSA
113 // def-dominates-use requirement enforced.
114 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
115 if (I != FuncInfo.ValueMap.end())
117 unsigned Reg = LocalValueMap[V];
121 // In bottom-up mode, just create the virtual register which will be used
122 // to hold the value. It will be materialized later.
123 if (isa<Instruction>(V)) {
124 Reg = createResultReg(TLI.getRegClassFor(VT));
125 FuncInfo.ValueMap[V] = Reg;
129 return materializeRegForValue(V, VT);
132 /// materializeRegForValue - Helper for getRegForVale. This function is
133 /// called when the value isn't already available in a register and must
134 /// be materialized with new instructions.
135 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
138 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
139 if (CI->getValue().getActiveBits() <= 64)
140 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
141 } else if (isa<AllocaInst>(V)) {
142 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
143 } else if (isa<ConstantPointerNull>(V)) {
144 // Translate this as an integer zero so that it can be
145 // local-CSE'd with actual integer zeros.
147 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
148 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
149 // Try to emit the constant directly.
150 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
153 // Try to emit the constant by using an integer constant with a cast.
154 const APFloat &Flt = CF->getValueAPF();
155 EVT IntVT = TLI.getPointerTy();
158 uint32_t IntBitWidth = IntVT.getSizeInBits();
160 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
161 APFloat::rmTowardZero, &isExact);
163 APInt IntVal(IntBitWidth, 2, x);
165 unsigned IntegerReg =
166 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
168 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
169 IntegerReg, /*Kill=*/false);
172 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
173 if (!SelectOperator(Op, Op->getOpcode()))
174 if (!isa<Instruction>(Op) ||
175 !TargetSelectInstruction(cast<Instruction>(Op)))
177 Reg = lookUpRegForValue(Op);
178 } else if (isa<UndefValue>(V)) {
179 Reg = createResultReg(TLI.getRegClassFor(VT));
180 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
181 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
184 // If target-independent code couldn't handle the value, give target-specific
186 if (!Reg && isa<Constant>(V))
187 Reg = TargetMaterializeConstant(cast<Constant>(V));
189 // Don't cache constant materializations in the general ValueMap.
190 // To do so would require tracking what uses they dominate.
192 LocalValueMap[V] = Reg;
193 LastLocalValue = MRI.getVRegDef(Reg);
198 unsigned FastISel::lookUpRegForValue(const Value *V) {
199 // Look up the value to see if we already have a register for it. We
200 // cache values defined by Instructions across blocks, and other values
201 // only locally. This is because Instructions already have the SSA
202 // def-dominates-use requirement enforced.
203 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
204 if (I != FuncInfo.ValueMap.end())
206 return LocalValueMap[V];
209 /// UpdateValueMap - Update the value map to include the new mapping for this
210 /// instruction, or insert an extra copy to get the result in a previous
211 /// determined register.
212 /// NOTE: This is only necessary because we might select a block that uses
213 /// a value before we select the block that defines the value. It might be
214 /// possible to fix this by selecting blocks in reverse postorder.
215 unsigned FastISel::UpdateValueMap(const Value *I, unsigned Reg) {
216 if (!isa<Instruction>(I)) {
217 LocalValueMap[I] = Reg;
221 unsigned &AssignedReg = FuncInfo.ValueMap[I];
222 if (AssignedReg == 0)
223 // Use the new register.
225 else if (Reg != AssignedReg) {
226 // We already have a register for this value. Replace uses of
227 // the existing register with uses of the new one.
228 MRI.replaceRegWith(AssignedReg, Reg);
229 // Replace uses of the existing register in PHINodesToUpdate too.
230 for (unsigned i = 0, e = FuncInfo.PHINodesToUpdate.size(); i != e; ++i)
231 if (FuncInfo.PHINodesToUpdate[i].second == AssignedReg)
232 FuncInfo.PHINodesToUpdate[i].second = Reg;
233 // And update the ValueMap.
240 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
241 unsigned IdxN = getRegForValue(Idx);
243 // Unhandled operand. Halt "fast" selection and bail.
244 return std::pair<unsigned, bool>(0, false);
246 bool IdxNIsKill = hasTrivialKill(Idx);
248 // If the index is smaller or larger than intptr_t, truncate or extend it.
249 MVT PtrVT = TLI.getPointerTy();
250 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
251 if (IdxVT.bitsLT(PtrVT)) {
252 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
256 else if (IdxVT.bitsGT(PtrVT)) {
257 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
261 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
264 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
265 /// which has an opcode which directly corresponds to the given ISD opcode.
267 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
268 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
269 if (VT == MVT::Other || !VT.isSimple())
270 // Unhandled type. Halt "fast" selection and bail.
273 // We only handle legal types. For example, on x86-32 the instruction
274 // selector contains all of the 64-bit instructions from x86-64,
275 // under the assumption that i64 won't be used if the target doesn't
277 if (!TLI.isTypeLegal(VT)) {
278 // MVT::i1 is special. Allow AND, OR, or XOR because they
279 // don't require additional zeroing, which makes them easy.
281 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
282 ISDOpcode == ISD::XOR))
283 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
288 unsigned Op0 = getRegForValue(I->getOperand(0));
290 // Unhandled operand. Halt "fast" selection and bail.
293 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
295 // Check if the second operand is a constant and handle it appropriately.
296 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
297 unsigned ResultReg = FastEmit_ri(VT.getSimpleVT(), VT.getSimpleVT(),
298 ISDOpcode, Op0, Op0IsKill,
300 if (ResultReg != 0) {
301 // We successfully emitted code for the given LLVM Instruction.
302 UpdateValueMap(I, ResultReg);
307 // Check if the second operand is a constant float.
308 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
309 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
310 ISDOpcode, Op0, Op0IsKill, CF);
311 if (ResultReg != 0) {
312 // We successfully emitted code for the given LLVM Instruction.
313 UpdateValueMap(I, ResultReg);
318 unsigned Op1 = getRegForValue(I->getOperand(1));
320 // Unhandled operand. Halt "fast" selection and bail.
323 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
325 // Now we have both operands in registers. Emit the instruction.
326 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
331 // Target-specific code wasn't able to find a machine opcode for
332 // the given ISD opcode and type. Halt "fast" selection and bail.
335 // We successfully emitted code for the given LLVM Instruction.
336 UpdateValueMap(I, ResultReg);
340 bool FastISel::SelectGetElementPtr(const User *I) {
341 unsigned N = getRegForValue(I->getOperand(0));
343 // Unhandled operand. Halt "fast" selection and bail.
346 bool NIsKill = hasTrivialKill(I->getOperand(0));
348 const Type *Ty = I->getOperand(0)->getType();
349 MVT VT = TLI.getPointerTy();
350 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
351 E = I->op_end(); OI != E; ++OI) {
352 const Value *Idx = *OI;
353 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
354 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
357 uint64_t Offs = TD.getStructLayout(StTy)->getElementOffset(Field);
358 // FIXME: This can be optimized by combining the add with a
360 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, Offs, VT);
362 // Unhandled operand. Halt "fast" selection and bail.
366 Ty = StTy->getElementType(Field);
368 Ty = cast<SequentialType>(Ty)->getElementType();
370 // If this is a constant subscript, handle it quickly.
371 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
372 if (CI->isZero()) continue;
374 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
375 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, Offs, VT);
377 // Unhandled operand. Halt "fast" selection and bail.
383 // N = N + Idx * ElementSize;
384 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
385 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
386 unsigned IdxN = Pair.first;
387 bool IdxNIsKill = Pair.second;
389 // Unhandled operand. Halt "fast" selection and bail.
392 if (ElementSize != 1) {
393 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
395 // Unhandled operand. Halt "fast" selection and bail.
399 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
401 // Unhandled operand. Halt "fast" selection and bail.
406 // We successfully emitted code for the given LLVM Instruction.
407 UpdateValueMap(I, N);
411 bool FastISel::SelectCall(const User *I) {
412 const Function *F = cast<CallInst>(I)->getCalledFunction();
413 if (!F) return false;
415 // Handle selected intrinsic function calls.
416 unsigned IID = F->getIntrinsicID();
419 case Intrinsic::dbg_declare: {
420 const DbgDeclareInst *DI = cast<DbgDeclareInst>(I);
421 if (!DIVariable(DI->getVariable()).Verify() ||
422 !FuncInfo.MF->getMMI().hasDebugInfo())
425 const Value *Address = DI->getAddress();
428 if (isa<UndefValue>(Address))
430 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
431 // Don't handle byval struct arguments or VLAs, for example.
432 // Note that if we have a byval struct argument, fast ISel is turned off;
433 // those are handled in SelectionDAGBuilder.
435 DenseMap<const AllocaInst*, int>::iterator SI =
436 FuncInfo.StaticAllocaMap.find(AI);
437 if (SI == FuncInfo.StaticAllocaMap.end()) break; // VLAs.
439 if (!DI->getDebugLoc().isUnknown())
440 FuncInfo.MF->getMMI().setVariableDbgInfo(DI->getVariable(),
441 FI, DI->getDebugLoc());
443 // Building the map above is target independent. Generating DBG_VALUE
444 // inline is target dependent; do this now.
445 (void)TargetSelectInstruction(cast<Instruction>(I));
448 case Intrinsic::dbg_value: {
449 // This form of DBG_VALUE is target-independent.
450 const DbgValueInst *DI = cast<DbgValueInst>(I);
451 const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
452 const Value *V = DI->getValue();
454 // Currently the optimizer can produce this; insert an undef to
455 // help debugging. Probably the optimizer should not do this.
456 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
457 .addReg(0U).addImm(DI->getOffset())
458 .addMetadata(DI->getVariable());
459 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
460 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
461 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
462 .addMetadata(DI->getVariable());
463 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
465 .addFPImm(CF).addImm(DI->getOffset())
466 .addMetadata(DI->getVariable());
467 } else if (unsigned Reg = lookUpRegForValue(V)) {
468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
469 .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
470 .addMetadata(DI->getVariable());
472 // We can't yet handle anything else here because it would require
473 // generating code, thus altering codegen because of debug info.
474 // Insert an undef so we can see what we dropped.
475 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
476 .addReg(0U).addImm(DI->getOffset())
477 .addMetadata(DI->getVariable());
481 case Intrinsic::eh_exception: {
482 EVT VT = TLI.getValueType(I->getType());
483 switch (TLI.getOperationAction(ISD::EXCEPTIONADDR, VT)) {
485 case TargetLowering::Expand: {
486 assert(FuncInfo.MBB->isLandingPad() &&
487 "Call to eh.exception not in landing pad!");
488 unsigned Reg = TLI.getExceptionAddressRegister();
489 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
490 unsigned ResultReg = createResultReg(RC);
491 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
492 ResultReg, Reg, RC, RC, DL);
493 assert(InsertedCopy && "Can't copy address registers!");
494 InsertedCopy = InsertedCopy;
495 UpdateValueMap(I, ResultReg);
501 case Intrinsic::eh_selector: {
502 EVT VT = TLI.getValueType(I->getType());
503 switch (TLI.getOperationAction(ISD::EHSELECTION, VT)) {
505 case TargetLowering::Expand: {
506 if (FuncInfo.MBB->isLandingPad())
507 AddCatchInfo(*cast<CallInst>(I), &FuncInfo.MF->getMMI(), FuncInfo.MBB);
510 FuncInfo.CatchInfoLost.insert(cast<CallInst>(I));
512 // FIXME: Mark exception selector register as live in. Hack for PR1508.
513 unsigned Reg = TLI.getExceptionSelectorRegister();
514 if (Reg) FuncInfo.MBB->addLiveIn(Reg);
517 unsigned Reg = TLI.getExceptionSelectorRegister();
518 EVT SrcVT = TLI.getPointerTy();
519 const TargetRegisterClass *RC = TLI.getRegClassFor(SrcVT);
520 unsigned ResultReg = createResultReg(RC);
521 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
522 ResultReg, Reg, RC, RC, DL);
523 assert(InsertedCopy && "Can't copy address registers!");
524 InsertedCopy = InsertedCopy;
526 bool ResultRegIsKill = hasTrivialKill(I);
528 // Cast the register to the type of the selector.
529 if (SrcVT.bitsGT(MVT::i32))
530 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32, ISD::TRUNCATE,
531 ResultReg, ResultRegIsKill);
532 else if (SrcVT.bitsLT(MVT::i32))
533 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32,
534 ISD::SIGN_EXTEND, ResultReg, ResultRegIsKill);
536 // Unhandled operand. Halt "fast" selection and bail.
539 UpdateValueMap(I, ResultReg);
548 // An arbitrary call. Bail.
552 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
553 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
554 EVT DstVT = TLI.getValueType(I->getType());
556 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
557 DstVT == MVT::Other || !DstVT.isSimple())
558 // Unhandled type. Halt "fast" selection and bail.
561 // Check if the destination type is legal. Or as a special case,
562 // it may be i1 if we're doing a truncate because that's
563 // easy and somewhat common.
564 if (!TLI.isTypeLegal(DstVT))
565 if (DstVT != MVT::i1 || Opcode != ISD::TRUNCATE)
566 // Unhandled type. Halt "fast" selection and bail.
569 // Check if the source operand is legal. Or as a special case,
570 // it may be i1 if we're doing zero-extension because that's
571 // easy and somewhat common.
572 if (!TLI.isTypeLegal(SrcVT))
573 if (SrcVT != MVT::i1 || Opcode != ISD::ZERO_EXTEND)
574 // Unhandled type. Halt "fast" selection and bail.
577 unsigned InputReg = getRegForValue(I->getOperand(0));
579 // Unhandled operand. Halt "fast" selection and bail.
582 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
584 // If the operand is i1, arrange for the high bits in the register to be zero.
585 if (SrcVT == MVT::i1) {
586 SrcVT = TLI.getTypeToTransformTo(I->getContext(), SrcVT);
587 InputReg = FastEmitZExtFromI1(SrcVT.getSimpleVT(), InputReg, InputRegIsKill);
590 InputRegIsKill = true;
592 // If the result is i1, truncate to the target's type for i1 first.
593 if (DstVT == MVT::i1)
594 DstVT = TLI.getTypeToTransformTo(I->getContext(), DstVT);
596 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
599 InputReg, InputRegIsKill);
603 UpdateValueMap(I, ResultReg);
607 bool FastISel::SelectBitCast(const User *I) {
608 // If the bitcast doesn't change the type, just use the operand value.
609 if (I->getType() == I->getOperand(0)->getType()) {
610 unsigned Reg = getRegForValue(I->getOperand(0));
613 UpdateValueMap(I, Reg);
617 // Bitcasts of other values become reg-reg copies or BIT_CONVERT operators.
618 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
619 EVT DstVT = TLI.getValueType(I->getType());
621 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
622 DstVT == MVT::Other || !DstVT.isSimple() ||
623 !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
624 // Unhandled type. Halt "fast" selection and bail.
627 unsigned Op0 = getRegForValue(I->getOperand(0));
629 // Unhandled operand. Halt "fast" selection and bail.
632 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
634 // First, try to perform the bitcast by inserting a reg-reg copy.
635 unsigned ResultReg = 0;
636 if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
637 TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
638 TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
639 ResultReg = createResultReg(DstClass);
641 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
643 DstClass, SrcClass, DL);
648 // If the reg-reg copy failed, select a BIT_CONVERT opcode.
650 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
651 ISD::BIT_CONVERT, Op0, Op0IsKill);
656 UpdateValueMap(I, ResultReg);
661 FastISel::SelectInstruction(const Instruction *I) {
662 // Just before the terminator instruction, insert instructions to
663 // feed PHI nodes in successor blocks.
664 if (isa<TerminatorInst>(I))
665 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
668 DL = I->getDebugLoc();
670 // First, try doing target-independent selection.
671 if (SelectOperator(I, I->getOpcode())) {
676 // Next, try calling the target to attempt to handle the instruction.
677 if (TargetSelectInstruction(I)) {
686 /// FastEmitBranch - Emit an unconditional branch to the given block,
687 /// unless it is the immediate (fall-through) successor, and update
690 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
691 if (FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
692 // The unconditional fall-through case, which needs no instructions.
694 // The unconditional branch case.
695 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
696 SmallVector<MachineOperand, 0>(), DL);
698 FuncInfo.MBB->addSuccessor(MSucc);
701 /// SelectFNeg - Emit an FNeg operation.
704 FastISel::SelectFNeg(const User *I) {
705 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
706 if (OpReg == 0) return false;
708 bool OpRegIsKill = hasTrivialKill(I);
710 // If the target has ISD::FNEG, use it.
711 EVT VT = TLI.getValueType(I->getType());
712 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
713 ISD::FNEG, OpReg, OpRegIsKill);
714 if (ResultReg != 0) {
715 UpdateValueMap(I, ResultReg);
719 // Bitcast the value to integer, twiddle the sign bit with xor,
720 // and then bitcast it back to floating-point.
721 if (VT.getSizeInBits() > 64) return false;
722 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
723 if (!TLI.isTypeLegal(IntVT))
726 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
727 ISD::BIT_CONVERT, OpReg, OpRegIsKill);
731 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
732 IntReg, /*Kill=*/true,
733 UINT64_C(1) << (VT.getSizeInBits()-1),
734 IntVT.getSimpleVT());
735 if (IntResultReg == 0)
738 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
739 ISD::BIT_CONVERT, IntResultReg, /*Kill=*/true);
743 UpdateValueMap(I, ResultReg);
748 FastISel::SelectLoad(const User *I) {
749 LoadInst *LI = const_cast<LoadInst *>(cast<LoadInst>(I));
751 // For a load from an alloca, make a limited effort to find the value
752 // already available in a register, avoiding redundant loads.
753 if (!LI->isVolatile() && isa<AllocaInst>(LI->getPointerOperand())) {
754 BasicBlock::iterator ScanFrom = LI;
755 if (const Value *V = FindAvailableLoadedValue(LI->getPointerOperand(),
756 LI->getParent(), ScanFrom)) {
757 if (!isa<Instruction>(V) ||
758 cast<Instruction>(V)->getParent() == LI->getParent() ||
759 (isa<AllocaInst>(V) && FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V)))) {
760 unsigned ResultReg = getRegForValue(V);
761 if (ResultReg != 0) {
762 UpdateValueMap(I, ResultReg);
773 FastISel::SelectOperator(const User *I, unsigned Opcode) {
775 case Instruction::Load:
776 return SelectLoad(I);
777 case Instruction::Add:
778 return SelectBinaryOp(I, ISD::ADD);
779 case Instruction::FAdd:
780 return SelectBinaryOp(I, ISD::FADD);
781 case Instruction::Sub:
782 return SelectBinaryOp(I, ISD::SUB);
783 case Instruction::FSub:
784 // FNeg is currently represented in LLVM IR as a special case of FSub.
785 if (BinaryOperator::isFNeg(I))
786 return SelectFNeg(I);
787 return SelectBinaryOp(I, ISD::FSUB);
788 case Instruction::Mul:
789 return SelectBinaryOp(I, ISD::MUL);
790 case Instruction::FMul:
791 return SelectBinaryOp(I, ISD::FMUL);
792 case Instruction::SDiv:
793 return SelectBinaryOp(I, ISD::SDIV);
794 case Instruction::UDiv:
795 return SelectBinaryOp(I, ISD::UDIV);
796 case Instruction::FDiv:
797 return SelectBinaryOp(I, ISD::FDIV);
798 case Instruction::SRem:
799 return SelectBinaryOp(I, ISD::SREM);
800 case Instruction::URem:
801 return SelectBinaryOp(I, ISD::UREM);
802 case Instruction::FRem:
803 return SelectBinaryOp(I, ISD::FREM);
804 case Instruction::Shl:
805 return SelectBinaryOp(I, ISD::SHL);
806 case Instruction::LShr:
807 return SelectBinaryOp(I, ISD::SRL);
808 case Instruction::AShr:
809 return SelectBinaryOp(I, ISD::SRA);
810 case Instruction::And:
811 return SelectBinaryOp(I, ISD::AND);
812 case Instruction::Or:
813 return SelectBinaryOp(I, ISD::OR);
814 case Instruction::Xor:
815 return SelectBinaryOp(I, ISD::XOR);
817 case Instruction::GetElementPtr:
818 return SelectGetElementPtr(I);
820 case Instruction::Br: {
821 const BranchInst *BI = cast<BranchInst>(I);
823 if (BI->isUnconditional()) {
824 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
825 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
826 FastEmitBranch(MSucc, BI->getDebugLoc());
830 // Conditional branches are not handed yet.
831 // Halt "fast" selection and bail.
835 case Instruction::Unreachable:
839 case Instruction::Alloca:
840 // FunctionLowering has the static-sized case covered.
841 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
844 // Dynamic-sized alloca is not handled yet.
847 case Instruction::Call:
848 return SelectCall(I);
850 case Instruction::BitCast:
851 return SelectBitCast(I);
853 case Instruction::FPToSI:
854 return SelectCast(I, ISD::FP_TO_SINT);
855 case Instruction::ZExt:
856 return SelectCast(I, ISD::ZERO_EXTEND);
857 case Instruction::SExt:
858 return SelectCast(I, ISD::SIGN_EXTEND);
859 case Instruction::Trunc:
860 return SelectCast(I, ISD::TRUNCATE);
861 case Instruction::SIToFP:
862 return SelectCast(I, ISD::SINT_TO_FP);
864 case Instruction::IntToPtr: // Deliberate fall-through.
865 case Instruction::PtrToInt: {
866 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
867 EVT DstVT = TLI.getValueType(I->getType());
868 if (DstVT.bitsGT(SrcVT))
869 return SelectCast(I, ISD::ZERO_EXTEND);
870 if (DstVT.bitsLT(SrcVT))
871 return SelectCast(I, ISD::TRUNCATE);
872 unsigned Reg = getRegForValue(I->getOperand(0));
873 if (Reg == 0) return false;
874 UpdateValueMap(I, Reg);
878 case Instruction::PHI:
879 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
882 // Unhandled instruction. Halt "fast" selection and bail.
887 FastISel::FastISel(FunctionLoweringInfo &funcInfo)
888 : FuncInfo(funcInfo),
889 MRI(FuncInfo.MF->getRegInfo()),
890 MFI(*FuncInfo.MF->getFrameInfo()),
891 MCP(*FuncInfo.MF->getConstantPool()),
892 TM(FuncInfo.MF->getTarget()),
893 TD(*TM.getTargetData()),
894 TII(*TM.getInstrInfo()),
895 TLI(*TM.getTargetLowering()),
896 TRI(*TM.getRegisterInfo()) {
899 FastISel::~FastISel() {}
901 unsigned FastISel::FastEmit_(MVT, MVT,
906 unsigned FastISel::FastEmit_r(MVT, MVT,
908 unsigned /*Op0*/, bool /*Op0IsKill*/) {
912 unsigned FastISel::FastEmit_rr(MVT, MVT,
914 unsigned /*Op0*/, bool /*Op0IsKill*/,
915 unsigned /*Op1*/, bool /*Op1IsKill*/) {
919 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
923 unsigned FastISel::FastEmit_f(MVT, MVT,
924 unsigned, const ConstantFP * /*FPImm*/) {
928 unsigned FastISel::FastEmit_ri(MVT, MVT,
930 unsigned /*Op0*/, bool /*Op0IsKill*/,
935 unsigned FastISel::FastEmit_rf(MVT, MVT,
937 unsigned /*Op0*/, bool /*Op0IsKill*/,
938 const ConstantFP * /*FPImm*/) {
942 unsigned FastISel::FastEmit_rri(MVT, MVT,
944 unsigned /*Op0*/, bool /*Op0IsKill*/,
945 unsigned /*Op1*/, bool /*Op1IsKill*/,
950 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
951 /// to emit an instruction with an immediate operand using FastEmit_ri.
952 /// If that fails, it materializes the immediate into a register and try
953 /// FastEmit_rr instead.
954 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
955 unsigned Op0, bool Op0IsKill,
956 uint64_t Imm, MVT ImmType) {
957 // First check if immediate type is legal. If not, we can't use the ri form.
958 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
961 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
962 if (MaterialReg == 0)
964 return FastEmit_rr(VT, VT, Opcode,
966 MaterialReg, /*Kill=*/true);
969 /// FastEmit_rf_ - This method is a wrapper of FastEmit_ri. It first tries
970 /// to emit an instruction with a floating-point immediate operand using
971 /// FastEmit_rf. If that fails, it materializes the immediate into a register
972 /// and try FastEmit_rr instead.
973 unsigned FastISel::FastEmit_rf_(MVT VT, unsigned Opcode,
974 unsigned Op0, bool Op0IsKill,
975 const ConstantFP *FPImm, MVT ImmType) {
976 // First check if immediate type is legal. If not, we can't use the rf form.
977 unsigned ResultReg = FastEmit_rf(VT, VT, Opcode, Op0, Op0IsKill, FPImm);
981 // Materialize the constant in a register.
982 unsigned MaterialReg = FastEmit_f(ImmType, ImmType, ISD::ConstantFP, FPImm);
983 if (MaterialReg == 0) {
984 // If the target doesn't have a way to directly enter a floating-point
985 // value into a register, use an alternate approach.
986 // TODO: The current approach only supports floating-point constants
987 // that can be constructed by conversion from integer values. This should
988 // be replaced by code that creates a load from a constant-pool entry,
989 // which will require some target-specific work.
990 const APFloat &Flt = FPImm->getValueAPF();
991 EVT IntVT = TLI.getPointerTy();
994 uint32_t IntBitWidth = IntVT.getSizeInBits();
996 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
997 APFloat::rmTowardZero, &isExact);
1000 APInt IntVal(IntBitWidth, 2, x);
1002 unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(),
1003 ISD::Constant, IntVal.getZExtValue());
1004 if (IntegerReg == 0)
1006 MaterialReg = FastEmit_r(IntVT.getSimpleVT(), VT,
1007 ISD::SINT_TO_FP, IntegerReg, /*Kill=*/true);
1008 if (MaterialReg == 0)
1011 return FastEmit_rr(VT, VT, Opcode,
1013 MaterialReg, /*Kill=*/true);
1016 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1017 return MRI.createVirtualRegister(RC);
1020 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1021 const TargetRegisterClass* RC) {
1022 unsigned ResultReg = createResultReg(RC);
1023 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1025 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1029 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1030 const TargetRegisterClass *RC,
1031 unsigned Op0, bool Op0IsKill) {
1032 unsigned ResultReg = createResultReg(RC);
1033 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1035 if (II.getNumDefs() >= 1)
1036 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1037 .addReg(Op0, Op0IsKill * RegState::Kill);
1039 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1040 .addReg(Op0, Op0IsKill * RegState::Kill);
1041 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
1042 ResultReg, II.ImplicitDefs[0],
1051 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1052 const TargetRegisterClass *RC,
1053 unsigned Op0, bool Op0IsKill,
1054 unsigned Op1, bool Op1IsKill) {
1055 unsigned ResultReg = createResultReg(RC);
1056 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1058 if (II.getNumDefs() >= 1)
1059 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1060 .addReg(Op0, Op0IsKill * RegState::Kill)
1061 .addReg(Op1, Op1IsKill * RegState::Kill);
1063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1064 .addReg(Op0, Op0IsKill * RegState::Kill)
1065 .addReg(Op1, Op1IsKill * RegState::Kill);
1066 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
1067 ResultReg, II.ImplicitDefs[0],
1075 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1076 const TargetRegisterClass *RC,
1077 unsigned Op0, bool Op0IsKill,
1079 unsigned ResultReg = createResultReg(RC);
1080 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1082 if (II.getNumDefs() >= 1)
1083 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1084 .addReg(Op0, Op0IsKill * RegState::Kill)
1087 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1088 .addReg(Op0, Op0IsKill * RegState::Kill)
1090 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
1091 ResultReg, II.ImplicitDefs[0],
1099 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1100 const TargetRegisterClass *RC,
1101 unsigned Op0, bool Op0IsKill,
1102 const ConstantFP *FPImm) {
1103 unsigned ResultReg = createResultReg(RC);
1104 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1106 if (II.getNumDefs() >= 1)
1107 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1108 .addReg(Op0, Op0IsKill * RegState::Kill)
1111 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1112 .addReg(Op0, Op0IsKill * RegState::Kill)
1114 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
1115 ResultReg, II.ImplicitDefs[0],
1123 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1124 const TargetRegisterClass *RC,
1125 unsigned Op0, bool Op0IsKill,
1126 unsigned Op1, bool Op1IsKill,
1128 unsigned ResultReg = createResultReg(RC);
1129 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1131 if (II.getNumDefs() >= 1)
1132 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1133 .addReg(Op0, Op0IsKill * RegState::Kill)
1134 .addReg(Op1, Op1IsKill * RegState::Kill)
1137 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1138 .addReg(Op0, Op0IsKill * RegState::Kill)
1139 .addReg(Op1, Op1IsKill * RegState::Kill)
1141 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
1142 ResultReg, II.ImplicitDefs[0],
1150 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1151 const TargetRegisterClass *RC,
1153 unsigned ResultReg = createResultReg(RC);
1154 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
1156 if (II.getNumDefs() >= 1)
1157 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1159 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1160 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
1161 ResultReg, II.ImplicitDefs[0],
1169 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1170 unsigned Op0, bool Op0IsKill,
1172 const TargetRegisterClass* RC = MRI.getRegClass(Op0);
1174 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1175 const TargetInstrDesc &II = TII.get(TargetOpcode::EXTRACT_SUBREG);
1177 if (II.getNumDefs() >= 1)
1178 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1179 .addReg(Op0, Op0IsKill * RegState::Kill)
1182 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1183 .addReg(Op0, Op0IsKill * RegState::Kill)
1185 bool InsertedCopy = TII.copyRegToReg(*FuncInfo.MBB, FuncInfo.InsertPt,
1186 ResultReg, II.ImplicitDefs[0],
1194 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1195 /// with all but the least significant bit set to zero.
1196 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1197 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1200 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1201 /// Emit code to ensure constants are copied into registers when needed.
1202 /// Remember the virtual registers that need to be added to the Machine PHI
1203 /// nodes as input. We cannot just directly add them, because expansion
1204 /// might result in multiple MBB's for one BB. As such, the start of the
1205 /// BB might correspond to a different MBB than the end.
1206 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1207 const TerminatorInst *TI = LLVMBB->getTerminator();
1209 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1210 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1212 // Check successor nodes' PHI nodes that expect a constant to be available
1214 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1215 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1216 if (!isa<PHINode>(SuccBB->begin())) continue;
1217 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1219 // If this terminator has multiple identical successors (common for
1220 // switches), only handle each succ once.
1221 if (!SuccsHandled.insert(SuccMBB)) continue;
1223 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1225 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1226 // nodes and Machine PHI nodes, but the incoming operands have not been
1228 for (BasicBlock::const_iterator I = SuccBB->begin();
1229 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1231 // Ignore dead phi's.
1232 if (PN->use_empty()) continue;
1234 // Only handle legal types. Two interesting things to note here. First,
1235 // by bailing out early, we may leave behind some dead instructions,
1236 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1237 // own moves. Second, this check is necessary becuase FastISel doesn't
1238 // use CreateRegs to create registers, so it always creates
1239 // exactly one register for each non-void instruction.
1240 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1241 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1244 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1246 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1251 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1253 // Set the DebugLoc for the copy. Prefer the location of the operand
1254 // if there is one; use the location of the PHI otherwise.
1255 DL = PN->getDebugLoc();
1256 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1257 DL = Inst->getDebugLoc();
1259 unsigned Reg = getRegForValue(PHIOp);
1261 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1264 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));