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/Statistic.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/CodeGen/Analysis.h"
47 #include "llvm/CodeGen/FunctionLoweringInfo.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/DebugInfo.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalVariable.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetLibraryInfo.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetMachine.h"
66 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
67 "target-independent selector");
68 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
69 "target-specific selector");
70 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
72 /// startNewBlock - Set the current block to which generated machine
73 /// instructions will be appended, and clear the local CSE map.
75 void FastISel::startNewBlock() {
76 LocalValueMap.clear();
78 // Instructions are appended to FuncInfo.MBB. If the basic block already
79 // contains labels or copies, use the last instruction as the last local
82 if (!FuncInfo.MBB->empty())
83 EmitStartPt = &FuncInfo.MBB->back();
84 LastLocalValue = EmitStartPt;
87 bool FastISel::LowerArguments() {
88 if (!FuncInfo.CanLowerReturn)
89 // Fallback to SDISel argument lowering code to deal with sret pointer
93 if (!FastLowerArguments())
96 // Enter non-dead arguments into ValueMap for uses in non-entry BBs.
97 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
98 E = FuncInfo.Fn->arg_end(); I != E; ++I) {
99 if (!I->use_empty()) {
100 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
101 assert(VI != LocalValueMap.end() && "Missed an argument?");
102 FuncInfo.ValueMap[I] = VI->second;
108 void FastISel::flushLocalValueMap() {
109 LocalValueMap.clear();
110 LastLocalValue = EmitStartPt;
114 bool FastISel::hasTrivialKill(const Value *V) const {
115 // Don't consider constants or arguments to have trivial kills.
116 const Instruction *I = dyn_cast<Instruction>(V);
120 // No-op casts are trivially coalesced by fast-isel.
121 if (const CastInst *Cast = dyn_cast<CastInst>(I))
122 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
123 !hasTrivialKill(Cast->getOperand(0)))
126 // GEPs with all zero indices are trivially coalesced by fast-isel.
127 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
128 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
131 // Only instructions with a single use in the same basic block are considered
132 // to have trivial kills.
133 return I->hasOneUse() &&
134 !(I->getOpcode() == Instruction::BitCast ||
135 I->getOpcode() == Instruction::PtrToInt ||
136 I->getOpcode() == Instruction::IntToPtr) &&
137 cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
140 unsigned FastISel::getRegForValue(const Value *V) {
141 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
142 // Don't handle non-simple values in FastISel.
143 if (!RealVT.isSimple())
146 // Ignore illegal types. We must do this before looking up the value
147 // in ValueMap because Arguments are given virtual registers regardless
148 // of whether FastISel can handle them.
149 MVT VT = RealVT.getSimpleVT();
150 if (!TLI.isTypeLegal(VT)) {
151 // Handle integer promotions, though, because they're common and easy.
152 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
153 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
158 // Look up the value to see if we already have a register for it.
159 unsigned Reg = lookUpRegForValue(V);
163 // In bottom-up mode, just create the virtual register which will be used
164 // to hold the value. It will be materialized later.
165 if (isa<Instruction>(V) &&
166 (!isa<AllocaInst>(V) ||
167 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
168 return FuncInfo.InitializeRegForValue(V);
170 SavePoint SaveInsertPt = enterLocalValueArea();
172 // Materialize the value in a register. Emit any instructions in the
174 Reg = materializeRegForValue(V, VT);
176 leaveLocalValueArea(SaveInsertPt);
181 /// materializeRegForValue - Helper for getRegForValue. This function is
182 /// called when the value isn't already available in a register and must
183 /// be materialized with new instructions.
184 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
187 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
188 if (CI->getValue().getActiveBits() <= 64)
189 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
190 } else if (isa<AllocaInst>(V)) {
191 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
192 } else if (isa<ConstantPointerNull>(V)) {
193 // Translate this as an integer zero so that it can be
194 // local-CSE'd with actual integer zeros.
196 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
197 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
198 if (CF->isNullValue()) {
199 Reg = TargetMaterializeFloatZero(CF);
201 // Try to emit the constant directly.
202 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
206 // Try to emit the constant by using an integer constant with a cast.
207 const APFloat &Flt = CF->getValueAPF();
208 EVT IntVT = TLI.getPointerTy();
211 uint32_t IntBitWidth = IntVT.getSizeInBits();
213 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
214 APFloat::rmTowardZero, &isExact);
216 APInt IntVal(IntBitWidth, x);
218 unsigned IntegerReg =
219 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
221 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
222 IntegerReg, /*Kill=*/false);
225 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
226 if (!SelectOperator(Op, Op->getOpcode()))
227 if (!isa<Instruction>(Op) ||
228 !TargetSelectInstruction(cast<Instruction>(Op)))
230 Reg = lookUpRegForValue(Op);
231 } else if (isa<UndefValue>(V)) {
232 Reg = createResultReg(TLI.getRegClassFor(VT));
233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
234 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
237 // If target-independent code couldn't handle the value, give target-specific
239 if (!Reg && isa<Constant>(V))
240 Reg = TargetMaterializeConstant(cast<Constant>(V));
242 // Don't cache constant materializations in the general ValueMap.
243 // To do so would require tracking what uses they dominate.
245 LocalValueMap[V] = Reg;
246 LastLocalValue = MRI.getVRegDef(Reg);
251 unsigned FastISel::lookUpRegForValue(const Value *V) {
252 // Look up the value to see if we already have a register for it. We
253 // cache values defined by Instructions across blocks, and other values
254 // only locally. This is because Instructions already have the SSA
255 // def-dominates-use requirement enforced.
256 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
257 if (I != FuncInfo.ValueMap.end())
259 return LocalValueMap[V];
262 /// UpdateValueMap - Update the value map to include the new mapping for this
263 /// instruction, or insert an extra copy to get the result in a previous
264 /// determined register.
265 /// NOTE: This is only necessary because we might select a block that uses
266 /// a value before we select the block that defines the value. It might be
267 /// possible to fix this by selecting blocks in reverse postorder.
268 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
269 if (!isa<Instruction>(I)) {
270 LocalValueMap[I] = Reg;
274 unsigned &AssignedReg = FuncInfo.ValueMap[I];
275 if (AssignedReg == 0)
276 // Use the new register.
278 else if (Reg != AssignedReg) {
279 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
280 for (unsigned i = 0; i < NumRegs; i++)
281 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
287 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
288 unsigned IdxN = getRegForValue(Idx);
290 // Unhandled operand. Halt "fast" selection and bail.
291 return std::pair<unsigned, bool>(0, false);
293 bool IdxNIsKill = hasTrivialKill(Idx);
295 // If the index is smaller or larger than intptr_t, truncate or extend it.
296 MVT PtrVT = TLI.getPointerTy();
297 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
298 if (IdxVT.bitsLT(PtrVT)) {
299 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
303 else if (IdxVT.bitsGT(PtrVT)) {
304 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
308 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
311 void FastISel::recomputeInsertPt() {
312 if (getLastLocalValue()) {
313 FuncInfo.InsertPt = getLastLocalValue();
314 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
317 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
319 // Now skip past any EH_LABELs, which must remain at the beginning.
320 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
321 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
325 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
326 MachineBasicBlock::iterator E) {
327 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
329 MachineInstr *Dead = &*I;
331 Dead->eraseFromParent();
337 FastISel::SavePoint FastISel::enterLocalValueArea() {
338 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
342 SavePoint SP = { OldInsertPt, OldDL };
346 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
347 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
348 LastLocalValue = llvm::prior(FuncInfo.InsertPt);
350 // Restore the previous insert position.
351 FuncInfo.InsertPt = OldInsertPt.InsertPt;
355 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
356 /// which has an opcode which directly corresponds to the given ISD opcode.
358 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
359 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
360 if (VT == MVT::Other || !VT.isSimple())
361 // Unhandled type. Halt "fast" selection and bail.
364 // We only handle legal types. For example, on x86-32 the instruction
365 // selector contains all of the 64-bit instructions from x86-64,
366 // under the assumption that i64 won't be used if the target doesn't
368 if (!TLI.isTypeLegal(VT)) {
369 // MVT::i1 is special. Allow AND, OR, or XOR because they
370 // don't require additional zeroing, which makes them easy.
372 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
373 ISDOpcode == ISD::XOR))
374 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
379 // Check if the first operand is a constant, and handle it as "ri". At -O0,
380 // we don't have anything that canonicalizes operand order.
381 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
382 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
383 unsigned Op1 = getRegForValue(I->getOperand(1));
384 if (Op1 == 0) return false;
386 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
388 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
389 Op1IsKill, CI->getZExtValue(),
391 if (ResultReg == 0) return false;
393 // We successfully emitted code for the given LLVM Instruction.
394 UpdateValueMap(I, ResultReg);
399 unsigned Op0 = getRegForValue(I->getOperand(0));
400 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
403 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
405 // Check if the second operand is a constant and handle it appropriately.
406 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
407 uint64_t Imm = CI->getZExtValue();
409 // Transform "sdiv exact X, 8" -> "sra X, 3".
410 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
411 cast<BinaryOperator>(I)->isExact() &&
412 isPowerOf2_64(Imm)) {
414 ISDOpcode = ISD::SRA;
417 // Transform "urem x, pow2" -> "and x, pow2-1".
418 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
419 isPowerOf2_64(Imm)) {
421 ISDOpcode = ISD::AND;
424 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
425 Op0IsKill, Imm, VT.getSimpleVT());
426 if (ResultReg == 0) return false;
428 // We successfully emitted code for the given LLVM Instruction.
429 UpdateValueMap(I, ResultReg);
433 // Check if the second operand is a constant float.
434 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
435 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
436 ISDOpcode, Op0, Op0IsKill, CF);
437 if (ResultReg != 0) {
438 // We successfully emitted code for the given LLVM Instruction.
439 UpdateValueMap(I, ResultReg);
444 unsigned Op1 = getRegForValue(I->getOperand(1));
446 // Unhandled operand. Halt "fast" selection and bail.
449 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
451 // Now we have both operands in registers. Emit the instruction.
452 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
457 // Target-specific code wasn't able to find a machine opcode for
458 // the given ISD opcode and type. Halt "fast" selection and bail.
461 // We successfully emitted code for the given LLVM Instruction.
462 UpdateValueMap(I, ResultReg);
466 bool FastISel::SelectGetElementPtr(const User *I) {
467 unsigned N = getRegForValue(I->getOperand(0));
469 // Unhandled operand. Halt "fast" selection and bail.
472 bool NIsKill = hasTrivialKill(I->getOperand(0));
474 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
475 // into a single N = N + TotalOffset.
476 uint64_t TotalOffs = 0;
477 // FIXME: What's a good SWAG number for MaxOffs?
478 uint64_t MaxOffs = 2048;
479 Type *Ty = I->getOperand(0)->getType();
480 MVT VT = TLI.getPointerTy();
481 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
482 E = I->op_end(); OI != E; ++OI) {
483 const Value *Idx = *OI;
484 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
485 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
488 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
489 if (TotalOffs >= MaxOffs) {
490 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
492 // Unhandled operand. Halt "fast" selection and bail.
498 Ty = StTy->getElementType(Field);
500 Ty = cast<SequentialType>(Ty)->getElementType();
502 // If this is a constant subscript, handle it quickly.
503 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
504 if (CI->isZero()) continue;
507 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
508 if (TotalOffs >= MaxOffs) {
509 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
511 // Unhandled operand. Halt "fast" selection and bail.
519 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
521 // Unhandled operand. Halt "fast" selection and bail.
527 // N = N + Idx * ElementSize;
528 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
529 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
530 unsigned IdxN = Pair.first;
531 bool IdxNIsKill = Pair.second;
533 // Unhandled operand. Halt "fast" selection and bail.
536 if (ElementSize != 1) {
537 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
539 // Unhandled operand. Halt "fast" selection and bail.
543 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
545 // Unhandled operand. Halt "fast" selection and bail.
550 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
552 // Unhandled operand. Halt "fast" selection and bail.
556 // We successfully emitted code for the given LLVM Instruction.
557 UpdateValueMap(I, N);
561 bool FastISel::SelectCall(const User *I) {
562 const CallInst *Call = cast<CallInst>(I);
564 // Handle simple inline asms.
565 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
566 // Don't attempt to handle constraints.
567 if (!IA->getConstraintString().empty())
570 unsigned ExtraInfo = 0;
571 if (IA->hasSideEffects())
572 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
573 if (IA->isAlignStack())
574 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
577 TII.get(TargetOpcode::INLINEASM))
578 .addExternalSymbol(IA->getAsmString().c_str())
583 MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
584 ComputeUsesVAFloatArgument(*Call, &MMI);
586 const Function *F = Call->getCalledFunction();
587 if (!F) return false;
589 // Handle selected intrinsic function calls.
590 switch (F->getIntrinsicID()) {
592 // At -O0 we don't care about the lifetime intrinsics.
593 case Intrinsic::lifetime_start:
594 case Intrinsic::lifetime_end:
595 // The donothing intrinsic does, well, nothing.
596 case Intrinsic::donothing:
599 case Intrinsic::dbg_declare: {
600 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
601 if (!DIVariable(DI->getVariable()).Verify() ||
602 !FuncInfo.MF->getMMI().hasDebugInfo()) {
603 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
607 const Value *Address = DI->getAddress();
608 if (!Address || isa<UndefValue>(Address)) {
609 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
615 if (const Argument *Arg = dyn_cast<Argument>(Address)) {
616 // Some arguments' frame index is recorded during argument lowering.
617 Offset = FuncInfo.getArgumentFrameIndex(Arg);
619 Reg = TRI.getFrameRegister(*FuncInfo.MF);
622 Reg = lookUpRegForValue(Address);
624 // If we have a VLA that has a "use" in a metadata node that's then used
625 // here but it has no other uses, then we have a problem. E.g.,
627 // int foo (const int *x) {
632 // If we assign 'a' a vreg and fast isel later on has to use the selection
633 // DAG isel, it will want to copy the value to the vreg. However, there are
634 // no uses, which goes counter to what selection DAG isel expects.
635 if (!Reg && !Address->use_empty() && isa<Instruction>(Address) &&
636 (!isa<AllocaInst>(Address) ||
637 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
638 Reg = FuncInfo.InitializeRegForValue(Address);
641 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
642 TII.get(TargetOpcode::DBG_VALUE))
643 .addReg(Reg, RegState::Debug).addImm(Offset)
644 .addMetadata(DI->getVariable());
646 // We can't yet handle anything else here because it would require
647 // generating code, thus altering codegen because of debug info.
648 DEBUG(dbgs() << "Dropping debug info for " << DI);
651 case Intrinsic::dbg_value: {
652 // This form of DBG_VALUE is target-independent.
653 const DbgValueInst *DI = cast<DbgValueInst>(Call);
654 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
655 const Value *V = DI->getValue();
657 // Currently the optimizer can produce this; insert an undef to
658 // help debugging. Probably the optimizer should not do this.
659 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
660 .addReg(0U).addImm(DI->getOffset())
661 .addMetadata(DI->getVariable());
662 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
663 if (CI->getBitWidth() > 64)
664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
665 .addCImm(CI).addImm(DI->getOffset())
666 .addMetadata(DI->getVariable());
668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
669 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
670 .addMetadata(DI->getVariable());
671 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
673 .addFPImm(CF).addImm(DI->getOffset())
674 .addMetadata(DI->getVariable());
675 } else if (unsigned Reg = lookUpRegForValue(V)) {
676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
677 .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
678 .addMetadata(DI->getVariable());
680 // We can't yet handle anything else here because it would require
681 // generating code, thus altering codegen because of debug info.
682 DEBUG(dbgs() << "Dropping debug info for " << DI);
686 case Intrinsic::objectsize: {
687 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
688 unsigned long long Res = CI->isZero() ? -1ULL : 0;
689 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
690 unsigned ResultReg = getRegForValue(ResCI);
693 UpdateValueMap(Call, ResultReg);
696 case Intrinsic::expect: {
697 unsigned ResultReg = getRegForValue(Call->getArgOperand(0));
700 UpdateValueMap(Call, ResultReg);
705 // Usually, it does not make sense to initialize a value,
706 // make an unrelated function call and use the value, because
707 // it tends to be spilled on the stack. So, we move the pointer
708 // to the last local value to the beginning of the block, so that
709 // all the values which have already been materialized,
710 // appear after the call. It also makes sense to skip intrinsics
711 // since they tend to be inlined.
712 if (!isa<IntrinsicInst>(Call))
713 flushLocalValueMap();
715 // An arbitrary call. Bail.
719 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
720 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
721 EVT DstVT = TLI.getValueType(I->getType());
723 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
724 DstVT == MVT::Other || !DstVT.isSimple())
725 // Unhandled type. Halt "fast" selection and bail.
728 // Check if the destination type is legal.
729 if (!TLI.isTypeLegal(DstVT))
732 // Check if the source operand is legal.
733 if (!TLI.isTypeLegal(SrcVT))
736 unsigned InputReg = getRegForValue(I->getOperand(0));
738 // Unhandled operand. Halt "fast" selection and bail.
741 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
743 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
746 InputReg, InputRegIsKill);
750 UpdateValueMap(I, ResultReg);
754 bool FastISel::SelectBitCast(const User *I) {
755 // If the bitcast doesn't change the type, just use the operand value.
756 if (I->getType() == I->getOperand(0)->getType()) {
757 unsigned Reg = getRegForValue(I->getOperand(0));
760 UpdateValueMap(I, Reg);
764 // Bitcasts of other values become reg-reg copies or BITCAST operators.
765 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
766 EVT DstEVT = TLI.getValueType(I->getType());
767 if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
768 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
769 // Unhandled type. Halt "fast" selection and bail.
772 MVT SrcVT = SrcEVT.getSimpleVT();
773 MVT DstVT = DstEVT.getSimpleVT();
774 unsigned Op0 = getRegForValue(I->getOperand(0));
776 // Unhandled operand. Halt "fast" selection and bail.
779 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
781 // First, try to perform the bitcast by inserting a reg-reg copy.
782 unsigned ResultReg = 0;
783 if (SrcVT == DstVT) {
784 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
785 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
786 // Don't attempt a cross-class copy. It will likely fail.
787 if (SrcClass == DstClass) {
788 ResultReg = createResultReg(DstClass);
789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
790 ResultReg).addReg(Op0);
794 // If the reg-reg copy failed, select a BITCAST opcode.
796 ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
801 UpdateValueMap(I, ResultReg);
806 FastISel::SelectInstruction(const Instruction *I) {
807 // Just before the terminator instruction, insert instructions to
808 // feed PHI nodes in successor blocks.
809 if (isa<TerminatorInst>(I))
810 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
813 DL = I->getDebugLoc();
815 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
817 // As a special case, don't handle calls to builtin library functions that
818 // may be translated directly to target instructions.
819 if (const CallInst *Call = dyn_cast<CallInst>(I)) {
820 const Function *F = Call->getCalledFunction();
822 if (F && !F->hasLocalLinkage() && F->hasName() &&
823 LibInfo->getLibFunc(F->getName(), Func) &&
824 LibInfo->hasOptimizedCodeGen(Func))
828 // First, try doing target-independent selection.
829 if (SelectOperator(I, I->getOpcode())) {
830 ++NumFastIselSuccessIndependent;
834 // Remove dead code. However, ignore call instructions since we've flushed
835 // the local value map and recomputed the insert point.
836 if (!isa<CallInst>(I)) {
838 if (SavedInsertPt != FuncInfo.InsertPt)
839 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
842 // Next, try calling the target to attempt to handle the instruction.
843 SavedInsertPt = FuncInfo.InsertPt;
844 if (TargetSelectInstruction(I)) {
845 ++NumFastIselSuccessTarget;
849 // Check for dead code and remove as necessary.
851 if (SavedInsertPt != FuncInfo.InsertPt)
852 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
858 /// FastEmitBranch - Emit an unconditional branch to the given block,
859 /// unless it is the immediate (fall-through) successor, and update
862 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
864 if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
865 FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
866 // For more accurate line information if this is the only instruction
867 // in the block then emit it, otherwise we have the unconditional
868 // fall-through case, which needs no instructions.
870 // The unconditional branch case.
871 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
872 SmallVector<MachineOperand, 0>(), DL);
874 FuncInfo.MBB->addSuccessor(MSucc);
877 /// SelectFNeg - Emit an FNeg operation.
880 FastISel::SelectFNeg(const User *I) {
881 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
882 if (OpReg == 0) return false;
884 bool OpRegIsKill = hasTrivialKill(I);
886 // If the target has ISD::FNEG, use it.
887 EVT VT = TLI.getValueType(I->getType());
888 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
889 ISD::FNEG, OpReg, OpRegIsKill);
890 if (ResultReg != 0) {
891 UpdateValueMap(I, ResultReg);
895 // Bitcast the value to integer, twiddle the sign bit with xor,
896 // and then bitcast it back to floating-point.
897 if (VT.getSizeInBits() > 64) return false;
898 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
899 if (!TLI.isTypeLegal(IntVT))
902 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
903 ISD::BITCAST, OpReg, OpRegIsKill);
907 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
908 IntReg, /*Kill=*/true,
909 UINT64_C(1) << (VT.getSizeInBits()-1),
910 IntVT.getSimpleVT());
911 if (IntResultReg == 0)
914 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
915 ISD::BITCAST, IntResultReg, /*Kill=*/true);
919 UpdateValueMap(I, ResultReg);
924 FastISel::SelectExtractValue(const User *U) {
925 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
929 // Make sure we only try to handle extracts with a legal result. But also
930 // allow i1 because it's easy.
931 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
932 if (!RealVT.isSimple())
934 MVT VT = RealVT.getSimpleVT();
935 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
938 const Value *Op0 = EVI->getOperand(0);
939 Type *AggTy = Op0->getType();
941 // Get the base result register.
943 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
944 if (I != FuncInfo.ValueMap.end())
945 ResultReg = I->second;
946 else if (isa<Instruction>(Op0))
947 ResultReg = FuncInfo.InitializeRegForValue(Op0);
949 return false; // fast-isel can't handle aggregate constants at the moment
951 // Get the actual result register, which is an offset from the base register.
952 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
954 SmallVector<EVT, 4> AggValueVTs;
955 ComputeValueVTs(TLI, AggTy, AggValueVTs);
957 for (unsigned i = 0; i < VTIndex; i++)
958 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
960 UpdateValueMap(EVI, ResultReg);
965 FastISel::SelectOperator(const User *I, unsigned Opcode) {
967 case Instruction::Add:
968 return SelectBinaryOp(I, ISD::ADD);
969 case Instruction::FAdd:
970 return SelectBinaryOp(I, ISD::FADD);
971 case Instruction::Sub:
972 return SelectBinaryOp(I, ISD::SUB);
973 case Instruction::FSub:
974 // FNeg is currently represented in LLVM IR as a special case of FSub.
975 if (BinaryOperator::isFNeg(I))
976 return SelectFNeg(I);
977 return SelectBinaryOp(I, ISD::FSUB);
978 case Instruction::Mul:
979 return SelectBinaryOp(I, ISD::MUL);
980 case Instruction::FMul:
981 return SelectBinaryOp(I, ISD::FMUL);
982 case Instruction::SDiv:
983 return SelectBinaryOp(I, ISD::SDIV);
984 case Instruction::UDiv:
985 return SelectBinaryOp(I, ISD::UDIV);
986 case Instruction::FDiv:
987 return SelectBinaryOp(I, ISD::FDIV);
988 case Instruction::SRem:
989 return SelectBinaryOp(I, ISD::SREM);
990 case Instruction::URem:
991 return SelectBinaryOp(I, ISD::UREM);
992 case Instruction::FRem:
993 return SelectBinaryOp(I, ISD::FREM);
994 case Instruction::Shl:
995 return SelectBinaryOp(I, ISD::SHL);
996 case Instruction::LShr:
997 return SelectBinaryOp(I, ISD::SRL);
998 case Instruction::AShr:
999 return SelectBinaryOp(I, ISD::SRA);
1000 case Instruction::And:
1001 return SelectBinaryOp(I, ISD::AND);
1002 case Instruction::Or:
1003 return SelectBinaryOp(I, ISD::OR);
1004 case Instruction::Xor:
1005 return SelectBinaryOp(I, ISD::XOR);
1007 case Instruction::GetElementPtr:
1008 return SelectGetElementPtr(I);
1010 case Instruction::Br: {
1011 const BranchInst *BI = cast<BranchInst>(I);
1013 if (BI->isUnconditional()) {
1014 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1015 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1016 FastEmitBranch(MSucc, BI->getDebugLoc());
1020 // Conditional branches are not handed yet.
1021 // Halt "fast" selection and bail.
1025 case Instruction::Unreachable:
1029 case Instruction::Alloca:
1030 // FunctionLowering has the static-sized case covered.
1031 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1034 // Dynamic-sized alloca is not handled yet.
1037 case Instruction::Call:
1038 return SelectCall(I);
1040 case Instruction::BitCast:
1041 return SelectBitCast(I);
1043 case Instruction::FPToSI:
1044 return SelectCast(I, ISD::FP_TO_SINT);
1045 case Instruction::ZExt:
1046 return SelectCast(I, ISD::ZERO_EXTEND);
1047 case Instruction::SExt:
1048 return SelectCast(I, ISD::SIGN_EXTEND);
1049 case Instruction::Trunc:
1050 return SelectCast(I, ISD::TRUNCATE);
1051 case Instruction::SIToFP:
1052 return SelectCast(I, ISD::SINT_TO_FP);
1054 case Instruction::IntToPtr: // Deliberate fall-through.
1055 case Instruction::PtrToInt: {
1056 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1057 EVT DstVT = TLI.getValueType(I->getType());
1058 if (DstVT.bitsGT(SrcVT))
1059 return SelectCast(I, ISD::ZERO_EXTEND);
1060 if (DstVT.bitsLT(SrcVT))
1061 return SelectCast(I, ISD::TRUNCATE);
1062 unsigned Reg = getRegForValue(I->getOperand(0));
1063 if (Reg == 0) return false;
1064 UpdateValueMap(I, Reg);
1068 case Instruction::ExtractValue:
1069 return SelectExtractValue(I);
1071 case Instruction::PHI:
1072 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1075 // Unhandled instruction. Halt "fast" selection and bail.
1080 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1081 const TargetLibraryInfo *libInfo)
1082 : FuncInfo(funcInfo),
1083 MRI(FuncInfo.MF->getRegInfo()),
1084 MFI(*FuncInfo.MF->getFrameInfo()),
1085 MCP(*FuncInfo.MF->getConstantPool()),
1086 TM(FuncInfo.MF->getTarget()),
1087 TD(*TM.getDataLayout()),
1088 TII(*TM.getInstrInfo()),
1089 TLI(*TM.getTargetLowering()),
1090 TRI(*TM.getRegisterInfo()),
1094 FastISel::~FastISel() {}
1096 bool FastISel::FastLowerArguments() {
1100 unsigned FastISel::FastEmit_(MVT, MVT,
1105 unsigned FastISel::FastEmit_r(MVT, MVT,
1107 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1111 unsigned FastISel::FastEmit_rr(MVT, MVT,
1113 unsigned /*Op0*/, bool /*Op0IsKill*/,
1114 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1118 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1122 unsigned FastISel::FastEmit_f(MVT, MVT,
1123 unsigned, const ConstantFP * /*FPImm*/) {
1127 unsigned FastISel::FastEmit_ri(MVT, MVT,
1129 unsigned /*Op0*/, bool /*Op0IsKill*/,
1134 unsigned FastISel::FastEmit_rf(MVT, MVT,
1136 unsigned /*Op0*/, bool /*Op0IsKill*/,
1137 const ConstantFP * /*FPImm*/) {
1141 unsigned FastISel::FastEmit_rri(MVT, MVT,
1143 unsigned /*Op0*/, bool /*Op0IsKill*/,
1144 unsigned /*Op1*/, bool /*Op1IsKill*/,
1149 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1150 /// to emit an instruction with an immediate operand using FastEmit_ri.
1151 /// If that fails, it materializes the immediate into a register and try
1152 /// FastEmit_rr instead.
1153 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1154 unsigned Op0, bool Op0IsKill,
1155 uint64_t Imm, MVT ImmType) {
1156 // If this is a multiply by a power of two, emit this as a shift left.
1157 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1160 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1161 // div x, 8 -> srl x, 3
1166 // Horrible hack (to be removed), check to make sure shift amounts are
1168 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1169 Imm >= VT.getSizeInBits())
1172 // First check if immediate type is legal. If not, we can't use the ri form.
1173 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1176 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1177 if (MaterialReg == 0) {
1178 // This is a bit ugly/slow, but failing here means falling out of
1179 // fast-isel, which would be very slow.
1180 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1181 VT.getSizeInBits());
1182 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1183 assert (MaterialReg != 0 && "Unable to materialize imm.");
1184 if (MaterialReg == 0) return 0;
1186 return FastEmit_rr(VT, VT, Opcode,
1188 MaterialReg, /*Kill=*/true);
1191 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1192 return MRI.createVirtualRegister(RC);
1195 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1196 const TargetRegisterClass* RC) {
1197 unsigned ResultReg = createResultReg(RC);
1198 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1200 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1204 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1205 const TargetRegisterClass *RC,
1206 unsigned Op0, bool Op0IsKill) {
1207 unsigned ResultReg = createResultReg(RC);
1208 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1210 if (II.getNumDefs() >= 1)
1211 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1212 .addReg(Op0, Op0IsKill * RegState::Kill);
1214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1215 .addReg(Op0, Op0IsKill * RegState::Kill);
1216 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1217 ResultReg).addReg(II.ImplicitDefs[0]);
1223 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1224 const TargetRegisterClass *RC,
1225 unsigned Op0, bool Op0IsKill,
1226 unsigned Op1, bool Op1IsKill) {
1227 unsigned ResultReg = createResultReg(RC);
1228 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1230 if (II.getNumDefs() >= 1)
1231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1232 .addReg(Op0, Op0IsKill * RegState::Kill)
1233 .addReg(Op1, Op1IsKill * RegState::Kill);
1235 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1236 .addReg(Op0, Op0IsKill * RegState::Kill)
1237 .addReg(Op1, Op1IsKill * RegState::Kill);
1238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1239 ResultReg).addReg(II.ImplicitDefs[0]);
1244 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1245 const TargetRegisterClass *RC,
1246 unsigned Op0, bool Op0IsKill,
1247 unsigned Op1, bool Op1IsKill,
1248 unsigned Op2, bool Op2IsKill) {
1249 unsigned ResultReg = createResultReg(RC);
1250 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1252 if (II.getNumDefs() >= 1)
1253 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1254 .addReg(Op0, Op0IsKill * RegState::Kill)
1255 .addReg(Op1, Op1IsKill * RegState::Kill)
1256 .addReg(Op2, Op2IsKill * RegState::Kill);
1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1259 .addReg(Op0, Op0IsKill * RegState::Kill)
1260 .addReg(Op1, Op1IsKill * RegState::Kill)
1261 .addReg(Op2, Op2IsKill * RegState::Kill);
1262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1263 ResultReg).addReg(II.ImplicitDefs[0]);
1268 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1269 const TargetRegisterClass *RC,
1270 unsigned Op0, bool Op0IsKill,
1272 unsigned ResultReg = createResultReg(RC);
1273 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1275 if (II.getNumDefs() >= 1)
1276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1277 .addReg(Op0, Op0IsKill * RegState::Kill)
1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1281 .addReg(Op0, Op0IsKill * RegState::Kill)
1283 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1284 ResultReg).addReg(II.ImplicitDefs[0]);
1289 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1290 const TargetRegisterClass *RC,
1291 unsigned Op0, bool Op0IsKill,
1292 uint64_t Imm1, uint64_t Imm2) {
1293 unsigned ResultReg = createResultReg(RC);
1294 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1296 if (II.getNumDefs() >= 1)
1297 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1298 .addReg(Op0, Op0IsKill * RegState::Kill)
1302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1303 .addReg(Op0, Op0IsKill * RegState::Kill)
1306 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1307 ResultReg).addReg(II.ImplicitDefs[0]);
1312 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1313 const TargetRegisterClass *RC,
1314 unsigned Op0, bool Op0IsKill,
1315 const ConstantFP *FPImm) {
1316 unsigned ResultReg = createResultReg(RC);
1317 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1319 if (II.getNumDefs() >= 1)
1320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1321 .addReg(Op0, Op0IsKill * RegState::Kill)
1324 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1325 .addReg(Op0, Op0IsKill * RegState::Kill)
1327 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1328 ResultReg).addReg(II.ImplicitDefs[0]);
1333 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1334 const TargetRegisterClass *RC,
1335 unsigned Op0, bool Op0IsKill,
1336 unsigned Op1, bool Op1IsKill,
1338 unsigned ResultReg = createResultReg(RC);
1339 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1341 if (II.getNumDefs() >= 1)
1342 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1343 .addReg(Op0, Op0IsKill * RegState::Kill)
1344 .addReg(Op1, Op1IsKill * RegState::Kill)
1347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1348 .addReg(Op0, Op0IsKill * RegState::Kill)
1349 .addReg(Op1, Op1IsKill * RegState::Kill)
1351 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1352 ResultReg).addReg(II.ImplicitDefs[0]);
1357 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1358 const TargetRegisterClass *RC,
1359 unsigned Op0, bool Op0IsKill,
1360 unsigned Op1, bool Op1IsKill,
1361 uint64_t Imm1, uint64_t Imm2) {
1362 unsigned ResultReg = createResultReg(RC);
1363 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1365 if (II.getNumDefs() >= 1)
1366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1367 .addReg(Op0, Op0IsKill * RegState::Kill)
1368 .addReg(Op1, Op1IsKill * RegState::Kill)
1369 .addImm(Imm1).addImm(Imm2);
1371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1372 .addReg(Op0, Op0IsKill * RegState::Kill)
1373 .addReg(Op1, Op1IsKill * RegState::Kill)
1374 .addImm(Imm1).addImm(Imm2);
1375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1376 ResultReg).addReg(II.ImplicitDefs[0]);
1381 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1382 const TargetRegisterClass *RC,
1384 unsigned ResultReg = createResultReg(RC);
1385 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1387 if (II.getNumDefs() >= 1)
1388 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1390 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1391 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1392 ResultReg).addReg(II.ImplicitDefs[0]);
1397 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1398 const TargetRegisterClass *RC,
1399 uint64_t Imm1, uint64_t Imm2) {
1400 unsigned ResultReg = createResultReg(RC);
1401 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1403 if (II.getNumDefs() >= 1)
1404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1405 .addImm(Imm1).addImm(Imm2);
1407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1409 ResultReg).addReg(II.ImplicitDefs[0]);
1414 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1415 unsigned Op0, bool Op0IsKill,
1417 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1418 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1419 "Cannot yet extract from physregs");
1420 const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1421 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1423 DL, TII.get(TargetOpcode::COPY), ResultReg)
1424 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1428 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1429 /// with all but the least significant bit set to zero.
1430 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1431 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1434 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1435 /// Emit code to ensure constants are copied into registers when needed.
1436 /// Remember the virtual registers that need to be added to the Machine PHI
1437 /// nodes as input. We cannot just directly add them, because expansion
1438 /// might result in multiple MBB's for one BB. As such, the start of the
1439 /// BB might correspond to a different MBB than the end.
1440 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1441 const TerminatorInst *TI = LLVMBB->getTerminator();
1443 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1444 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1446 // Check successor nodes' PHI nodes that expect a constant to be available
1448 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1449 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1450 if (!isa<PHINode>(SuccBB->begin())) continue;
1451 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1453 // If this terminator has multiple identical successors (common for
1454 // switches), only handle each succ once.
1455 if (!SuccsHandled.insert(SuccMBB)) continue;
1457 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1459 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1460 // nodes and Machine PHI nodes, but the incoming operands have not been
1462 for (BasicBlock::const_iterator I = SuccBB->begin();
1463 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1465 // Ignore dead phi's.
1466 if (PN->use_empty()) continue;
1468 // Only handle legal types. Two interesting things to note here. First,
1469 // by bailing out early, we may leave behind some dead instructions,
1470 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1471 // own moves. Second, this check is necessary because FastISel doesn't
1472 // use CreateRegs to create registers, so it always creates
1473 // exactly one register for each non-void instruction.
1474 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1475 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1476 // Handle integer promotions, though, because they're common and easy.
1477 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1478 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1480 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1485 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1487 // Set the DebugLoc for the copy. Prefer the location of the operand
1488 // if there is one; use the location of the PHI otherwise.
1489 DL = PN->getDebugLoc();
1490 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1491 DL = Inst->getDebugLoc();
1493 unsigned Reg = getRegForValue(PHIOp);
1495 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1498 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1506 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
1507 assert(LI->hasOneUse() &&
1508 "tryToFoldLoad expected a LoadInst with a single use");
1509 // We know that the load has a single use, but don't know what it is. If it
1510 // isn't one of the folded instructions, then we can't succeed here. Handle
1511 // this by scanning the single-use users of the load until we get to FoldInst.
1512 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
1514 const Instruction *TheUser = LI->use_back();
1515 while (TheUser != FoldInst && // Scan up until we find FoldInst.
1516 // Stay in the right block.
1517 TheUser->getParent() == FoldInst->getParent() &&
1518 --MaxUsers) { // Don't scan too far.
1519 // If there are multiple or no uses of this instruction, then bail out.
1520 if (!TheUser->hasOneUse())
1523 TheUser = TheUser->use_back();
1526 // If we didn't find the fold instruction, then we failed to collapse the
1528 if (TheUser != FoldInst)
1531 // Don't try to fold volatile loads. Target has to deal with alignment
1533 if (LI->isVolatile())
1536 // Figure out which vreg this is going into. If there is no assigned vreg yet
1537 // then there actually was no reference to it. Perhaps the load is referenced
1538 // by a dead instruction.
1539 unsigned LoadReg = getRegForValue(LI);
1543 // We can't fold if this vreg has no uses or more than one use. Multiple uses
1544 // may mean that the instruction got lowered to multiple MIs, or the use of
1545 // the loaded value ended up being multiple operands of the result.
1546 if (!MRI.hasOneUse(LoadReg))
1549 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
1550 MachineInstr *User = &*RI;
1552 // Set the insertion point properly. Folding the load can cause generation of
1553 // other random instructions (like sign extends) for addressing modes; make
1554 // sure they get inserted in a logical place before the new instruction.
1555 FuncInfo.InsertPt = User;
1556 FuncInfo.MBB = User->getParent();
1558 // Ask the target to try folding the load.
1559 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);