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/CodeGen/FastISel.h"
44 #include "llvm/ADT/Optional.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Analysis/Loads.h"
47 #include "llvm/CodeGen/Analysis.h"
48 #include "llvm/CodeGen/FunctionLoweringInfo.h"
49 #include "llvm/CodeGen/MachineInstrBuilder.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/DebugInfo.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalVariable.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/IntrinsicInst.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Target/TargetInstrInfo.h"
62 #include "llvm/Target/TargetLibraryInfo.h"
63 #include "llvm/Target/TargetLowering.h"
64 #include "llvm/Target/TargetMachine.h"
67 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
68 "target-independent selector");
69 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
70 "target-specific selector");
71 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
73 /// startNewBlock - Set the current block to which generated machine
74 /// instructions will be appended, and clear the local CSE map.
76 void FastISel::startNewBlock() {
77 LocalValueMap.clear();
81 // Advance the emit start point past any EH_LABEL instructions.
82 MachineBasicBlock::iterator
83 I = FuncInfo.MBB->begin(), E = FuncInfo.MBB->end();
84 while (I != E && I->getOpcode() == TargetOpcode::EH_LABEL) {
88 LastLocalValue = EmitStartPt;
91 bool FastISel::LowerArguments() {
92 if (!FuncInfo.CanLowerReturn)
93 // Fallback to SDISel argument lowering code to deal with sret pointer
97 if (!FastLowerArguments())
100 // Enter non-dead arguments into ValueMap for uses in non-entry BBs.
101 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
102 E = FuncInfo.Fn->arg_end(); I != E; ++I) {
103 if (!I->use_empty()) {
104 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
105 assert(VI != LocalValueMap.end() && "Missed an argument?");
106 FuncInfo.ValueMap[I] = VI->second;
112 void FastISel::flushLocalValueMap() {
113 LocalValueMap.clear();
114 LastLocalValue = EmitStartPt;
118 bool FastISel::hasTrivialKill(const Value *V) const {
119 // Don't consider constants or arguments to have trivial kills.
120 const Instruction *I = dyn_cast<Instruction>(V);
124 // No-op casts are trivially coalesced by fast-isel.
125 if (const CastInst *Cast = dyn_cast<CastInst>(I))
126 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
127 !hasTrivialKill(Cast->getOperand(0)))
130 // GEPs with all zero indices are trivially coalesced by fast-isel.
131 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
132 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
135 // Only instructions with a single use in the same basic block are considered
136 // to have trivial kills.
137 return I->hasOneUse() &&
138 !(I->getOpcode() == Instruction::BitCast ||
139 I->getOpcode() == Instruction::PtrToInt ||
140 I->getOpcode() == Instruction::IntToPtr) &&
141 cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
144 unsigned FastISel::getRegForValue(const Value *V) {
145 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
146 // Don't handle non-simple values in FastISel.
147 if (!RealVT.isSimple())
150 // Ignore illegal types. We must do this before looking up the value
151 // in ValueMap because Arguments are given virtual registers regardless
152 // of whether FastISel can handle them.
153 MVT VT = RealVT.getSimpleVT();
154 if (!TLI.isTypeLegal(VT)) {
155 // Handle integer promotions, though, because they're common and easy.
156 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
157 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
162 // Look up the value to see if we already have a register for it.
163 unsigned Reg = lookUpRegForValue(V);
167 // In bottom-up mode, just create the virtual register which will be used
168 // to hold the value. It will be materialized later.
169 if (isa<Instruction>(V) &&
170 (!isa<AllocaInst>(V) ||
171 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
172 return FuncInfo.InitializeRegForValue(V);
174 SavePoint SaveInsertPt = enterLocalValueArea();
176 // Materialize the value in a register. Emit any instructions in the
178 Reg = materializeRegForValue(V, VT);
180 leaveLocalValueArea(SaveInsertPt);
185 /// materializeRegForValue - Helper for getRegForValue. This function is
186 /// called when the value isn't already available in a register and must
187 /// be materialized with new instructions.
188 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
191 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
192 if (CI->getValue().getActiveBits() <= 64)
193 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
194 } else if (isa<AllocaInst>(V)) {
195 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
196 } else if (isa<ConstantPointerNull>(V)) {
197 // Translate this as an integer zero so that it can be
198 // local-CSE'd with actual integer zeros.
200 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
201 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
202 if (CF->isNullValue()) {
203 Reg = TargetMaterializeFloatZero(CF);
205 // Try to emit the constant directly.
206 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
210 // Try to emit the constant by using an integer constant with a cast.
211 const APFloat &Flt = CF->getValueAPF();
212 EVT IntVT = TLI.getPointerTy();
215 uint32_t IntBitWidth = IntVT.getSizeInBits();
217 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
218 APFloat::rmTowardZero, &isExact);
220 APInt IntVal(IntBitWidth, x);
222 unsigned IntegerReg =
223 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
225 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
226 IntegerReg, /*Kill=*/false);
229 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
230 if (!SelectOperator(Op, Op->getOpcode()))
231 if (!isa<Instruction>(Op) ||
232 !TargetSelectInstruction(cast<Instruction>(Op)))
234 Reg = lookUpRegForValue(Op);
235 } else if (isa<UndefValue>(V)) {
236 Reg = createResultReg(TLI.getRegClassFor(VT));
237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
238 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
241 // If target-independent code couldn't handle the value, give target-specific
243 if (!Reg && isa<Constant>(V))
244 Reg = TargetMaterializeConstant(cast<Constant>(V));
246 // Don't cache constant materializations in the general ValueMap.
247 // To do so would require tracking what uses they dominate.
249 LocalValueMap[V] = Reg;
250 LastLocalValue = MRI.getVRegDef(Reg);
255 unsigned FastISel::lookUpRegForValue(const Value *V) {
256 // Look up the value to see if we already have a register for it. We
257 // cache values defined by Instructions across blocks, and other values
258 // only locally. This is because Instructions already have the SSA
259 // def-dominates-use requirement enforced.
260 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
261 if (I != FuncInfo.ValueMap.end())
263 return LocalValueMap[V];
266 /// UpdateValueMap - Update the value map to include the new mapping for this
267 /// instruction, or insert an extra copy to get the result in a previous
268 /// determined register.
269 /// NOTE: This is only necessary because we might select a block that uses
270 /// a value before we select the block that defines the value. It might be
271 /// possible to fix this by selecting blocks in reverse postorder.
272 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
273 if (!isa<Instruction>(I)) {
274 LocalValueMap[I] = Reg;
278 unsigned &AssignedReg = FuncInfo.ValueMap[I];
279 if (AssignedReg == 0)
280 // Use the new register.
282 else if (Reg != AssignedReg) {
283 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
284 for (unsigned i = 0; i < NumRegs; i++)
285 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
291 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
292 unsigned IdxN = getRegForValue(Idx);
294 // Unhandled operand. Halt "fast" selection and bail.
295 return std::pair<unsigned, bool>(0, false);
297 bool IdxNIsKill = hasTrivialKill(Idx);
299 // If the index is smaller or larger than intptr_t, truncate or extend it.
300 MVT PtrVT = TLI.getPointerTy();
301 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
302 if (IdxVT.bitsLT(PtrVT)) {
303 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
307 else if (IdxVT.bitsGT(PtrVT)) {
308 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
312 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
315 void FastISel::recomputeInsertPt() {
316 if (getLastLocalValue()) {
317 FuncInfo.InsertPt = getLastLocalValue();
318 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
321 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
323 // Now skip past any EH_LABELs, which must remain at the beginning.
324 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
325 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
329 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
330 MachineBasicBlock::iterator E) {
331 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
333 MachineInstr *Dead = &*I;
335 Dead->eraseFromParent();
341 FastISel::SavePoint FastISel::enterLocalValueArea() {
342 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
346 SavePoint SP = { OldInsertPt, OldDL };
350 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
351 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
352 LastLocalValue = llvm::prior(FuncInfo.InsertPt);
354 // Restore the previous insert position.
355 FuncInfo.InsertPt = OldInsertPt.InsertPt;
359 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
360 /// which has an opcode which directly corresponds to the given ISD opcode.
362 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
363 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
364 if (VT == MVT::Other || !VT.isSimple())
365 // Unhandled type. Halt "fast" selection and bail.
368 // We only handle legal types. For example, on x86-32 the instruction
369 // selector contains all of the 64-bit instructions from x86-64,
370 // under the assumption that i64 won't be used if the target doesn't
372 if (!TLI.isTypeLegal(VT)) {
373 // MVT::i1 is special. Allow AND, OR, or XOR because they
374 // don't require additional zeroing, which makes them easy.
376 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
377 ISDOpcode == ISD::XOR))
378 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
383 // Check if the first operand is a constant, and handle it as "ri". At -O0,
384 // we don't have anything that canonicalizes operand order.
385 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
386 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
387 unsigned Op1 = getRegForValue(I->getOperand(1));
388 if (Op1 == 0) return false;
390 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
392 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
393 Op1IsKill, CI->getZExtValue(),
395 if (ResultReg == 0) return false;
397 // We successfully emitted code for the given LLVM Instruction.
398 UpdateValueMap(I, ResultReg);
403 unsigned Op0 = getRegForValue(I->getOperand(0));
404 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
407 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
409 // Check if the second operand is a constant and handle it appropriately.
410 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
411 uint64_t Imm = CI->getZExtValue();
413 // Transform "sdiv exact X, 8" -> "sra X, 3".
414 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
415 cast<BinaryOperator>(I)->isExact() &&
416 isPowerOf2_64(Imm)) {
418 ISDOpcode = ISD::SRA;
421 // Transform "urem x, pow2" -> "and x, pow2-1".
422 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
423 isPowerOf2_64(Imm)) {
425 ISDOpcode = ISD::AND;
428 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
429 Op0IsKill, Imm, VT.getSimpleVT());
430 if (ResultReg == 0) return false;
432 // We successfully emitted code for the given LLVM Instruction.
433 UpdateValueMap(I, ResultReg);
437 // Check if the second operand is a constant float.
438 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
439 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
440 ISDOpcode, Op0, Op0IsKill, CF);
441 if (ResultReg != 0) {
442 // We successfully emitted code for the given LLVM Instruction.
443 UpdateValueMap(I, ResultReg);
448 unsigned Op1 = getRegForValue(I->getOperand(1));
450 // Unhandled operand. Halt "fast" selection and bail.
453 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
455 // Now we have both operands in registers. Emit the instruction.
456 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
461 // Target-specific code wasn't able to find a machine opcode for
462 // the given ISD opcode and type. Halt "fast" selection and bail.
465 // We successfully emitted code for the given LLVM Instruction.
466 UpdateValueMap(I, ResultReg);
470 bool FastISel::SelectGetElementPtr(const User *I) {
471 unsigned N = getRegForValue(I->getOperand(0));
473 // Unhandled operand. Halt "fast" selection and bail.
476 bool NIsKill = hasTrivialKill(I->getOperand(0));
478 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
479 // into a single N = N + TotalOffset.
480 uint64_t TotalOffs = 0;
481 // FIXME: What's a good SWAG number for MaxOffs?
482 uint64_t MaxOffs = 2048;
483 Type *Ty = I->getOperand(0)->getType();
484 MVT VT = TLI.getPointerTy();
485 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
486 E = I->op_end(); OI != E; ++OI) {
487 const Value *Idx = *OI;
488 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
489 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
492 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
493 if (TotalOffs >= MaxOffs) {
494 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
496 // Unhandled operand. Halt "fast" selection and bail.
502 Ty = StTy->getElementType(Field);
504 Ty = cast<SequentialType>(Ty)->getElementType();
506 // If this is a constant subscript, handle it quickly.
507 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
508 if (CI->isZero()) continue;
511 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
512 if (TotalOffs >= MaxOffs) {
513 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
515 // Unhandled operand. Halt "fast" selection and bail.
523 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
525 // Unhandled operand. Halt "fast" selection and bail.
531 // N = N + Idx * ElementSize;
532 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
533 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
534 unsigned IdxN = Pair.first;
535 bool IdxNIsKill = Pair.second;
537 // Unhandled operand. Halt "fast" selection and bail.
540 if (ElementSize != 1) {
541 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
543 // Unhandled operand. Halt "fast" selection and bail.
547 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
549 // Unhandled operand. Halt "fast" selection and bail.
554 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
556 // Unhandled operand. Halt "fast" selection and bail.
560 // We successfully emitted code for the given LLVM Instruction.
561 UpdateValueMap(I, N);
565 bool FastISel::SelectCall(const User *I) {
566 const CallInst *Call = cast<CallInst>(I);
568 // Handle simple inline asms.
569 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
570 // Don't attempt to handle constraints.
571 if (!IA->getConstraintString().empty())
574 unsigned ExtraInfo = 0;
575 if (IA->hasSideEffects())
576 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
577 if (IA->isAlignStack())
578 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
580 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
581 TII.get(TargetOpcode::INLINEASM))
582 .addExternalSymbol(IA->getAsmString().c_str())
587 MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
588 ComputeUsesVAFloatArgument(*Call, &MMI);
590 const Function *F = Call->getCalledFunction();
591 if (!F) return false;
593 // Handle selected intrinsic function calls.
594 switch (F->getIntrinsicID()) {
596 // At -O0 we don't care about the lifetime intrinsics.
597 case Intrinsic::lifetime_start:
598 case Intrinsic::lifetime_end:
599 // The donothing intrinsic does, well, nothing.
600 case Intrinsic::donothing:
603 case Intrinsic::dbg_declare: {
604 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
605 if (!DIVariable(DI->getVariable()).Verify() ||
606 !FuncInfo.MF->getMMI().hasDebugInfo()) {
607 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
611 const Value *Address = DI->getAddress();
612 if (!Address || isa<UndefValue>(Address)) {
613 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
617 Optional<MachineOperand> Op;
618 if (const Argument *Arg = dyn_cast<Argument>(Address))
619 // Some arguments' frame index is recorded during argument lowering.
620 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
621 Op = MachineOperand::CreateFI(FI);
623 if (unsigned Reg = lookUpRegForValue(Address))
624 Op = MachineOperand::CreateReg(Reg, false);
626 // If we have a VLA that has a "use" in a metadata node that's then used
627 // here but it has no other uses, then we have a problem. E.g.,
629 // int foo (const int *x) {
634 // If we assign 'a' a vreg and fast isel later on has to use the selection
635 // DAG isel, it will want to copy the value to the vreg. However, there are
636 // no uses, which goes counter to what selection DAG isel expects.
637 if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
638 (!isa<AllocaInst>(Address) ||
639 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
640 Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
643 if (Op && Op->isReg())
644 Op->setIsDebug(true);
647 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
648 TII.get(TargetOpcode::DBG_VALUE)).addOperand(*Op).addImm(0)
649 .addMetadata(DI->getVariable());
651 // We can't yet handle anything else here because it would require
652 // generating code, thus altering codegen because of debug info.
653 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
656 case Intrinsic::dbg_value: {
657 // This form of DBG_VALUE is target-independent.
658 const DbgValueInst *DI = cast<DbgValueInst>(Call);
659 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
660 const Value *V = DI->getValue();
662 // Currently the optimizer can produce this; insert an undef to
663 // help debugging. Probably the optimizer should not do this.
664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
665 .addReg(0U).addImm(DI->getOffset())
666 .addMetadata(DI->getVariable());
667 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
668 if (CI->getBitWidth() > 64)
669 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
670 .addCImm(CI).addImm(DI->getOffset())
671 .addMetadata(DI->getVariable());
673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
674 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
675 .addMetadata(DI->getVariable());
676 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
678 .addFPImm(CF).addImm(DI->getOffset())
679 .addMetadata(DI->getVariable());
680 } else if (unsigned Reg = lookUpRegForValue(V)) {
681 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
682 .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
683 .addMetadata(DI->getVariable());
685 // We can't yet handle anything else here because it would require
686 // generating code, thus altering codegen because of debug info.
687 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
691 case Intrinsic::objectsize: {
692 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
693 unsigned long long Res = CI->isZero() ? -1ULL : 0;
694 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
695 unsigned ResultReg = getRegForValue(ResCI);
698 UpdateValueMap(Call, ResultReg);
701 case Intrinsic::expect: {
702 unsigned ResultReg = getRegForValue(Call->getArgOperand(0));
705 UpdateValueMap(Call, ResultReg);
710 // Usually, it does not make sense to initialize a value,
711 // make an unrelated function call and use the value, because
712 // it tends to be spilled on the stack. So, we move the pointer
713 // to the last local value to the beginning of the block, so that
714 // all the values which have already been materialized,
715 // appear after the call. It also makes sense to skip intrinsics
716 // since they tend to be inlined.
717 if (!isa<IntrinsicInst>(Call))
718 flushLocalValueMap();
720 // An arbitrary call. Bail.
724 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
725 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
726 EVT DstVT = TLI.getValueType(I->getType());
728 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
729 DstVT == MVT::Other || !DstVT.isSimple())
730 // Unhandled type. Halt "fast" selection and bail.
733 // Check if the destination type is legal.
734 if (!TLI.isTypeLegal(DstVT))
737 // Check if the source operand is legal.
738 if (!TLI.isTypeLegal(SrcVT))
741 unsigned InputReg = getRegForValue(I->getOperand(0));
743 // Unhandled operand. Halt "fast" selection and bail.
746 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
748 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
751 InputReg, InputRegIsKill);
755 UpdateValueMap(I, ResultReg);
759 bool FastISel::SelectBitCast(const User *I) {
760 // If the bitcast doesn't change the type, just use the operand value.
761 if (I->getType() == I->getOperand(0)->getType()) {
762 unsigned Reg = getRegForValue(I->getOperand(0));
765 UpdateValueMap(I, Reg);
769 // Bitcasts of other values become reg-reg copies or BITCAST operators.
770 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
771 EVT DstEVT = TLI.getValueType(I->getType());
772 if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
773 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
774 // Unhandled type. Halt "fast" selection and bail.
777 MVT SrcVT = SrcEVT.getSimpleVT();
778 MVT DstVT = DstEVT.getSimpleVT();
779 unsigned Op0 = getRegForValue(I->getOperand(0));
781 // Unhandled operand. Halt "fast" selection and bail.
784 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
786 // First, try to perform the bitcast by inserting a reg-reg copy.
787 unsigned ResultReg = 0;
788 if (SrcVT == DstVT) {
789 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
790 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
791 // Don't attempt a cross-class copy. It will likely fail.
792 if (SrcClass == DstClass) {
793 ResultReg = createResultReg(DstClass);
794 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
795 ResultReg).addReg(Op0);
799 // If the reg-reg copy failed, select a BITCAST opcode.
801 ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
806 UpdateValueMap(I, ResultReg);
811 FastISel::SelectInstruction(const Instruction *I) {
812 // Just before the terminator instruction, insert instructions to
813 // feed PHI nodes in successor blocks.
814 if (isa<TerminatorInst>(I))
815 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
818 DL = I->getDebugLoc();
820 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
822 // As a special case, don't handle calls to builtin library functions that
823 // may be translated directly to target instructions.
824 if (const CallInst *Call = dyn_cast<CallInst>(I)) {
825 const Function *F = Call->getCalledFunction();
827 if (F && !F->hasLocalLinkage() && F->hasName() &&
828 LibInfo->getLibFunc(F->getName(), Func) &&
829 LibInfo->hasOptimizedCodeGen(Func))
833 // First, try doing target-independent selection.
834 if (SelectOperator(I, I->getOpcode())) {
835 ++NumFastIselSuccessIndependent;
839 // Remove dead code. However, ignore call instructions since we've flushed
840 // the local value map and recomputed the insert point.
841 if (!isa<CallInst>(I)) {
843 if (SavedInsertPt != FuncInfo.InsertPt)
844 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
847 // Next, try calling the target to attempt to handle the instruction.
848 SavedInsertPt = FuncInfo.InsertPt;
849 if (TargetSelectInstruction(I)) {
850 ++NumFastIselSuccessTarget;
854 // Check for dead code and remove as necessary.
856 if (SavedInsertPt != FuncInfo.InsertPt)
857 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
863 /// FastEmitBranch - Emit an unconditional branch to the given block,
864 /// unless it is the immediate (fall-through) successor, and update
867 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
869 if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
870 FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
871 // For more accurate line information if this is the only instruction
872 // in the block then emit it, otherwise we have the unconditional
873 // fall-through case, which needs no instructions.
875 // The unconditional branch case.
876 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
877 SmallVector<MachineOperand, 0>(), DL);
879 FuncInfo.MBB->addSuccessor(MSucc);
882 /// SelectFNeg - Emit an FNeg operation.
885 FastISel::SelectFNeg(const User *I) {
886 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
887 if (OpReg == 0) return false;
889 bool OpRegIsKill = hasTrivialKill(I);
891 // If the target has ISD::FNEG, use it.
892 EVT VT = TLI.getValueType(I->getType());
893 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
894 ISD::FNEG, OpReg, OpRegIsKill);
895 if (ResultReg != 0) {
896 UpdateValueMap(I, ResultReg);
900 // Bitcast the value to integer, twiddle the sign bit with xor,
901 // and then bitcast it back to floating-point.
902 if (VT.getSizeInBits() > 64) return false;
903 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
904 if (!TLI.isTypeLegal(IntVT))
907 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
908 ISD::BITCAST, OpReg, OpRegIsKill);
912 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
913 IntReg, /*Kill=*/true,
914 UINT64_C(1) << (VT.getSizeInBits()-1),
915 IntVT.getSimpleVT());
916 if (IntResultReg == 0)
919 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
920 ISD::BITCAST, IntResultReg, /*Kill=*/true);
924 UpdateValueMap(I, ResultReg);
929 FastISel::SelectExtractValue(const User *U) {
930 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
934 // Make sure we only try to handle extracts with a legal result. But also
935 // allow i1 because it's easy.
936 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
937 if (!RealVT.isSimple())
939 MVT VT = RealVT.getSimpleVT();
940 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
943 const Value *Op0 = EVI->getOperand(0);
944 Type *AggTy = Op0->getType();
946 // Get the base result register.
948 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
949 if (I != FuncInfo.ValueMap.end())
950 ResultReg = I->second;
951 else if (isa<Instruction>(Op0))
952 ResultReg = FuncInfo.InitializeRegForValue(Op0);
954 return false; // fast-isel can't handle aggregate constants at the moment
956 // Get the actual result register, which is an offset from the base register.
957 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
959 SmallVector<EVT, 4> AggValueVTs;
960 ComputeValueVTs(TLI, AggTy, AggValueVTs);
962 for (unsigned i = 0; i < VTIndex; i++)
963 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
965 UpdateValueMap(EVI, ResultReg);
970 FastISel::SelectOperator(const User *I, unsigned Opcode) {
972 case Instruction::Add:
973 return SelectBinaryOp(I, ISD::ADD);
974 case Instruction::FAdd:
975 return SelectBinaryOp(I, ISD::FADD);
976 case Instruction::Sub:
977 return SelectBinaryOp(I, ISD::SUB);
978 case Instruction::FSub:
979 // FNeg is currently represented in LLVM IR as a special case of FSub.
980 if (BinaryOperator::isFNeg(I))
981 return SelectFNeg(I);
982 return SelectBinaryOp(I, ISD::FSUB);
983 case Instruction::Mul:
984 return SelectBinaryOp(I, ISD::MUL);
985 case Instruction::FMul:
986 return SelectBinaryOp(I, ISD::FMUL);
987 case Instruction::SDiv:
988 return SelectBinaryOp(I, ISD::SDIV);
989 case Instruction::UDiv:
990 return SelectBinaryOp(I, ISD::UDIV);
991 case Instruction::FDiv:
992 return SelectBinaryOp(I, ISD::FDIV);
993 case Instruction::SRem:
994 return SelectBinaryOp(I, ISD::SREM);
995 case Instruction::URem:
996 return SelectBinaryOp(I, ISD::UREM);
997 case Instruction::FRem:
998 return SelectBinaryOp(I, ISD::FREM);
999 case Instruction::Shl:
1000 return SelectBinaryOp(I, ISD::SHL);
1001 case Instruction::LShr:
1002 return SelectBinaryOp(I, ISD::SRL);
1003 case Instruction::AShr:
1004 return SelectBinaryOp(I, ISD::SRA);
1005 case Instruction::And:
1006 return SelectBinaryOp(I, ISD::AND);
1007 case Instruction::Or:
1008 return SelectBinaryOp(I, ISD::OR);
1009 case Instruction::Xor:
1010 return SelectBinaryOp(I, ISD::XOR);
1012 case Instruction::GetElementPtr:
1013 return SelectGetElementPtr(I);
1015 case Instruction::Br: {
1016 const BranchInst *BI = cast<BranchInst>(I);
1018 if (BI->isUnconditional()) {
1019 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1020 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1021 FastEmitBranch(MSucc, BI->getDebugLoc());
1025 // Conditional branches are not handed yet.
1026 // Halt "fast" selection and bail.
1030 case Instruction::Unreachable:
1034 case Instruction::Alloca:
1035 // FunctionLowering has the static-sized case covered.
1036 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1039 // Dynamic-sized alloca is not handled yet.
1042 case Instruction::Call:
1043 return SelectCall(I);
1045 case Instruction::BitCast:
1046 return SelectBitCast(I);
1048 case Instruction::FPToSI:
1049 return SelectCast(I, ISD::FP_TO_SINT);
1050 case Instruction::ZExt:
1051 return SelectCast(I, ISD::ZERO_EXTEND);
1052 case Instruction::SExt:
1053 return SelectCast(I, ISD::SIGN_EXTEND);
1054 case Instruction::Trunc:
1055 return SelectCast(I, ISD::TRUNCATE);
1056 case Instruction::SIToFP:
1057 return SelectCast(I, ISD::SINT_TO_FP);
1059 case Instruction::IntToPtr: // Deliberate fall-through.
1060 case Instruction::PtrToInt: {
1061 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1062 EVT DstVT = TLI.getValueType(I->getType());
1063 if (DstVT.bitsGT(SrcVT))
1064 return SelectCast(I, ISD::ZERO_EXTEND);
1065 if (DstVT.bitsLT(SrcVT))
1066 return SelectCast(I, ISD::TRUNCATE);
1067 unsigned Reg = getRegForValue(I->getOperand(0));
1068 if (Reg == 0) return false;
1069 UpdateValueMap(I, Reg);
1073 case Instruction::ExtractValue:
1074 return SelectExtractValue(I);
1076 case Instruction::PHI:
1077 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1080 // Unhandled instruction. Halt "fast" selection and bail.
1085 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1086 const TargetLibraryInfo *libInfo)
1087 : FuncInfo(funcInfo),
1088 MRI(FuncInfo.MF->getRegInfo()),
1089 MFI(*FuncInfo.MF->getFrameInfo()),
1090 MCP(*FuncInfo.MF->getConstantPool()),
1091 TM(FuncInfo.MF->getTarget()),
1092 TD(*TM.getDataLayout()),
1093 TII(*TM.getInstrInfo()),
1094 TLI(*TM.getTargetLowering()),
1095 TRI(*TM.getRegisterInfo()),
1099 FastISel::~FastISel() {}
1101 bool FastISel::FastLowerArguments() {
1105 unsigned FastISel::FastEmit_(MVT, MVT,
1110 unsigned FastISel::FastEmit_r(MVT, MVT,
1112 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1116 unsigned FastISel::FastEmit_rr(MVT, MVT,
1118 unsigned /*Op0*/, bool /*Op0IsKill*/,
1119 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1123 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1127 unsigned FastISel::FastEmit_f(MVT, MVT,
1128 unsigned, const ConstantFP * /*FPImm*/) {
1132 unsigned FastISel::FastEmit_ri(MVT, MVT,
1134 unsigned /*Op0*/, bool /*Op0IsKill*/,
1139 unsigned FastISel::FastEmit_rf(MVT, MVT,
1141 unsigned /*Op0*/, bool /*Op0IsKill*/,
1142 const ConstantFP * /*FPImm*/) {
1146 unsigned FastISel::FastEmit_rri(MVT, MVT,
1148 unsigned /*Op0*/, bool /*Op0IsKill*/,
1149 unsigned /*Op1*/, bool /*Op1IsKill*/,
1154 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1155 /// to emit an instruction with an immediate operand using FastEmit_ri.
1156 /// If that fails, it materializes the immediate into a register and try
1157 /// FastEmit_rr instead.
1158 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1159 unsigned Op0, bool Op0IsKill,
1160 uint64_t Imm, MVT ImmType) {
1161 // If this is a multiply by a power of two, emit this as a shift left.
1162 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1165 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1166 // div x, 8 -> srl x, 3
1171 // Horrible hack (to be removed), check to make sure shift amounts are
1173 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1174 Imm >= VT.getSizeInBits())
1177 // First check if immediate type is legal. If not, we can't use the ri form.
1178 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1181 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1182 if (MaterialReg == 0) {
1183 // This is a bit ugly/slow, but failing here means falling out of
1184 // fast-isel, which would be very slow.
1185 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1186 VT.getSizeInBits());
1187 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1188 assert (MaterialReg != 0 && "Unable to materialize imm.");
1189 if (MaterialReg == 0) return 0;
1191 return FastEmit_rr(VT, VT, Opcode,
1193 MaterialReg, /*Kill=*/true);
1196 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1197 return MRI.createVirtualRegister(RC);
1200 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1201 const TargetRegisterClass* RC) {
1202 unsigned ResultReg = createResultReg(RC);
1203 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1209 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1210 const TargetRegisterClass *RC,
1211 unsigned Op0, bool Op0IsKill) {
1212 unsigned ResultReg = createResultReg(RC);
1213 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1215 if (II.getNumDefs() >= 1)
1216 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1217 .addReg(Op0, Op0IsKill * RegState::Kill);
1219 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1220 .addReg(Op0, Op0IsKill * RegState::Kill);
1221 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1222 ResultReg).addReg(II.ImplicitDefs[0]);
1228 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1229 const TargetRegisterClass *RC,
1230 unsigned Op0, bool Op0IsKill,
1231 unsigned Op1, bool Op1IsKill) {
1232 unsigned ResultReg = createResultReg(RC);
1233 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1235 if (II.getNumDefs() >= 1)
1236 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1237 .addReg(Op0, Op0IsKill * RegState::Kill)
1238 .addReg(Op1, Op1IsKill * RegState::Kill);
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1241 .addReg(Op0, Op0IsKill * RegState::Kill)
1242 .addReg(Op1, Op1IsKill * RegState::Kill);
1243 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1244 ResultReg).addReg(II.ImplicitDefs[0]);
1249 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1250 const TargetRegisterClass *RC,
1251 unsigned Op0, bool Op0IsKill,
1252 unsigned Op1, bool Op1IsKill,
1253 unsigned Op2, bool Op2IsKill) {
1254 unsigned ResultReg = createResultReg(RC);
1255 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1257 if (II.getNumDefs() >= 1)
1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1259 .addReg(Op0, Op0IsKill * RegState::Kill)
1260 .addReg(Op1, Op1IsKill * RegState::Kill)
1261 .addReg(Op2, Op2IsKill * RegState::Kill);
1263 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1264 .addReg(Op0, Op0IsKill * RegState::Kill)
1265 .addReg(Op1, Op1IsKill * RegState::Kill)
1266 .addReg(Op2, Op2IsKill * RegState::Kill);
1267 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1268 ResultReg).addReg(II.ImplicitDefs[0]);
1273 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1274 const TargetRegisterClass *RC,
1275 unsigned Op0, bool Op0IsKill,
1277 unsigned ResultReg = createResultReg(RC);
1278 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1280 if (II.getNumDefs() >= 1)
1281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1282 .addReg(Op0, Op0IsKill * RegState::Kill)
1285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1286 .addReg(Op0, Op0IsKill * RegState::Kill)
1288 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1289 ResultReg).addReg(II.ImplicitDefs[0]);
1294 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1295 const TargetRegisterClass *RC,
1296 unsigned Op0, bool Op0IsKill,
1297 uint64_t Imm1, uint64_t Imm2) {
1298 unsigned ResultReg = createResultReg(RC);
1299 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1301 if (II.getNumDefs() >= 1)
1302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1303 .addReg(Op0, Op0IsKill * RegState::Kill)
1307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1308 .addReg(Op0, Op0IsKill * RegState::Kill)
1311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1312 ResultReg).addReg(II.ImplicitDefs[0]);
1317 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1318 const TargetRegisterClass *RC,
1319 unsigned Op0, bool Op0IsKill,
1320 const ConstantFP *FPImm) {
1321 unsigned ResultReg = createResultReg(RC);
1322 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1324 if (II.getNumDefs() >= 1)
1325 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1326 .addReg(Op0, Op0IsKill * RegState::Kill)
1329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1330 .addReg(Op0, Op0IsKill * RegState::Kill)
1332 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1333 ResultReg).addReg(II.ImplicitDefs[0]);
1338 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1339 const TargetRegisterClass *RC,
1340 unsigned Op0, bool Op0IsKill,
1341 unsigned Op1, bool Op1IsKill,
1343 unsigned ResultReg = createResultReg(RC);
1344 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1346 if (II.getNumDefs() >= 1)
1347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1348 .addReg(Op0, Op0IsKill * RegState::Kill)
1349 .addReg(Op1, Op1IsKill * RegState::Kill)
1352 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1353 .addReg(Op0, Op0IsKill * RegState::Kill)
1354 .addReg(Op1, Op1IsKill * RegState::Kill)
1356 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1357 ResultReg).addReg(II.ImplicitDefs[0]);
1362 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1363 const TargetRegisterClass *RC,
1364 unsigned Op0, bool Op0IsKill,
1365 unsigned Op1, bool Op1IsKill,
1366 uint64_t Imm1, uint64_t Imm2) {
1367 unsigned ResultReg = createResultReg(RC);
1368 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1370 if (II.getNumDefs() >= 1)
1371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1372 .addReg(Op0, Op0IsKill * RegState::Kill)
1373 .addReg(Op1, Op1IsKill * RegState::Kill)
1374 .addImm(Imm1).addImm(Imm2);
1376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1377 .addReg(Op0, Op0IsKill * RegState::Kill)
1378 .addReg(Op1, Op1IsKill * RegState::Kill)
1379 .addImm(Imm1).addImm(Imm2);
1380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1381 ResultReg).addReg(II.ImplicitDefs[0]);
1386 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1387 const TargetRegisterClass *RC,
1389 unsigned ResultReg = createResultReg(RC);
1390 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1392 if (II.getNumDefs() >= 1)
1393 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1395 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1396 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1397 ResultReg).addReg(II.ImplicitDefs[0]);
1402 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1403 const TargetRegisterClass *RC,
1404 uint64_t Imm1, uint64_t Imm2) {
1405 unsigned ResultReg = createResultReg(RC);
1406 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1408 if (II.getNumDefs() >= 1)
1409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1410 .addImm(Imm1).addImm(Imm2);
1412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1413 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1414 ResultReg).addReg(II.ImplicitDefs[0]);
1419 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1420 unsigned Op0, bool Op0IsKill,
1422 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1423 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1424 "Cannot yet extract from physregs");
1425 const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1426 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1427 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1428 DL, TII.get(TargetOpcode::COPY), ResultReg)
1429 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1433 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1434 /// with all but the least significant bit set to zero.
1435 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1436 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1439 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1440 /// Emit code to ensure constants are copied into registers when needed.
1441 /// Remember the virtual registers that need to be added to the Machine PHI
1442 /// nodes as input. We cannot just directly add them, because expansion
1443 /// might result in multiple MBB's for one BB. As such, the start of the
1444 /// BB might correspond to a different MBB than the end.
1445 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1446 const TerminatorInst *TI = LLVMBB->getTerminator();
1448 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1449 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1451 // Check successor nodes' PHI nodes that expect a constant to be available
1453 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1454 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1455 if (!isa<PHINode>(SuccBB->begin())) continue;
1456 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1458 // If this terminator has multiple identical successors (common for
1459 // switches), only handle each succ once.
1460 if (!SuccsHandled.insert(SuccMBB)) continue;
1462 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1464 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1465 // nodes and Machine PHI nodes, but the incoming operands have not been
1467 for (BasicBlock::const_iterator I = SuccBB->begin();
1468 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1470 // Ignore dead phi's.
1471 if (PN->use_empty()) continue;
1473 // Only handle legal types. Two interesting things to note here. First,
1474 // by bailing out early, we may leave behind some dead instructions,
1475 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1476 // own moves. Second, this check is necessary because FastISel doesn't
1477 // use CreateRegs to create registers, so it always creates
1478 // exactly one register for each non-void instruction.
1479 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1480 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1481 // Handle integer promotions, though, because they're common and easy.
1482 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1483 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1485 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1490 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1492 // Set the DebugLoc for the copy. Prefer the location of the operand
1493 // if there is one; use the location of the PHI otherwise.
1494 DL = PN->getDebugLoc();
1495 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1496 DL = Inst->getDebugLoc();
1498 unsigned Reg = getRegForValue(PHIOp);
1500 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1503 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1511 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
1512 assert(LI->hasOneUse() &&
1513 "tryToFoldLoad expected a LoadInst with a single use");
1514 // We know that the load has a single use, but don't know what it is. If it
1515 // isn't one of the folded instructions, then we can't succeed here. Handle
1516 // this by scanning the single-use users of the load until we get to FoldInst.
1517 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
1519 const Instruction *TheUser = LI->use_back();
1520 while (TheUser != FoldInst && // Scan up until we find FoldInst.
1521 // Stay in the right block.
1522 TheUser->getParent() == FoldInst->getParent() &&
1523 --MaxUsers) { // Don't scan too far.
1524 // If there are multiple or no uses of this instruction, then bail out.
1525 if (!TheUser->hasOneUse())
1528 TheUser = TheUser->use_back();
1531 // If we didn't find the fold instruction, then we failed to collapse the
1533 if (TheUser != FoldInst)
1536 // Don't try to fold volatile loads. Target has to deal with alignment
1538 if (LI->isVolatile())
1541 // Figure out which vreg this is going into. If there is no assigned vreg yet
1542 // then there actually was no reference to it. Perhaps the load is referenced
1543 // by a dead instruction.
1544 unsigned LoadReg = getRegForValue(LI);
1548 // We can't fold if this vreg has no uses or more than one use. Multiple uses
1549 // may mean that the instruction got lowered to multiple MIs, or the use of
1550 // the loaded value ended up being multiple operands of the result.
1551 if (!MRI.hasOneUse(LoadReg))
1554 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
1555 MachineInstr *User = &*RI;
1557 // Set the insertion point properly. Folding the load can cause generation of
1558 // other random instructions (like sign extends) for addressing modes; make
1559 // sure they get inserted in a logical place before the new instruction.
1560 FuncInfo.InsertPt = User;
1561 FuncInfo.MBB = User->getParent();
1563 // Ask the target to try folding the load.
1564 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);