1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel 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 implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/Collector.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Compiler.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
60 cl::desc("Pop up a window to show SUnit dags after they are processed"));
62 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
65 //===---------------------------------------------------------------------===//
67 /// RegisterScheduler class - Track the registration of instruction schedulers.
69 //===---------------------------------------------------------------------===//
70 MachinePassRegistry RegisterScheduler::Registry;
72 //===---------------------------------------------------------------------===//
74 /// ISHeuristic command line option for instruction schedulers.
76 //===---------------------------------------------------------------------===//
78 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
80 ISHeuristic("pre-RA-sched",
81 cl::init(&createDefaultScheduler),
82 cl::desc("Instruction schedulers available (before register"
85 static RegisterScheduler
86 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
90 namespace { struct SDISelAsmOperandInfo; }
92 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
93 /// MVT::ValueTypes that represent all the individual underlying
94 /// non-aggregate types that comprise it.
95 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
96 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
97 // Given a struct type, recursively traverse the elements.
98 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
99 for (StructType::element_iterator EI = STy->element_begin(),
100 EB = STy->element_end();
102 ComputeValueVTs(TLI, *EI, ValueVTs);
105 // Given an array type, recursively traverse the elements.
106 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
107 const Type *EltTy = ATy->getElementType();
108 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
109 ComputeValueVTs(TLI, EltTy, ValueVTs);
112 // Base case: we can get an MVT::ValueType for this LLVM IR type.
113 ValueVTs.push_back(TLI.getValueType(Ty));
117 /// RegsForValue - This struct represents the physical registers that a
118 /// particular value is assigned and the type information about the value.
119 /// This is needed because values can be promoted into larger registers and
120 /// expanded into multiple smaller registers than the value.
121 struct VISIBILITY_HIDDEN RegsForValue {
122 /// TLI - The TargetLowering object.
123 const TargetLowering *TLI;
125 /// Regs - This list holds the register (for legal and promoted values)
126 /// or register set (for expanded values) that the value should be assigned
128 SmallVector<unsigned, 4> Regs;
130 /// RegVTs - The value types of the registers. This is the same size
131 /// as ValueVTs; every register contributing to a given value must
132 /// have the same type. When Regs contains all virtual registers, the
133 /// contents of RegVTs is redundant with TLI's getRegisterType member
134 /// function, however when Regs contains physical registers, it is
135 /// necessary to have a separate record of the types.
137 SmallVector<MVT::ValueType, 4> RegVTs;
139 /// ValueVTs - The value types of the values, which may be promoted
140 /// or synthesized from one or more registers.
141 SmallVector<MVT::ValueType, 4> ValueVTs;
143 RegsForValue() : TLI(0) {}
145 RegsForValue(const TargetLowering &tli,
146 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
147 : TLI(&tli), Regs(1, Reg), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
148 RegsForValue(const TargetLowering &tli,
149 const SmallVector<unsigned, 4> ®s,
150 MVT::ValueType regvt, MVT::ValueType valuevt)
151 : TLI(&tli), Regs(regs), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
152 RegsForValue(const TargetLowering &tli,
153 const SmallVector<unsigned, 4> ®s,
154 const SmallVector<MVT::ValueType, 4> ®vts,
155 const SmallVector<MVT::ValueType, 4> &valuevts)
156 : TLI(&tli), Regs(regs), RegVTs(regvts), ValueVTs(valuevts) {}
157 RegsForValue(const TargetLowering &tli,
158 unsigned Reg, const Type *Ty) : TLI(&tli) {
159 ComputeValueVTs(tli, Ty, ValueVTs);
161 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
162 MVT::ValueType ValueVT = ValueVTs[Value];
163 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
164 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
165 for (unsigned i = 0; i != NumRegs; ++i)
166 Regs.push_back(Reg + i);
167 RegVTs.push_back(RegisterVT);
172 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
173 /// this value and returns the result as a ValueVTs value. This uses
174 /// Chain/Flag as the input and updates them for the output Chain/Flag.
175 /// If the Flag pointer is NULL, no flag is used.
176 SDOperand getCopyFromRegs(SelectionDAG &DAG,
177 SDOperand &Chain, SDOperand *Flag) const;
179 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
180 /// specified value into the registers specified by this object. This uses
181 /// Chain/Flag as the input and updates them for the output Chain/Flag.
182 /// If the Flag pointer is NULL, no flag is used.
183 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
184 SDOperand &Chain, SDOperand *Flag) const;
186 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
187 /// operand list. This adds the code marker and includes the number of
188 /// values added into it.
189 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
190 std::vector<SDOperand> &Ops) const;
195 //===--------------------------------------------------------------------===//
196 /// createDefaultScheduler - This creates an instruction scheduler appropriate
198 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
200 MachineBasicBlock *BB) {
201 TargetLowering &TLI = IS->getTargetLowering();
203 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
204 return createTDListDAGScheduler(IS, DAG, BB);
206 assert(TLI.getSchedulingPreference() ==
207 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
208 return createBURRListDAGScheduler(IS, DAG, BB);
213 //===--------------------------------------------------------------------===//
214 /// FunctionLoweringInfo - This contains information that is global to a
215 /// function that is used when lowering a region of the function.
216 class FunctionLoweringInfo {
221 MachineRegisterInfo &RegInfo;
223 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
225 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
226 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
228 /// ValueMap - Since we emit code for the function a basic block at a time,
229 /// we must remember which virtual registers hold the values for
230 /// cross-basic-block values.
231 DenseMap<const Value*, unsigned> ValueMap;
233 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
234 /// the entry block. This allows the allocas to be efficiently referenced
235 /// anywhere in the function.
236 std::map<const AllocaInst*, int> StaticAllocaMap;
239 SmallSet<Instruction*, 8> CatchInfoLost;
240 SmallSet<Instruction*, 8> CatchInfoFound;
243 unsigned MakeReg(MVT::ValueType VT) {
244 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
247 /// isExportedInst - Return true if the specified value is an instruction
248 /// exported from its block.
249 bool isExportedInst(const Value *V) {
250 return ValueMap.count(V);
253 unsigned CreateRegForValue(const Value *V);
255 unsigned InitializeRegForValue(const Value *V) {
256 unsigned &R = ValueMap[V];
257 assert(R == 0 && "Already initialized this value register!");
258 return R = CreateRegForValue(V);
263 /// isSelector - Return true if this instruction is a call to the
264 /// eh.selector intrinsic.
265 static bool isSelector(Instruction *I) {
266 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
267 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
268 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
272 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
273 /// PHI nodes or outside of the basic block that defines it, or used by a
274 /// switch or atomic instruction, which may expand to multiple basic blocks.
275 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
276 if (isa<PHINode>(I)) return true;
277 BasicBlock *BB = I->getParent();
278 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
279 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
280 // FIXME: Remove switchinst special case.
281 isa<SwitchInst>(*UI))
286 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
287 /// entry block, return true. This includes arguments used by switches, since
288 /// the switch may expand into multiple basic blocks.
289 static bool isOnlyUsedInEntryBlock(Argument *A) {
290 BasicBlock *Entry = A->getParent()->begin();
291 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
292 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
293 return false; // Use not in entry block.
297 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
298 Function &fn, MachineFunction &mf)
299 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
301 // Create a vreg for each argument register that is not dead and is used
302 // outside of the entry block for the function.
303 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
305 if (!isOnlyUsedInEntryBlock(AI))
306 InitializeRegForValue(AI);
308 // Initialize the mapping of values to registers. This is only set up for
309 // instruction values that are used outside of the block that defines
311 Function::iterator BB = Fn.begin(), EB = Fn.end();
312 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
313 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
314 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
315 const Type *Ty = AI->getAllocatedType();
316 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
318 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
321 TySize *= CUI->getZExtValue(); // Get total allocated size.
322 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
323 StaticAllocaMap[AI] =
324 MF.getFrameInfo()->CreateStackObject(TySize, Align);
327 for (; BB != EB; ++BB)
328 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
329 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
330 if (!isa<AllocaInst>(I) ||
331 !StaticAllocaMap.count(cast<AllocaInst>(I)))
332 InitializeRegForValue(I);
334 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
335 // also creates the initial PHI MachineInstrs, though none of the input
336 // operands are populated.
337 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
338 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
340 MF.getBasicBlockList().push_back(MBB);
342 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
345 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
346 if (PN->use_empty()) continue;
348 MVT::ValueType VT = TLI.getValueType(PN->getType());
349 unsigned NumRegisters = TLI.getNumRegisters(VT);
350 unsigned PHIReg = ValueMap[PN];
351 assert(PHIReg && "PHI node does not have an assigned virtual register!");
352 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
353 for (unsigned i = 0; i != NumRegisters; ++i)
354 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
359 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
360 /// the correctly promoted or expanded types. Assign these registers
361 /// consecutive vreg numbers and return the first assigned number.
362 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
363 SmallVector<MVT::ValueType, 4> ValueVTs;
364 ComputeValueVTs(TLI, V->getType(), ValueVTs);
366 unsigned FirstReg = 0;
367 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
368 MVT::ValueType ValueVT = ValueVTs[Value];
369 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
371 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
372 for (unsigned i = 0; i != NumRegs; ++i) {
373 unsigned R = MakeReg(RegisterVT);
374 if (!FirstReg) FirstReg = R;
380 //===----------------------------------------------------------------------===//
381 /// SelectionDAGLowering - This is the common target-independent lowering
382 /// implementation that is parameterized by a TargetLowering object.
383 /// Also, targets can overload any lowering method.
386 class SelectionDAGLowering {
387 MachineBasicBlock *CurMBB;
389 DenseMap<const Value*, SDOperand> NodeMap;
391 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
392 /// them up and then emit token factor nodes when possible. This allows us to
393 /// get simple disambiguation between loads without worrying about alias
395 std::vector<SDOperand> PendingLoads;
397 /// PendingExports - CopyToReg nodes that copy values to virtual registers
398 /// for export to other blocks need to be emitted before any terminator
399 /// instruction, but they have no other ordering requirements. We bunch them
400 /// up and the emit a single tokenfactor for them just before terminator
402 std::vector<SDOperand> PendingExports;
404 /// Case - A struct to record the Value for a switch case, and the
405 /// case's target basic block.
409 MachineBasicBlock* BB;
411 Case() : Low(0), High(0), BB(0) { }
412 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
413 Low(low), High(high), BB(bb) { }
414 uint64_t size() const {
415 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
416 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
417 return (rHigh - rLow + 1ULL);
423 MachineBasicBlock* BB;
426 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
427 Mask(mask), BB(bb), Bits(bits) { }
430 typedef std::vector<Case> CaseVector;
431 typedef std::vector<CaseBits> CaseBitsVector;
432 typedef CaseVector::iterator CaseItr;
433 typedef std::pair<CaseItr, CaseItr> CaseRange;
435 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
436 /// of conditional branches.
438 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
439 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
441 /// CaseBB - The MBB in which to emit the compare and branch
442 MachineBasicBlock *CaseBB;
443 /// LT, GE - If nonzero, we know the current case value must be less-than or
444 /// greater-than-or-equal-to these Constants.
447 /// Range - A pair of iterators representing the range of case values to be
448 /// processed at this point in the binary search tree.
452 typedef std::vector<CaseRec> CaseRecVector;
454 /// The comparison function for sorting the switch case values in the vector.
455 /// WARNING: Case ranges should be disjoint!
457 bool operator () (const Case& C1, const Case& C2) {
458 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
459 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
460 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
461 return CI1->getValue().slt(CI2->getValue());
466 bool operator () (const CaseBits& C1, const CaseBits& C2) {
467 return C1.Bits > C2.Bits;
471 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
474 // TLI - This is information that describes the available target features we
475 // need for lowering. This indicates when operations are unavailable,
476 // implemented with a libcall, etc.
479 const TargetData *TD;
482 /// SwitchCases - Vector of CaseBlock structures used to communicate
483 /// SwitchInst code generation information.
484 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
485 /// JTCases - Vector of JumpTable structures used to communicate
486 /// SwitchInst code generation information.
487 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
488 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
490 /// FuncInfo - Information about the function as a whole.
492 FunctionLoweringInfo &FuncInfo;
494 /// GCI - Garbage collection metadata for the function.
495 CollectorMetadata *GCI;
497 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
499 FunctionLoweringInfo &funcinfo,
500 CollectorMetadata *gci)
501 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
502 FuncInfo(funcinfo), GCI(gci) {
505 /// getRoot - Return the current virtual root of the Selection DAG,
506 /// flushing any PendingLoad items. This must be done before emitting
507 /// a store or any other node that may need to be ordered after any
508 /// prior load instructions.
510 SDOperand getRoot() {
511 if (PendingLoads.empty())
512 return DAG.getRoot();
514 if (PendingLoads.size() == 1) {
515 SDOperand Root = PendingLoads[0];
517 PendingLoads.clear();
521 // Otherwise, we have to make a token factor node.
522 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
523 &PendingLoads[0], PendingLoads.size());
524 PendingLoads.clear();
529 /// getControlRoot - Similar to getRoot, but instead of flushing all the
530 /// PendingLoad items, flush all the PendingExports items. It is necessary
531 /// to do this before emitting a terminator instruction.
533 SDOperand getControlRoot() {
534 SDOperand Root = DAG.getRoot();
536 if (PendingExports.empty())
539 // Turn all of the CopyToReg chains into one factored node.
540 if (Root.getOpcode() != ISD::EntryToken) {
541 unsigned i = 0, e = PendingExports.size();
542 for (; i != e; ++i) {
543 assert(PendingExports[i].Val->getNumOperands() > 1);
544 if (PendingExports[i].Val->getOperand(0) == Root)
545 break; // Don't add the root if we already indirectly depend on it.
549 PendingExports.push_back(Root);
552 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
554 PendingExports.size());
555 PendingExports.clear();
560 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
562 void visit(Instruction &I) { visit(I.getOpcode(), I); }
564 void visit(unsigned Opcode, User &I) {
565 // Note: this doesn't use InstVisitor, because it has to work with
566 // ConstantExpr's in addition to instructions.
568 default: assert(0 && "Unknown instruction type encountered!");
570 // Build the switch statement using the Instruction.def file.
571 #define HANDLE_INST(NUM, OPCODE, CLASS) \
572 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
573 #include "llvm/Instruction.def"
577 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
579 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
580 const Value *SV, SDOperand Root,
581 bool isVolatile, unsigned Alignment);
583 SDOperand getValue(const Value *V);
585 void setValue(const Value *V, SDOperand NewN) {
586 SDOperand &N = NodeMap[V];
587 assert(N.Val == 0 && "Already set a value for this node!");
591 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
592 std::set<unsigned> &OutputRegs,
593 std::set<unsigned> &InputRegs);
595 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
596 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
598 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
599 void ExportFromCurrentBlock(Value *V);
600 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
601 MachineBasicBlock *LandingPad = NULL);
603 // Terminator instructions.
604 void visitRet(ReturnInst &I);
605 void visitBr(BranchInst &I);
606 void visitSwitch(SwitchInst &I);
607 void visitUnreachable(UnreachableInst &I) { /* noop */ }
609 // Helpers for visitSwitch
610 bool handleSmallSwitchRange(CaseRec& CR,
611 CaseRecVector& WorkList,
613 MachineBasicBlock* Default);
614 bool handleJTSwitchCase(CaseRec& CR,
615 CaseRecVector& WorkList,
617 MachineBasicBlock* Default);
618 bool handleBTSplitSwitchCase(CaseRec& CR,
619 CaseRecVector& WorkList,
621 MachineBasicBlock* Default);
622 bool handleBitTestsSwitchCase(CaseRec& CR,
623 CaseRecVector& WorkList,
625 MachineBasicBlock* Default);
626 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
627 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
628 void visitBitTestCase(MachineBasicBlock* NextMBB,
630 SelectionDAGISel::BitTestCase &B);
631 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
632 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
633 SelectionDAGISel::JumpTableHeader &JTH);
635 // These all get lowered before this pass.
636 void visitInvoke(InvokeInst &I);
637 void visitUnwind(UnwindInst &I);
639 void visitBinary(User &I, unsigned OpCode);
640 void visitShift(User &I, unsigned Opcode);
641 void visitAdd(User &I) {
642 if (I.getType()->isFPOrFPVector())
643 visitBinary(I, ISD::FADD);
645 visitBinary(I, ISD::ADD);
647 void visitSub(User &I);
648 void visitMul(User &I) {
649 if (I.getType()->isFPOrFPVector())
650 visitBinary(I, ISD::FMUL);
652 visitBinary(I, ISD::MUL);
654 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
655 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
656 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
657 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
658 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
659 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
660 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
661 void visitOr (User &I) { visitBinary(I, ISD::OR); }
662 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
663 void visitShl (User &I) { visitShift(I, ISD::SHL); }
664 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
665 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
666 void visitICmp(User &I);
667 void visitFCmp(User &I);
668 // Visit the conversion instructions
669 void visitTrunc(User &I);
670 void visitZExt(User &I);
671 void visitSExt(User &I);
672 void visitFPTrunc(User &I);
673 void visitFPExt(User &I);
674 void visitFPToUI(User &I);
675 void visitFPToSI(User &I);
676 void visitUIToFP(User &I);
677 void visitSIToFP(User &I);
678 void visitPtrToInt(User &I);
679 void visitIntToPtr(User &I);
680 void visitBitCast(User &I);
682 void visitExtractElement(User &I);
683 void visitInsertElement(User &I);
684 void visitShuffleVector(User &I);
686 void visitGetElementPtr(User &I);
687 void visitSelect(User &I);
689 void visitMalloc(MallocInst &I);
690 void visitFree(FreeInst &I);
691 void visitAlloca(AllocaInst &I);
692 void visitLoad(LoadInst &I);
693 void visitStore(StoreInst &I);
694 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
695 void visitCall(CallInst &I);
696 void visitInlineAsm(CallSite CS);
697 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
698 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
700 void visitVAStart(CallInst &I);
701 void visitVAArg(VAArgInst &I);
702 void visitVAEnd(CallInst &I);
703 void visitVACopy(CallInst &I);
705 void visitGetResult(GetResultInst &I);
707 void visitUserOp1(Instruction &I) {
708 assert(0 && "UserOp1 should not exist at instruction selection time!");
711 void visitUserOp2(Instruction &I) {
712 assert(0 && "UserOp2 should not exist at instruction selection time!");
716 } // end namespace llvm
719 /// getCopyFromParts - Create a value that contains the specified legal parts
720 /// combined into the value they represent. If the parts combine to a type
721 /// larger then ValueVT then AssertOp can be used to specify whether the extra
722 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
723 /// (ISD::AssertSext).
724 static SDOperand getCopyFromParts(SelectionDAG &DAG,
725 const SDOperand *Parts,
727 MVT::ValueType PartVT,
728 MVT::ValueType ValueVT,
729 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
730 assert(NumParts > 0 && "No parts to assemble!");
731 TargetLowering &TLI = DAG.getTargetLoweringInfo();
732 SDOperand Val = Parts[0];
735 // Assemble the value from multiple parts.
736 if (!MVT::isVector(ValueVT)) {
737 unsigned PartBits = MVT::getSizeInBits(PartVT);
738 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
740 // Assemble the power of 2 part.
741 unsigned RoundParts = NumParts & (NumParts - 1) ?
742 1 << Log2_32(NumParts) : NumParts;
743 unsigned RoundBits = PartBits * RoundParts;
744 MVT::ValueType RoundVT = RoundBits == ValueBits ?
745 ValueVT : MVT::getIntegerType(RoundBits);
748 if (RoundParts > 2) {
749 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
750 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
751 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
757 if (TLI.isBigEndian())
759 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
761 if (RoundParts < NumParts) {
762 // Assemble the trailing non-power-of-2 part.
763 unsigned OddParts = NumParts - RoundParts;
764 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
765 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
767 // Combine the round and odd parts.
769 if (TLI.isBigEndian())
771 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
772 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
773 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
774 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
775 TLI.getShiftAmountTy()));
776 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
777 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
780 // Handle a multi-element vector.
781 MVT::ValueType IntermediateVT, RegisterVT;
782 unsigned NumIntermediates;
784 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
787 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
788 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
789 assert(RegisterVT == Parts[0].getValueType() &&
790 "Part type doesn't match part!");
792 // Assemble the parts into intermediate operands.
793 SmallVector<SDOperand, 8> Ops(NumIntermediates);
794 if (NumIntermediates == NumParts) {
795 // If the register was not expanded, truncate or copy the value,
797 for (unsigned i = 0; i != NumParts; ++i)
798 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
799 PartVT, IntermediateVT);
800 } else if (NumParts > 0) {
801 // If the intermediate type was expanded, build the intermediate operands
803 assert(NumParts % NumIntermediates == 0 &&
804 "Must expand into a divisible number of parts!");
805 unsigned Factor = NumParts / NumIntermediates;
806 for (unsigned i = 0; i != NumIntermediates; ++i)
807 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
808 PartVT, IntermediateVT);
811 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
813 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
814 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
815 ValueVT, &Ops[0], NumIntermediates);
819 // There is now one part, held in Val. Correct it to match ValueVT.
820 PartVT = Val.getValueType();
822 if (PartVT == ValueVT)
825 if (MVT::isVector(PartVT)) {
826 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
827 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
830 if (MVT::isVector(ValueVT)) {
831 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
832 MVT::getVectorNumElements(ValueVT) == 1 &&
833 "Only trivial scalar-to-vector conversions should get here!");
834 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
837 if (MVT::isInteger(PartVT) &&
838 MVT::isInteger(ValueVT)) {
839 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
840 // For a truncate, see if we have any information to
841 // indicate whether the truncated bits will always be
842 // zero or sign-extension.
843 if (AssertOp != ISD::DELETED_NODE)
844 Val = DAG.getNode(AssertOp, PartVT, Val,
845 DAG.getValueType(ValueVT));
846 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
848 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
852 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
853 if (ValueVT < Val.getValueType())
854 // FP_ROUND's are always exact here.
855 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
856 DAG.getIntPtrConstant(1));
857 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
860 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
861 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
863 assert(0 && "Unknown mismatch!");
867 /// getCopyToParts - Create a series of nodes that contain the specified value
868 /// split into legal parts. If the parts contain more bits than Val, then, for
869 /// integers, ExtendKind can be used to specify how to generate the extra bits.
870 static void getCopyToParts(SelectionDAG &DAG,
874 MVT::ValueType PartVT,
875 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
876 TargetLowering &TLI = DAG.getTargetLoweringInfo();
877 MVT::ValueType PtrVT = TLI.getPointerTy();
878 MVT::ValueType ValueVT = Val.getValueType();
879 unsigned PartBits = MVT::getSizeInBits(PartVT);
880 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
885 if (!MVT::isVector(ValueVT)) {
886 if (PartVT == ValueVT) {
887 assert(NumParts == 1 && "No-op copy with multiple parts!");
892 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
893 // If the parts cover more bits than the value has, promote the value.
894 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
895 assert(NumParts == 1 && "Do not know what to promote to!");
896 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
897 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
898 ValueVT = MVT::getIntegerType(NumParts * PartBits);
899 Val = DAG.getNode(ExtendKind, ValueVT, Val);
901 assert(0 && "Unknown mismatch!");
903 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
904 // Different types of the same size.
905 assert(NumParts == 1 && PartVT != ValueVT);
906 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
907 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
908 // If the parts cover less bits than value has, truncate the value.
909 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
910 ValueVT = MVT::getIntegerType(NumParts * PartBits);
911 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
913 assert(0 && "Unknown mismatch!");
917 // The value may have changed - recompute ValueVT.
918 ValueVT = Val.getValueType();
919 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
920 "Failed to tile the value with PartVT!");
923 assert(PartVT == ValueVT && "Type conversion failed!");
928 // Expand the value into multiple parts.
929 if (NumParts & (NumParts - 1)) {
930 // The number of parts is not a power of 2. Split off and copy the tail.
931 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
932 "Do not know what to expand to!");
933 unsigned RoundParts = 1 << Log2_32(NumParts);
934 unsigned RoundBits = RoundParts * PartBits;
935 unsigned OddParts = NumParts - RoundParts;
936 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
937 DAG.getConstant(RoundBits,
938 TLI.getShiftAmountTy()));
939 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
940 if (TLI.isBigEndian())
941 // The odd parts were reversed by getCopyToParts - unreverse them.
942 std::reverse(Parts + RoundParts, Parts + NumParts);
943 NumParts = RoundParts;
944 ValueVT = MVT::getIntegerType(NumParts * PartBits);
945 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
948 // The number of parts is a power of 2. Repeatedly bisect the value using
950 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
951 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
953 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
954 for (unsigned i = 0; i < NumParts; i += StepSize) {
955 unsigned ThisBits = StepSize * PartBits / 2;
956 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
957 SDOperand &Part0 = Parts[i];
958 SDOperand &Part1 = Parts[i+StepSize/2];
960 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
961 DAG.getConstant(1, PtrVT));
962 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
963 DAG.getConstant(0, PtrVT));
965 if (ThisBits == PartBits && ThisVT != PartVT) {
966 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
967 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
972 if (TLI.isBigEndian())
973 std::reverse(Parts, Parts + NumParts);
980 if (PartVT != ValueVT) {
981 if (MVT::isVector(PartVT)) {
982 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
984 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
985 MVT::getVectorNumElements(ValueVT) == 1 &&
986 "Only trivial vector-to-scalar conversions should get here!");
987 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
988 DAG.getConstant(0, PtrVT));
996 // Handle a multi-element vector.
997 MVT::ValueType IntermediateVT, RegisterVT;
998 unsigned NumIntermediates;
1000 DAG.getTargetLoweringInfo()
1001 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1003 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1005 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1006 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1008 // Split the vector into intermediate operands.
1009 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1010 for (unsigned i = 0; i != NumIntermediates; ++i)
1011 if (MVT::isVector(IntermediateVT))
1012 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1013 IntermediateVT, Val,
1014 DAG.getConstant(i * (NumElements / NumIntermediates),
1017 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1018 IntermediateVT, Val,
1019 DAG.getConstant(i, PtrVT));
1021 // Split the intermediate operands into legal parts.
1022 if (NumParts == NumIntermediates) {
1023 // If the register was not expanded, promote or copy the value,
1025 for (unsigned i = 0; i != NumParts; ++i)
1026 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1027 } else if (NumParts > 0) {
1028 // If the intermediate type was expanded, split each the value into
1030 assert(NumParts % NumIntermediates == 0 &&
1031 "Must expand into a divisible number of parts!");
1032 unsigned Factor = NumParts / NumIntermediates;
1033 for (unsigned i = 0; i != NumIntermediates; ++i)
1034 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1039 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1040 SDOperand &N = NodeMap[V];
1041 if (N.Val) return N;
1043 const Type *VTy = V->getType();
1044 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1045 MVT::ValueType VT = TLI.getValueType(VTy, true);
1047 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1048 return N = DAG.getConstant(CI->getValue(), VT);
1050 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1051 return N = DAG.getGlobalAddress(GV, VT);
1053 if (isa<ConstantPointerNull>(C))
1054 return N = DAG.getConstant(0, TLI.getPointerTy());
1056 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1057 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1059 if (isa<UndefValue>(C)) {
1060 if (!isa<VectorType>(VTy))
1061 return N = DAG.getNode(ISD::UNDEF, VT);
1063 // Create a BUILD_VECTOR of undef nodes.
1064 const VectorType *PTy = cast<VectorType>(VTy);
1065 unsigned NumElements = PTy->getNumElements();
1066 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1068 SmallVector<SDOperand, 8> Ops;
1069 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
1071 // Create a VConstant node with generic Vector type.
1072 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
1073 return N = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1076 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1077 visit(CE->getOpcode(), *CE);
1078 SDOperand N1 = NodeMap[V];
1079 assert(N1.Val && "visit didn't populate the ValueMap!");
1083 const VectorType *VecTy = cast<VectorType>(VTy);
1084 unsigned NumElements = VecTy->getNumElements();
1085 MVT::ValueType PVT = TLI.getValueType(VecTy->getElementType());
1087 // Now that we know the number and type of the elements, push a
1088 // Constant or ConstantFP node onto the ops list for each element of
1089 // the vector constant.
1090 SmallVector<SDOperand, 8> Ops;
1091 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1092 for (unsigned i = 0; i != NumElements; ++i)
1093 Ops.push_back(getValue(CP->getOperand(i)));
1095 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1097 if (MVT::isFloatingPoint(PVT))
1098 Op = DAG.getConstantFP(0, PVT);
1100 Op = DAG.getConstant(0, PVT);
1101 Ops.assign(NumElements, Op);
1104 // Create a BUILD_VECTOR node.
1105 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1108 // If this is a static alloca, generate it as the frameindex instead of
1110 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1111 std::map<const AllocaInst*, int>::iterator SI =
1112 FuncInfo.StaticAllocaMap.find(AI);
1113 if (SI != FuncInfo.StaticAllocaMap.end())
1114 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1117 unsigned InReg = FuncInfo.ValueMap[V];
1118 assert(InReg && "Value not in map!");
1120 RegsForValue RFV(TLI, InReg, VTy);
1121 SDOperand Chain = DAG.getEntryNode();
1122 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1126 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1127 if (I.getNumOperands() == 0) {
1128 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1132 SmallVector<SDOperand, 8> NewValues;
1133 NewValues.push_back(getControlRoot());
1134 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1135 SDOperand RetOp = getValue(I.getOperand(i));
1136 MVT::ValueType VT = RetOp.getValueType();
1138 // FIXME: C calling convention requires the return type to be promoted to
1139 // at least 32-bit. But this is not necessary for non-C calling conventions.
1140 if (MVT::isInteger(VT)) {
1141 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1142 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1146 unsigned NumParts = TLI.getNumRegisters(VT);
1147 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1148 SmallVector<SDOperand, 4> Parts(NumParts);
1149 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1151 const Function *F = I.getParent()->getParent();
1152 if (F->paramHasAttr(0, ParamAttr::SExt))
1153 ExtendKind = ISD::SIGN_EXTEND;
1154 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1155 ExtendKind = ISD::ZERO_EXTEND;
1157 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1159 for (unsigned i = 0; i < NumParts; ++i) {
1160 NewValues.push_back(Parts[i]);
1161 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1164 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1165 &NewValues[0], NewValues.size()));
1168 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1169 /// the current basic block, add it to ValueMap now so that we'll get a
1171 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1172 // No need to export constants.
1173 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1175 // Already exported?
1176 if (FuncInfo.isExportedInst(V)) return;
1178 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1179 CopyValueToVirtualRegister(V, Reg);
1182 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1183 const BasicBlock *FromBB) {
1184 // The operands of the setcc have to be in this block. We don't know
1185 // how to export them from some other block.
1186 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1187 // Can export from current BB.
1188 if (VI->getParent() == FromBB)
1191 // Is already exported, noop.
1192 return FuncInfo.isExportedInst(V);
1195 // If this is an argument, we can export it if the BB is the entry block or
1196 // if it is already exported.
1197 if (isa<Argument>(V)) {
1198 if (FromBB == &FromBB->getParent()->getEntryBlock())
1201 // Otherwise, can only export this if it is already exported.
1202 return FuncInfo.isExportedInst(V);
1205 // Otherwise, constants can always be exported.
1209 static bool InBlock(const Value *V, const BasicBlock *BB) {
1210 if (const Instruction *I = dyn_cast<Instruction>(V))
1211 return I->getParent() == BB;
1215 /// FindMergedConditions - If Cond is an expression like
1216 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1217 MachineBasicBlock *TBB,
1218 MachineBasicBlock *FBB,
1219 MachineBasicBlock *CurBB,
1221 // If this node is not part of the or/and tree, emit it as a branch.
1222 Instruction *BOp = dyn_cast<Instruction>(Cond);
1224 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1225 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1226 BOp->getParent() != CurBB->getBasicBlock() ||
1227 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1228 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1229 const BasicBlock *BB = CurBB->getBasicBlock();
1231 // If the leaf of the tree is a comparison, merge the condition into
1233 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1234 // The operands of the cmp have to be in this block. We don't know
1235 // how to export them from some other block. If this is the first block
1236 // of the sequence, no exporting is needed.
1238 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1239 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1240 BOp = cast<Instruction>(Cond);
1241 ISD::CondCode Condition;
1242 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1243 switch (IC->getPredicate()) {
1244 default: assert(0 && "Unknown icmp predicate opcode!");
1245 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1246 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1247 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1248 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1249 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1250 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1251 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1252 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1253 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1254 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1256 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1257 ISD::CondCode FPC, FOC;
1258 switch (FC->getPredicate()) {
1259 default: assert(0 && "Unknown fcmp predicate opcode!");
1260 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1261 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1262 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1263 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1264 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1265 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1266 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1267 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1268 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1269 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1270 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1271 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1272 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1273 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1274 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1275 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1277 if (FiniteOnlyFPMath())
1282 Condition = ISD::SETEQ; // silence warning.
1283 assert(0 && "Unknown compare instruction");
1286 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1287 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1288 SwitchCases.push_back(CB);
1292 // Create a CaseBlock record representing this branch.
1293 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1294 NULL, TBB, FBB, CurBB);
1295 SwitchCases.push_back(CB);
1300 // Create TmpBB after CurBB.
1301 MachineFunction::iterator BBI = CurBB;
1302 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1303 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1305 if (Opc == Instruction::Or) {
1306 // Codegen X | Y as:
1314 // Emit the LHS condition.
1315 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1317 // Emit the RHS condition into TmpBB.
1318 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1320 assert(Opc == Instruction::And && "Unknown merge op!");
1321 // Codegen X & Y as:
1328 // This requires creation of TmpBB after CurBB.
1330 // Emit the LHS condition.
1331 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1333 // Emit the RHS condition into TmpBB.
1334 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1338 /// If the set of cases should be emitted as a series of branches, return true.
1339 /// If we should emit this as a bunch of and/or'd together conditions, return
1342 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1343 if (Cases.size() != 2) return true;
1345 // If this is two comparisons of the same values or'd or and'd together, they
1346 // will get folded into a single comparison, so don't emit two blocks.
1347 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1348 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1349 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1350 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1357 void SelectionDAGLowering::visitBr(BranchInst &I) {
1358 // Update machine-CFG edges.
1359 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1361 // Figure out which block is immediately after the current one.
1362 MachineBasicBlock *NextBlock = 0;
1363 MachineFunction::iterator BBI = CurMBB;
1364 if (++BBI != CurMBB->getParent()->end())
1367 if (I.isUnconditional()) {
1368 // If this is not a fall-through branch, emit the branch.
1369 if (Succ0MBB != NextBlock)
1370 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1371 DAG.getBasicBlock(Succ0MBB)));
1373 // Update machine-CFG edges.
1374 CurMBB->addSuccessor(Succ0MBB);
1378 // If this condition is one of the special cases we handle, do special stuff
1380 Value *CondVal = I.getCondition();
1381 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1383 // If this is a series of conditions that are or'd or and'd together, emit
1384 // this as a sequence of branches instead of setcc's with and/or operations.
1385 // For example, instead of something like:
1398 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1399 if (BOp->hasOneUse() &&
1400 (BOp->getOpcode() == Instruction::And ||
1401 BOp->getOpcode() == Instruction::Or)) {
1402 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1403 // If the compares in later blocks need to use values not currently
1404 // exported from this block, export them now. This block should always
1405 // be the first entry.
1406 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1408 // Allow some cases to be rejected.
1409 if (ShouldEmitAsBranches(SwitchCases)) {
1410 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1411 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1412 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1415 // Emit the branch for this block.
1416 visitSwitchCase(SwitchCases[0]);
1417 SwitchCases.erase(SwitchCases.begin());
1421 // Okay, we decided not to do this, remove any inserted MBB's and clear
1423 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1424 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1426 SwitchCases.clear();
1430 // Create a CaseBlock record representing this branch.
1431 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1432 NULL, Succ0MBB, Succ1MBB, CurMBB);
1433 // Use visitSwitchCase to actually insert the fast branch sequence for this
1435 visitSwitchCase(CB);
1438 /// visitSwitchCase - Emits the necessary code to represent a single node in
1439 /// the binary search tree resulting from lowering a switch instruction.
1440 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1442 SDOperand CondLHS = getValue(CB.CmpLHS);
1444 // Build the setcc now.
1445 if (CB.CmpMHS == NULL) {
1446 // Fold "(X == true)" to X and "(X == false)" to !X to
1447 // handle common cases produced by branch lowering.
1448 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1450 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1451 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1452 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1454 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1456 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1458 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1459 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1461 SDOperand CmpOp = getValue(CB.CmpMHS);
1462 MVT::ValueType VT = CmpOp.getValueType();
1464 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1465 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1467 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1468 Cond = DAG.getSetCC(MVT::i1, SUB,
1469 DAG.getConstant(High-Low, VT), ISD::SETULE);
1474 // Set NextBlock to be the MBB immediately after the current one, if any.
1475 // This is used to avoid emitting unnecessary branches to the next block.
1476 MachineBasicBlock *NextBlock = 0;
1477 MachineFunction::iterator BBI = CurMBB;
1478 if (++BBI != CurMBB->getParent()->end())
1481 // If the lhs block is the next block, invert the condition so that we can
1482 // fall through to the lhs instead of the rhs block.
1483 if (CB.TrueBB == NextBlock) {
1484 std::swap(CB.TrueBB, CB.FalseBB);
1485 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1486 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1488 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1489 DAG.getBasicBlock(CB.TrueBB));
1490 if (CB.FalseBB == NextBlock)
1491 DAG.setRoot(BrCond);
1493 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1494 DAG.getBasicBlock(CB.FalseBB)));
1495 // Update successor info
1496 CurMBB->addSuccessor(CB.TrueBB);
1497 CurMBB->addSuccessor(CB.FalseBB);
1500 /// visitJumpTable - Emit JumpTable node in the current MBB
1501 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1502 // Emit the code for the jump table
1503 assert(JT.Reg != -1U && "Should lower JT Header first!");
1504 MVT::ValueType PTy = TLI.getPointerTy();
1505 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1506 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1507 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1512 /// visitJumpTableHeader - This function emits necessary code to produce index
1513 /// in the JumpTable from switch case.
1514 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1515 SelectionDAGISel::JumpTableHeader &JTH) {
1516 // Subtract the lowest switch case value from the value being switched on
1517 // and conditional branch to default mbb if the result is greater than the
1518 // difference between smallest and largest cases.
1519 SDOperand SwitchOp = getValue(JTH.SValue);
1520 MVT::ValueType VT = SwitchOp.getValueType();
1521 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1522 DAG.getConstant(JTH.First, VT));
1524 // The SDNode we just created, which holds the value being switched on
1525 // minus the the smallest case value, needs to be copied to a virtual
1526 // register so it can be used as an index into the jump table in a
1527 // subsequent basic block. This value may be smaller or larger than the
1528 // target's pointer type, and therefore require extension or truncating.
1529 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1530 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1532 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1534 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1535 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1536 JT.Reg = JumpTableReg;
1538 // Emit the range check for the jump table, and branch to the default
1539 // block for the switch statement if the value being switched on exceeds
1540 // the largest case in the switch.
1541 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1542 DAG.getConstant(JTH.Last-JTH.First,VT),
1545 // Set NextBlock to be the MBB immediately after the current one, if any.
1546 // This is used to avoid emitting unnecessary branches to the next block.
1547 MachineBasicBlock *NextBlock = 0;
1548 MachineFunction::iterator BBI = CurMBB;
1549 if (++BBI != CurMBB->getParent()->end())
1552 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1553 DAG.getBasicBlock(JT.Default));
1555 if (JT.MBB == NextBlock)
1556 DAG.setRoot(BrCond);
1558 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1559 DAG.getBasicBlock(JT.MBB)));
1564 /// visitBitTestHeader - This function emits necessary code to produce value
1565 /// suitable for "bit tests"
1566 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1567 // Subtract the minimum value
1568 SDOperand SwitchOp = getValue(B.SValue);
1569 MVT::ValueType VT = SwitchOp.getValueType();
1570 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1571 DAG.getConstant(B.First, VT));
1574 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1575 DAG.getConstant(B.Range, VT),
1579 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1580 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1582 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1584 // Make desired shift
1585 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1586 DAG.getConstant(1, TLI.getPointerTy()),
1589 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1590 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1593 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1594 DAG.getBasicBlock(B.Default));
1596 // Set NextBlock to be the MBB immediately after the current one, if any.
1597 // This is used to avoid emitting unnecessary branches to the next block.
1598 MachineBasicBlock *NextBlock = 0;
1599 MachineFunction::iterator BBI = CurMBB;
1600 if (++BBI != CurMBB->getParent()->end())
1603 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1604 if (MBB == NextBlock)
1605 DAG.setRoot(BrRange);
1607 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1608 DAG.getBasicBlock(MBB)));
1610 CurMBB->addSuccessor(B.Default);
1611 CurMBB->addSuccessor(MBB);
1616 /// visitBitTestCase - this function produces one "bit test"
1617 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1619 SelectionDAGISel::BitTestCase &B) {
1620 // Emit bit tests and jumps
1621 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1623 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1625 DAG.getConstant(B.Mask,
1626 TLI.getPointerTy()));
1627 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1628 DAG.getConstant(0, TLI.getPointerTy()),
1630 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1631 AndCmp, DAG.getBasicBlock(B.TargetBB));
1633 // Set NextBlock to be the MBB immediately after the current one, if any.
1634 // This is used to avoid emitting unnecessary branches to the next block.
1635 MachineBasicBlock *NextBlock = 0;
1636 MachineFunction::iterator BBI = CurMBB;
1637 if (++BBI != CurMBB->getParent()->end())
1640 if (NextMBB == NextBlock)
1643 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1644 DAG.getBasicBlock(NextMBB)));
1646 CurMBB->addSuccessor(B.TargetBB);
1647 CurMBB->addSuccessor(NextMBB);
1652 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1653 // Retrieve successors.
1654 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1655 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1657 if (isa<InlineAsm>(I.getCalledValue()))
1660 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1662 // If the value of the invoke is used outside of its defining block, make it
1663 // available as a virtual register.
1664 if (!I.use_empty()) {
1665 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1666 if (VMI != FuncInfo.ValueMap.end())
1667 CopyValueToVirtualRegister(&I, VMI->second);
1670 // Drop into normal successor.
1671 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1672 DAG.getBasicBlock(Return)));
1674 // Update successor info
1675 CurMBB->addSuccessor(Return);
1676 CurMBB->addSuccessor(LandingPad);
1679 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1682 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1683 /// small case ranges).
1684 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1685 CaseRecVector& WorkList,
1687 MachineBasicBlock* Default) {
1688 Case& BackCase = *(CR.Range.second-1);
1690 // Size is the number of Cases represented by this range.
1691 unsigned Size = CR.Range.second - CR.Range.first;
1695 // Get the MachineFunction which holds the current MBB. This is used when
1696 // inserting any additional MBBs necessary to represent the switch.
1697 MachineFunction *CurMF = CurMBB->getParent();
1699 // Figure out which block is immediately after the current one.
1700 MachineBasicBlock *NextBlock = 0;
1701 MachineFunction::iterator BBI = CR.CaseBB;
1703 if (++BBI != CurMBB->getParent()->end())
1706 // TODO: If any two of the cases has the same destination, and if one value
1707 // is the same as the other, but has one bit unset that the other has set,
1708 // use bit manipulation to do two compares at once. For example:
1709 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1711 // Rearrange the case blocks so that the last one falls through if possible.
1712 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1713 // The last case block won't fall through into 'NextBlock' if we emit the
1714 // branches in this order. See if rearranging a case value would help.
1715 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1716 if (I->BB == NextBlock) {
1717 std::swap(*I, BackCase);
1723 // Create a CaseBlock record representing a conditional branch to
1724 // the Case's target mbb if the value being switched on SV is equal
1726 MachineBasicBlock *CurBlock = CR.CaseBB;
1727 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1728 MachineBasicBlock *FallThrough;
1730 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1731 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1733 // If the last case doesn't match, go to the default block.
1734 FallThrough = Default;
1737 Value *RHS, *LHS, *MHS;
1739 if (I->High == I->Low) {
1740 // This is just small small case range :) containing exactly 1 case
1742 LHS = SV; RHS = I->High; MHS = NULL;
1745 LHS = I->Low; MHS = SV; RHS = I->High;
1747 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1748 I->BB, FallThrough, CurBlock);
1750 // If emitting the first comparison, just call visitSwitchCase to emit the
1751 // code into the current block. Otherwise, push the CaseBlock onto the
1752 // vector to be later processed by SDISel, and insert the node's MBB
1753 // before the next MBB.
1754 if (CurBlock == CurMBB)
1755 visitSwitchCase(CB);
1757 SwitchCases.push_back(CB);
1759 CurBlock = FallThrough;
1765 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1766 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1767 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1770 /// handleJTSwitchCase - Emit jumptable for current switch case range
1771 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1772 CaseRecVector& WorkList,
1774 MachineBasicBlock* Default) {
1775 Case& FrontCase = *CR.Range.first;
1776 Case& BackCase = *(CR.Range.second-1);
1778 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1779 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1782 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1786 if (!areJTsAllowed(TLI) || TSize <= 3)
1789 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1793 DOUT << "Lowering jump table\n"
1794 << "First entry: " << First << ". Last entry: " << Last << "\n"
1795 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1797 // Get the MachineFunction which holds the current MBB. This is used when
1798 // inserting any additional MBBs necessary to represent the switch.
1799 MachineFunction *CurMF = CurMBB->getParent();
1801 // Figure out which block is immediately after the current one.
1802 MachineBasicBlock *NextBlock = 0;
1803 MachineFunction::iterator BBI = CR.CaseBB;
1805 if (++BBI != CurMBB->getParent()->end())
1808 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1810 // Create a new basic block to hold the code for loading the address
1811 // of the jump table, and jumping to it. Update successor information;
1812 // we will either branch to the default case for the switch, or the jump
1814 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1815 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1816 CR.CaseBB->addSuccessor(Default);
1817 CR.CaseBB->addSuccessor(JumpTableBB);
1819 // Build a vector of destination BBs, corresponding to each target
1820 // of the jump table. If the value of the jump table slot corresponds to
1821 // a case statement, push the case's BB onto the vector, otherwise, push
1823 std::vector<MachineBasicBlock*> DestBBs;
1824 int64_t TEI = First;
1825 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1826 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1827 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1829 if ((Low <= TEI) && (TEI <= High)) {
1830 DestBBs.push_back(I->BB);
1834 DestBBs.push_back(Default);
1838 // Update successor info. Add one edge to each unique successor.
1839 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1840 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1841 E = DestBBs.end(); I != E; ++I) {
1842 if (!SuccsHandled[(*I)->getNumber()]) {
1843 SuccsHandled[(*I)->getNumber()] = true;
1844 JumpTableBB->addSuccessor(*I);
1848 // Create a jump table index for this jump table, or return an existing
1850 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1852 // Set the jump table information so that we can codegen it as a second
1853 // MachineBasicBlock
1854 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1855 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1856 (CR.CaseBB == CurMBB));
1857 if (CR.CaseBB == CurMBB)
1858 visitJumpTableHeader(JT, JTH);
1860 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1865 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1867 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1868 CaseRecVector& WorkList,
1870 MachineBasicBlock* Default) {
1871 // Get the MachineFunction which holds the current MBB. This is used when
1872 // inserting any additional MBBs necessary to represent the switch.
1873 MachineFunction *CurMF = CurMBB->getParent();
1875 // Figure out which block is immediately after the current one.
1876 MachineBasicBlock *NextBlock = 0;
1877 MachineFunction::iterator BBI = CR.CaseBB;
1879 if (++BBI != CurMBB->getParent()->end())
1882 Case& FrontCase = *CR.Range.first;
1883 Case& BackCase = *(CR.Range.second-1);
1884 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1886 // Size is the number of Cases represented by this range.
1887 unsigned Size = CR.Range.second - CR.Range.first;
1889 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1890 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1892 CaseItr Pivot = CR.Range.first + Size/2;
1894 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1895 // (heuristically) allow us to emit JumpTable's later.
1897 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1901 uint64_t LSize = FrontCase.size();
1902 uint64_t RSize = TSize-LSize;
1903 DOUT << "Selecting best pivot: \n"
1904 << "First: " << First << ", Last: " << Last <<"\n"
1905 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1906 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1908 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1909 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1910 assert((RBegin-LEnd>=1) && "Invalid case distance");
1911 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1912 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1913 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1914 // Should always split in some non-trivial place
1916 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1917 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1918 << "Metric: " << Metric << "\n";
1919 if (FMetric < Metric) {
1922 DOUT << "Current metric set to: " << FMetric << "\n";
1928 if (areJTsAllowed(TLI)) {
1929 // If our case is dense we *really* should handle it earlier!
1930 assert((FMetric > 0) && "Should handle dense range earlier!");
1932 Pivot = CR.Range.first + Size/2;
1935 CaseRange LHSR(CR.Range.first, Pivot);
1936 CaseRange RHSR(Pivot, CR.Range.second);
1937 Constant *C = Pivot->Low;
1938 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1940 // We know that we branch to the LHS if the Value being switched on is
1941 // less than the Pivot value, C. We use this to optimize our binary
1942 // tree a bit, by recognizing that if SV is greater than or equal to the
1943 // LHS's Case Value, and that Case Value is exactly one less than the
1944 // Pivot's Value, then we can branch directly to the LHS's Target,
1945 // rather than creating a leaf node for it.
1946 if ((LHSR.second - LHSR.first) == 1 &&
1947 LHSR.first->High == CR.GE &&
1948 cast<ConstantInt>(C)->getSExtValue() ==
1949 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1950 TrueBB = LHSR.first->BB;
1952 TrueBB = new MachineBasicBlock(LLVMBB);
1953 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1954 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1957 // Similar to the optimization above, if the Value being switched on is
1958 // known to be less than the Constant CR.LT, and the current Case Value
1959 // is CR.LT - 1, then we can branch directly to the target block for
1960 // the current Case Value, rather than emitting a RHS leaf node for it.
1961 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1962 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1963 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1964 FalseBB = RHSR.first->BB;
1966 FalseBB = new MachineBasicBlock(LLVMBB);
1967 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1968 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1971 // Create a CaseBlock record representing a conditional branch to
1972 // the LHS node if the value being switched on SV is less than C.
1973 // Otherwise, branch to LHS.
1974 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1975 TrueBB, FalseBB, CR.CaseBB);
1977 if (CR.CaseBB == CurMBB)
1978 visitSwitchCase(CB);
1980 SwitchCases.push_back(CB);
1985 /// handleBitTestsSwitchCase - if current case range has few destination and
1986 /// range span less, than machine word bitwidth, encode case range into series
1987 /// of masks and emit bit tests with these masks.
1988 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1989 CaseRecVector& WorkList,
1991 MachineBasicBlock* Default){
1992 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1994 Case& FrontCase = *CR.Range.first;
1995 Case& BackCase = *(CR.Range.second-1);
1997 // Get the MachineFunction which holds the current MBB. This is used when
1998 // inserting any additional MBBs necessary to represent the switch.
1999 MachineFunction *CurMF = CurMBB->getParent();
2001 unsigned numCmps = 0;
2002 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2004 // Single case counts one, case range - two.
2005 if (I->Low == I->High)
2011 // Count unique destinations
2012 SmallSet<MachineBasicBlock*, 4> Dests;
2013 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2014 Dests.insert(I->BB);
2015 if (Dests.size() > 3)
2016 // Don't bother the code below, if there are too much unique destinations
2019 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2020 << "Total number of comparisons: " << numCmps << "\n";
2022 // Compute span of values.
2023 Constant* minValue = FrontCase.Low;
2024 Constant* maxValue = BackCase.High;
2025 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2026 cast<ConstantInt>(minValue)->getSExtValue();
2027 DOUT << "Compare range: " << range << "\n"
2028 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2029 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2031 if (range>=IntPtrBits ||
2032 (!(Dests.size() == 1 && numCmps >= 3) &&
2033 !(Dests.size() == 2 && numCmps >= 5) &&
2034 !(Dests.size() >= 3 && numCmps >= 6)))
2037 DOUT << "Emitting bit tests\n";
2038 int64_t lowBound = 0;
2040 // Optimize the case where all the case values fit in a
2041 // word without having to subtract minValue. In this case,
2042 // we can optimize away the subtraction.
2043 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2044 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2045 range = cast<ConstantInt>(maxValue)->getSExtValue();
2047 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2050 CaseBitsVector CasesBits;
2051 unsigned i, count = 0;
2053 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2054 MachineBasicBlock* Dest = I->BB;
2055 for (i = 0; i < count; ++i)
2056 if (Dest == CasesBits[i].BB)
2060 assert((count < 3) && "Too much destinations to test!");
2061 CasesBits.push_back(CaseBits(0, Dest, 0));
2065 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2066 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2068 for (uint64_t j = lo; j <= hi; j++) {
2069 CasesBits[i].Mask |= 1ULL << j;
2070 CasesBits[i].Bits++;
2074 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2076 SelectionDAGISel::BitTestInfo BTC;
2078 // Figure out which block is immediately after the current one.
2079 MachineFunction::iterator BBI = CR.CaseBB;
2082 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2085 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2086 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2087 << ", BB: " << CasesBits[i].BB << "\n";
2089 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2090 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2091 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2096 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2097 -1U, (CR.CaseBB == CurMBB),
2098 CR.CaseBB, Default, BTC);
2100 if (CR.CaseBB == CurMBB)
2101 visitBitTestHeader(BTB);
2103 BitTestCases.push_back(BTB);
2109 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2110 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2111 const SwitchInst& SI) {
2112 unsigned numCmps = 0;
2114 // Start with "simple" cases
2115 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2116 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2117 Cases.push_back(Case(SI.getSuccessorValue(i),
2118 SI.getSuccessorValue(i),
2121 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2123 // Merge case into clusters
2124 if (Cases.size()>=2)
2125 // Must recompute end() each iteration because it may be
2126 // invalidated by erase if we hold on to it
2127 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2128 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2129 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2130 MachineBasicBlock* nextBB = J->BB;
2131 MachineBasicBlock* currentBB = I->BB;
2133 // If the two neighboring cases go to the same destination, merge them
2134 // into a single case.
2135 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2143 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2144 if (I->Low != I->High)
2145 // A range counts double, since it requires two compares.
2152 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2153 // Figure out which block is immediately after the current one.
2154 MachineBasicBlock *NextBlock = 0;
2155 MachineFunction::iterator BBI = CurMBB;
2157 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2159 // If there is only the default destination, branch to it if it is not the
2160 // next basic block. Otherwise, just fall through.
2161 if (SI.getNumOperands() == 2) {
2162 // Update machine-CFG edges.
2164 // If this is not a fall-through branch, emit the branch.
2165 if (Default != NextBlock)
2166 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2167 DAG.getBasicBlock(Default)));
2169 CurMBB->addSuccessor(Default);
2173 // If there are any non-default case statements, create a vector of Cases
2174 // representing each one, and sort the vector so that we can efficiently
2175 // create a binary search tree from them.
2177 unsigned numCmps = Clusterify(Cases, SI);
2178 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2179 << ". Total compares: " << numCmps << "\n";
2181 // Get the Value to be switched on and default basic blocks, which will be
2182 // inserted into CaseBlock records, representing basic blocks in the binary
2184 Value *SV = SI.getOperand(0);
2186 // Push the initial CaseRec onto the worklist
2187 CaseRecVector WorkList;
2188 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2190 while (!WorkList.empty()) {
2191 // Grab a record representing a case range to process off the worklist
2192 CaseRec CR = WorkList.back();
2193 WorkList.pop_back();
2195 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2198 // If the range has few cases (two or less) emit a series of specific
2200 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2203 // If the switch has more than 5 blocks, and at least 40% dense, and the
2204 // target supports indirect branches, then emit a jump table rather than
2205 // lowering the switch to a binary tree of conditional branches.
2206 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2209 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2210 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2211 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2216 void SelectionDAGLowering::visitSub(User &I) {
2217 // -0.0 - X --> fneg
2218 const Type *Ty = I.getType();
2219 if (isa<VectorType>(Ty)) {
2220 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2221 const VectorType *DestTy = cast<VectorType>(I.getType());
2222 const Type *ElTy = DestTy->getElementType();
2223 if (ElTy->isFloatingPoint()) {
2224 unsigned VL = DestTy->getNumElements();
2225 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2226 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2228 SDOperand Op2 = getValue(I.getOperand(1));
2229 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2235 if (Ty->isFloatingPoint()) {
2236 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2237 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2238 SDOperand Op2 = getValue(I.getOperand(1));
2239 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2244 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2247 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2248 SDOperand Op1 = getValue(I.getOperand(0));
2249 SDOperand Op2 = getValue(I.getOperand(1));
2251 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2254 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2255 SDOperand Op1 = getValue(I.getOperand(0));
2256 SDOperand Op2 = getValue(I.getOperand(1));
2258 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2259 MVT::getSizeInBits(Op2.getValueType()))
2260 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2261 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2262 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2264 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2267 void SelectionDAGLowering::visitICmp(User &I) {
2268 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2269 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2270 predicate = IC->getPredicate();
2271 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2272 predicate = ICmpInst::Predicate(IC->getPredicate());
2273 SDOperand Op1 = getValue(I.getOperand(0));
2274 SDOperand Op2 = getValue(I.getOperand(1));
2275 ISD::CondCode Opcode;
2276 switch (predicate) {
2277 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2278 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2279 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2280 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2281 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2282 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2283 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2284 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2285 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2286 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2288 assert(!"Invalid ICmp predicate value");
2289 Opcode = ISD::SETEQ;
2292 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2295 void SelectionDAGLowering::visitFCmp(User &I) {
2296 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2297 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2298 predicate = FC->getPredicate();
2299 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2300 predicate = FCmpInst::Predicate(FC->getPredicate());
2301 SDOperand Op1 = getValue(I.getOperand(0));
2302 SDOperand Op2 = getValue(I.getOperand(1));
2303 ISD::CondCode Condition, FOC, FPC;
2304 switch (predicate) {
2305 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2306 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2307 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2308 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2309 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2310 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2311 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2312 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2313 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2314 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2315 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2316 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2317 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2318 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2319 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2320 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2322 assert(!"Invalid FCmp predicate value");
2323 FOC = FPC = ISD::SETFALSE;
2326 if (FiniteOnlyFPMath())
2330 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2333 void SelectionDAGLowering::visitSelect(User &I) {
2334 SDOperand Cond = getValue(I.getOperand(0));
2335 SDOperand TrueVal = getValue(I.getOperand(1));
2336 SDOperand FalseVal = getValue(I.getOperand(2));
2337 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2338 TrueVal, FalseVal));
2342 void SelectionDAGLowering::visitTrunc(User &I) {
2343 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2344 SDOperand N = getValue(I.getOperand(0));
2345 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2346 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2349 void SelectionDAGLowering::visitZExt(User &I) {
2350 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2351 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2352 SDOperand N = getValue(I.getOperand(0));
2353 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2354 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2357 void SelectionDAGLowering::visitSExt(User &I) {
2358 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2359 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2360 SDOperand N = getValue(I.getOperand(0));
2361 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2362 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2365 void SelectionDAGLowering::visitFPTrunc(User &I) {
2366 // FPTrunc is never a no-op cast, no need to check
2367 SDOperand N = getValue(I.getOperand(0));
2368 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2369 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2372 void SelectionDAGLowering::visitFPExt(User &I){
2373 // FPTrunc is never a no-op cast, no need to check
2374 SDOperand N = getValue(I.getOperand(0));
2375 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2376 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2379 void SelectionDAGLowering::visitFPToUI(User &I) {
2380 // FPToUI is never a no-op cast, no need to check
2381 SDOperand N = getValue(I.getOperand(0));
2382 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2383 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2386 void SelectionDAGLowering::visitFPToSI(User &I) {
2387 // FPToSI is never a no-op cast, no need to check
2388 SDOperand N = getValue(I.getOperand(0));
2389 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2390 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2393 void SelectionDAGLowering::visitUIToFP(User &I) {
2394 // UIToFP is never a no-op cast, no need to check
2395 SDOperand N = getValue(I.getOperand(0));
2396 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2397 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2400 void SelectionDAGLowering::visitSIToFP(User &I){
2401 // UIToFP is never a no-op cast, no need to check
2402 SDOperand N = getValue(I.getOperand(0));
2403 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2404 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2407 void SelectionDAGLowering::visitPtrToInt(User &I) {
2408 // What to do depends on the size of the integer and the size of the pointer.
2409 // We can either truncate, zero extend, or no-op, accordingly.
2410 SDOperand N = getValue(I.getOperand(0));
2411 MVT::ValueType SrcVT = N.getValueType();
2412 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2414 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2415 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2417 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2418 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2419 setValue(&I, Result);
2422 void SelectionDAGLowering::visitIntToPtr(User &I) {
2423 // What to do depends on the size of the integer and the size of the pointer.
2424 // We can either truncate, zero extend, or no-op, accordingly.
2425 SDOperand N = getValue(I.getOperand(0));
2426 MVT::ValueType SrcVT = N.getValueType();
2427 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2428 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2429 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2431 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2432 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2435 void SelectionDAGLowering::visitBitCast(User &I) {
2436 SDOperand N = getValue(I.getOperand(0));
2437 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2439 // BitCast assures us that source and destination are the same size so this
2440 // is either a BIT_CONVERT or a no-op.
2441 if (DestVT != N.getValueType())
2442 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2444 setValue(&I, N); // noop cast.
2447 void SelectionDAGLowering::visitInsertElement(User &I) {
2448 SDOperand InVec = getValue(I.getOperand(0));
2449 SDOperand InVal = getValue(I.getOperand(1));
2450 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2451 getValue(I.getOperand(2)));
2453 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2454 TLI.getValueType(I.getType()),
2455 InVec, InVal, InIdx));
2458 void SelectionDAGLowering::visitExtractElement(User &I) {
2459 SDOperand InVec = getValue(I.getOperand(0));
2460 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2461 getValue(I.getOperand(1)));
2462 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2463 TLI.getValueType(I.getType()), InVec, InIdx));
2466 void SelectionDAGLowering::visitShuffleVector(User &I) {
2467 SDOperand V1 = getValue(I.getOperand(0));
2468 SDOperand V2 = getValue(I.getOperand(1));
2469 SDOperand Mask = getValue(I.getOperand(2));
2471 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2472 TLI.getValueType(I.getType()),
2477 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2478 SDOperand N = getValue(I.getOperand(0));
2479 const Type *Ty = I.getOperand(0)->getType();
2481 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2484 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2485 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2488 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2489 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2490 DAG.getIntPtrConstant(Offset));
2492 Ty = StTy->getElementType(Field);
2494 Ty = cast<SequentialType>(Ty)->getElementType();
2496 // If this is a constant subscript, handle it quickly.
2497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2498 if (CI->getZExtValue() == 0) continue;
2500 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2501 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2502 DAG.getIntPtrConstant(Offs));
2506 // N = N + Idx * ElementSize;
2507 uint64_t ElementSize = TD->getABITypeSize(Ty);
2508 SDOperand IdxN = getValue(Idx);
2510 // If the index is smaller or larger than intptr_t, truncate or extend
2512 if (IdxN.getValueType() < N.getValueType()) {
2513 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2514 } else if (IdxN.getValueType() > N.getValueType())
2515 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2517 // If this is a multiply by a power of two, turn it into a shl
2518 // immediately. This is a very common case.
2519 if (isPowerOf2_64(ElementSize)) {
2520 unsigned Amt = Log2_64(ElementSize);
2521 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2522 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2523 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2527 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2528 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2529 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2535 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2536 // If this is a fixed sized alloca in the entry block of the function,
2537 // allocate it statically on the stack.
2538 if (FuncInfo.StaticAllocaMap.count(&I))
2539 return; // getValue will auto-populate this.
2541 const Type *Ty = I.getAllocatedType();
2542 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2544 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2547 SDOperand AllocSize = getValue(I.getArraySize());
2548 MVT::ValueType IntPtr = TLI.getPointerTy();
2549 if (IntPtr < AllocSize.getValueType())
2550 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2551 else if (IntPtr > AllocSize.getValueType())
2552 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2554 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2555 DAG.getIntPtrConstant(TySize));
2557 // Handle alignment. If the requested alignment is less than or equal to
2558 // the stack alignment, ignore it. If the size is greater than or equal to
2559 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2560 unsigned StackAlign =
2561 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2562 if (Align <= StackAlign)
2565 // Round the size of the allocation up to the stack alignment size
2566 // by add SA-1 to the size.
2567 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2568 DAG.getIntPtrConstant(StackAlign-1));
2569 // Mask out the low bits for alignment purposes.
2570 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2571 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2573 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2574 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2576 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2578 DAG.setRoot(DSA.getValue(1));
2580 // Inform the Frame Information that we have just allocated a variable-sized
2582 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2585 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2586 SDOperand Ptr = getValue(I.getOperand(0));
2592 // Do not serialize non-volatile loads against each other.
2593 Root = DAG.getRoot();
2596 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2597 Root, I.isVolatile(), I.getAlignment()));
2600 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2601 const Value *SV, SDOperand Root,
2603 unsigned Alignment) {
2605 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2606 isVolatile, Alignment);
2609 DAG.setRoot(L.getValue(1));
2611 PendingLoads.push_back(L.getValue(1));
2617 void SelectionDAGLowering::visitStore(StoreInst &I) {
2618 Value *SrcV = I.getOperand(0);
2619 SDOperand Src = getValue(SrcV);
2620 SDOperand Ptr = getValue(I.getOperand(1));
2621 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2622 I.isVolatile(), I.getAlignment()));
2625 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2627 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2628 unsigned Intrinsic) {
2629 bool HasChain = !I.doesNotAccessMemory();
2630 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2632 // Build the operand list.
2633 SmallVector<SDOperand, 8> Ops;
2634 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2636 // We don't need to serialize loads against other loads.
2637 Ops.push_back(DAG.getRoot());
2639 Ops.push_back(getRoot());
2643 // Add the intrinsic ID as an integer operand.
2644 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2646 // Add all operands of the call to the operand list.
2647 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2648 SDOperand Op = getValue(I.getOperand(i));
2649 assert(TLI.isTypeLegal(Op.getValueType()) &&
2650 "Intrinsic uses a non-legal type?");
2654 std::vector<MVT::ValueType> VTs;
2655 if (I.getType() != Type::VoidTy) {
2656 MVT::ValueType VT = TLI.getValueType(I.getType());
2657 if (MVT::isVector(VT)) {
2658 const VectorType *DestTy = cast<VectorType>(I.getType());
2659 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2661 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2662 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2665 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2669 VTs.push_back(MVT::Other);
2671 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2676 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2677 &Ops[0], Ops.size());
2678 else if (I.getType() != Type::VoidTy)
2679 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2680 &Ops[0], Ops.size());
2682 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2683 &Ops[0], Ops.size());
2686 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2688 PendingLoads.push_back(Chain);
2692 if (I.getType() != Type::VoidTy) {
2693 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2694 MVT::ValueType VT = TLI.getValueType(PTy);
2695 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2697 setValue(&I, Result);
2701 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2702 static GlobalVariable *ExtractTypeInfo (Value *V) {
2703 V = IntrinsicInst::StripPointerCasts(V);
2704 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2705 assert ((GV || isa<ConstantPointerNull>(V)) &&
2706 "TypeInfo must be a global variable or NULL");
2710 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2711 /// call, and add them to the specified machine basic block.
2712 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2713 MachineBasicBlock *MBB) {
2714 // Inform the MachineModuleInfo of the personality for this landing pad.
2715 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2716 assert(CE->getOpcode() == Instruction::BitCast &&
2717 isa<Function>(CE->getOperand(0)) &&
2718 "Personality should be a function");
2719 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2721 // Gather all the type infos for this landing pad and pass them along to
2722 // MachineModuleInfo.
2723 std::vector<GlobalVariable *> TyInfo;
2724 unsigned N = I.getNumOperands();
2726 for (unsigned i = N - 1; i > 2; --i) {
2727 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2728 unsigned FilterLength = CI->getZExtValue();
2729 unsigned FirstCatch = i + FilterLength + !FilterLength;
2730 assert (FirstCatch <= N && "Invalid filter length");
2732 if (FirstCatch < N) {
2733 TyInfo.reserve(N - FirstCatch);
2734 for (unsigned j = FirstCatch; j < N; ++j)
2735 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2736 MMI->addCatchTypeInfo(MBB, TyInfo);
2740 if (!FilterLength) {
2742 MMI->addCleanup(MBB);
2745 TyInfo.reserve(FilterLength - 1);
2746 for (unsigned j = i + 1; j < FirstCatch; ++j)
2747 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2748 MMI->addFilterTypeInfo(MBB, TyInfo);
2757 TyInfo.reserve(N - 3);
2758 for (unsigned j = 3; j < N; ++j)
2759 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2760 MMI->addCatchTypeInfo(MBB, TyInfo);
2764 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2765 /// we want to emit this as a call to a named external function, return the name
2766 /// otherwise lower it and return null.
2768 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2769 switch (Intrinsic) {
2771 // By default, turn this into a target intrinsic node.
2772 visitTargetIntrinsic(I, Intrinsic);
2774 case Intrinsic::vastart: visitVAStart(I); return 0;
2775 case Intrinsic::vaend: visitVAEnd(I); return 0;
2776 case Intrinsic::vacopy: visitVACopy(I); return 0;
2777 case Intrinsic::returnaddress:
2778 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2779 getValue(I.getOperand(1))));
2781 case Intrinsic::frameaddress:
2782 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2783 getValue(I.getOperand(1))));
2785 case Intrinsic::setjmp:
2786 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2788 case Intrinsic::longjmp:
2789 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2791 case Intrinsic::memcpy_i32:
2792 case Intrinsic::memcpy_i64: {
2793 SDOperand Op1 = getValue(I.getOperand(1));
2794 SDOperand Op2 = getValue(I.getOperand(2));
2795 SDOperand Op3 = getValue(I.getOperand(3));
2796 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2797 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2798 I.getOperand(1), 0, I.getOperand(2), 0));
2801 case Intrinsic::memset_i32:
2802 case Intrinsic::memset_i64: {
2803 SDOperand Op1 = getValue(I.getOperand(1));
2804 SDOperand Op2 = getValue(I.getOperand(2));
2805 SDOperand Op3 = getValue(I.getOperand(3));
2806 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2807 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2808 I.getOperand(1), 0));
2811 case Intrinsic::memmove_i32:
2812 case Intrinsic::memmove_i64: {
2813 SDOperand Op1 = getValue(I.getOperand(1));
2814 SDOperand Op2 = getValue(I.getOperand(2));
2815 SDOperand Op3 = getValue(I.getOperand(3));
2816 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2818 // If the source and destination are known to not be aliases, we can
2819 // lower memmove as memcpy.
2820 uint64_t Size = -1ULL;
2821 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2822 Size = C->getValue();
2823 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2824 AliasAnalysis::NoAlias) {
2825 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2826 I.getOperand(1), 0, I.getOperand(2), 0));
2830 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2831 I.getOperand(1), 0, I.getOperand(2), 0));
2834 case Intrinsic::dbg_stoppoint: {
2835 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2836 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2837 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2841 Ops[1] = getValue(SPI.getLineValue());
2842 Ops[2] = getValue(SPI.getColumnValue());
2844 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2845 assert(DD && "Not a debug information descriptor");
2846 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2848 Ops[3] = DAG.getString(CompileUnit->getFileName());
2849 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2851 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2856 case Intrinsic::dbg_region_start: {
2857 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2858 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2859 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2860 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2861 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2862 DAG.getConstant(LabelID, MVT::i32),
2863 DAG.getConstant(0, MVT::i32)));
2868 case Intrinsic::dbg_region_end: {
2869 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2870 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2871 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2872 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2873 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2874 DAG.getConstant(LabelID, MVT::i32),
2875 DAG.getConstant(0, MVT::i32)));
2880 case Intrinsic::dbg_func_start: {
2881 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2883 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2884 Value *SP = FSI.getSubprogram();
2885 if (SP && MMI->Verify(SP)) {
2886 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2887 // what (most?) gdb expects.
2888 DebugInfoDesc *DD = MMI->getDescFor(SP);
2889 assert(DD && "Not a debug information descriptor");
2890 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2891 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2892 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2893 CompileUnit->getFileName());
2894 // Record the source line but does create a label. It will be emitted
2895 // at asm emission time.
2896 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2901 case Intrinsic::dbg_declare: {
2902 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2903 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2904 Value *Variable = DI.getVariable();
2905 if (MMI && Variable && MMI->Verify(Variable))
2906 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2907 getValue(DI.getAddress()), getValue(Variable)));
2911 case Intrinsic::eh_exception: {
2912 if (!CurMBB->isLandingPad()) {
2913 // FIXME: Mark exception register as live in. Hack for PR1508.
2914 unsigned Reg = TLI.getExceptionAddressRegister();
2915 if (Reg) CurMBB->addLiveIn(Reg);
2917 // Insert the EXCEPTIONADDR instruction.
2918 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2920 Ops[0] = DAG.getRoot();
2921 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2923 DAG.setRoot(Op.getValue(1));
2927 case Intrinsic::eh_selector_i32:
2928 case Intrinsic::eh_selector_i64: {
2929 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2930 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2931 MVT::i32 : MVT::i64);
2934 if (CurMBB->isLandingPad())
2935 addCatchInfo(I, MMI, CurMBB);
2938 FuncInfo.CatchInfoLost.insert(&I);
2940 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2941 unsigned Reg = TLI.getExceptionSelectorRegister();
2942 if (Reg) CurMBB->addLiveIn(Reg);
2945 // Insert the EHSELECTION instruction.
2946 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2948 Ops[0] = getValue(I.getOperand(1));
2950 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2952 DAG.setRoot(Op.getValue(1));
2954 setValue(&I, DAG.getConstant(0, VT));
2960 case Intrinsic::eh_typeid_for_i32:
2961 case Intrinsic::eh_typeid_for_i64: {
2962 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2963 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2964 MVT::i32 : MVT::i64);
2967 // Find the type id for the given typeinfo.
2968 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2970 unsigned TypeID = MMI->getTypeIDFor(GV);
2971 setValue(&I, DAG.getConstant(TypeID, VT));
2973 // Return something different to eh_selector.
2974 setValue(&I, DAG.getConstant(1, VT));
2980 case Intrinsic::eh_return: {
2981 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2984 MMI->setCallsEHReturn(true);
2985 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2988 getValue(I.getOperand(1)),
2989 getValue(I.getOperand(2))));
2991 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2997 case Intrinsic::eh_unwind_init: {
2998 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2999 MMI->setCallsUnwindInit(true);
3005 case Intrinsic::eh_dwarf_cfa: {
3006 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3008 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3009 CfaArg = DAG.getNode(ISD::TRUNCATE,
3010 TLI.getPointerTy(), getValue(I.getOperand(1)));
3012 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3013 TLI.getPointerTy(), getValue(I.getOperand(1)));
3015 SDOperand Offset = DAG.getNode(ISD::ADD,
3017 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3018 TLI.getPointerTy()),
3020 setValue(&I, DAG.getNode(ISD::ADD,
3022 DAG.getNode(ISD::FRAMEADDR,
3025 TLI.getPointerTy())),
3030 case Intrinsic::sqrt:
3031 setValue(&I, DAG.getNode(ISD::FSQRT,
3032 getValue(I.getOperand(1)).getValueType(),
3033 getValue(I.getOperand(1))));
3035 case Intrinsic::powi:
3036 setValue(&I, DAG.getNode(ISD::FPOWI,
3037 getValue(I.getOperand(1)).getValueType(),
3038 getValue(I.getOperand(1)),
3039 getValue(I.getOperand(2))));
3041 case Intrinsic::sin:
3042 setValue(&I, DAG.getNode(ISD::FSIN,
3043 getValue(I.getOperand(1)).getValueType(),
3044 getValue(I.getOperand(1))));
3046 case Intrinsic::cos:
3047 setValue(&I, DAG.getNode(ISD::FCOS,
3048 getValue(I.getOperand(1)).getValueType(),
3049 getValue(I.getOperand(1))));
3051 case Intrinsic::pow:
3052 setValue(&I, DAG.getNode(ISD::FPOW,
3053 getValue(I.getOperand(1)).getValueType(),
3054 getValue(I.getOperand(1)),
3055 getValue(I.getOperand(2))));
3057 case Intrinsic::pcmarker: {
3058 SDOperand Tmp = getValue(I.getOperand(1));
3059 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3062 case Intrinsic::readcyclecounter: {
3063 SDOperand Op = getRoot();
3064 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3065 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3068 DAG.setRoot(Tmp.getValue(1));
3071 case Intrinsic::part_select: {
3072 // Currently not implemented: just abort
3073 assert(0 && "part_select intrinsic not implemented");
3076 case Intrinsic::part_set: {
3077 // Currently not implemented: just abort
3078 assert(0 && "part_set intrinsic not implemented");
3081 case Intrinsic::bswap:
3082 setValue(&I, DAG.getNode(ISD::BSWAP,
3083 getValue(I.getOperand(1)).getValueType(),
3084 getValue(I.getOperand(1))));
3086 case Intrinsic::cttz: {
3087 SDOperand Arg = getValue(I.getOperand(1));
3088 MVT::ValueType Ty = Arg.getValueType();
3089 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3090 setValue(&I, result);
3093 case Intrinsic::ctlz: {
3094 SDOperand Arg = getValue(I.getOperand(1));
3095 MVT::ValueType Ty = Arg.getValueType();
3096 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3097 setValue(&I, result);
3100 case Intrinsic::ctpop: {
3101 SDOperand Arg = getValue(I.getOperand(1));
3102 MVT::ValueType Ty = Arg.getValueType();
3103 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3104 setValue(&I, result);
3107 case Intrinsic::stacksave: {
3108 SDOperand Op = getRoot();
3109 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3110 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3112 DAG.setRoot(Tmp.getValue(1));
3115 case Intrinsic::stackrestore: {
3116 SDOperand Tmp = getValue(I.getOperand(1));
3117 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3120 case Intrinsic::var_annotation:
3121 // Discard annotate attributes
3124 case Intrinsic::init_trampoline: {
3126 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3130 Ops[1] = getValue(I.getOperand(1));
3131 Ops[2] = getValue(I.getOperand(2));
3132 Ops[3] = getValue(I.getOperand(3));
3133 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3134 Ops[5] = DAG.getSrcValue(F);
3136 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3137 DAG.getNodeValueTypes(TLI.getPointerTy(),
3142 DAG.setRoot(Tmp.getValue(1));
3146 case Intrinsic::gcroot:
3148 Value *Alloca = I.getOperand(1);
3149 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3151 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3152 GCI->addStackRoot(FI->getIndex(), TypeMap);
3156 case Intrinsic::gcread:
3157 case Intrinsic::gcwrite:
3158 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3161 case Intrinsic::flt_rounds: {
3162 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3166 case Intrinsic::trap: {
3167 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3170 case Intrinsic::prefetch: {
3173 Ops[1] = getValue(I.getOperand(1));
3174 Ops[2] = getValue(I.getOperand(2));
3175 Ops[3] = getValue(I.getOperand(3));
3176 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3180 case Intrinsic::memory_barrier: {
3183 for (int x = 1; x < 6; ++x)
3184 Ops[x] = getValue(I.getOperand(x));
3186 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3189 case Intrinsic::atomic_lcs: {
3190 SDOperand Root = getRoot();
3191 SDOperand O3 = getValue(I.getOperand(3));
3192 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3193 getValue(I.getOperand(1)),
3194 getValue(I.getOperand(2)),
3195 O3, O3.getValueType());
3197 DAG.setRoot(L.getValue(1));
3200 case Intrinsic::atomic_las: {
3201 SDOperand Root = getRoot();
3202 SDOperand O2 = getValue(I.getOperand(2));
3203 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3204 getValue(I.getOperand(1)),
3205 O2, O2.getValueType());
3207 DAG.setRoot(L.getValue(1));
3210 case Intrinsic::atomic_swap: {
3211 SDOperand Root = getRoot();
3212 SDOperand O2 = getValue(I.getOperand(2));
3213 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3214 getValue(I.getOperand(1)),
3215 O2, O2.getValueType());
3217 DAG.setRoot(L.getValue(1));
3225 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3227 MachineBasicBlock *LandingPad) {
3228 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3229 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3230 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3231 unsigned BeginLabel = 0, EndLabel = 0;
3233 TargetLowering::ArgListTy Args;
3234 TargetLowering::ArgListEntry Entry;
3235 Args.reserve(CS.arg_size());
3236 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3238 SDOperand ArgNode = getValue(*i);
3239 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3241 unsigned attrInd = i - CS.arg_begin() + 1;
3242 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3243 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3244 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3245 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3246 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3247 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3248 Entry.Alignment = CS.getParamAlignment(attrInd);
3249 Args.push_back(Entry);
3252 if (LandingPad && MMI) {
3253 // Insert a label before the invoke call to mark the try range. This can be
3254 // used to detect deletion of the invoke via the MachineModuleInfo.
3255 BeginLabel = MMI->NextLabelID();
3256 // Both PendingLoads and PendingExports must be flushed here;
3257 // this call might not return.
3259 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3260 DAG.getConstant(BeginLabel, MVT::i32),
3261 DAG.getConstant(1, MVT::i32)));
3264 std::pair<SDOperand,SDOperand> Result =
3265 TLI.LowerCallTo(getRoot(), CS.getType(),
3266 CS.paramHasAttr(0, ParamAttr::SExt),
3267 CS.paramHasAttr(0, ParamAttr::ZExt),
3268 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3270 if (CS.getType() != Type::VoidTy)
3271 setValue(CS.getInstruction(), Result.first);
3272 DAG.setRoot(Result.second);
3274 if (LandingPad && MMI) {
3275 // Insert a label at the end of the invoke call to mark the try range. This
3276 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3277 EndLabel = MMI->NextLabelID();
3278 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3279 DAG.getConstant(EndLabel, MVT::i32),
3280 DAG.getConstant(1, MVT::i32)));
3282 // Inform MachineModuleInfo of range.
3283 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3288 void SelectionDAGLowering::visitCall(CallInst &I) {
3289 const char *RenameFn = 0;
3290 if (Function *F = I.getCalledFunction()) {
3291 if (F->isDeclaration()) {
3292 if (unsigned IID = F->getIntrinsicID()) {
3293 RenameFn = visitIntrinsicCall(I, IID);
3299 // Check for well-known libc/libm calls. If the function is internal, it
3300 // can't be a library call.
3301 unsigned NameLen = F->getNameLen();
3302 if (!F->hasInternalLinkage() && NameLen) {
3303 const char *NameStr = F->getNameStart();
3304 if (NameStr[0] == 'c' &&
3305 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3306 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3307 if (I.getNumOperands() == 3 && // Basic sanity checks.
3308 I.getOperand(1)->getType()->isFloatingPoint() &&
3309 I.getType() == I.getOperand(1)->getType() &&
3310 I.getType() == I.getOperand(2)->getType()) {
3311 SDOperand LHS = getValue(I.getOperand(1));
3312 SDOperand RHS = getValue(I.getOperand(2));
3313 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3317 } else if (NameStr[0] == 'f' &&
3318 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3319 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3320 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3321 if (I.getNumOperands() == 2 && // Basic sanity checks.
3322 I.getOperand(1)->getType()->isFloatingPoint() &&
3323 I.getType() == I.getOperand(1)->getType()) {
3324 SDOperand Tmp = getValue(I.getOperand(1));
3325 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3328 } else if (NameStr[0] == 's' &&
3329 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3330 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3331 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3332 if (I.getNumOperands() == 2 && // Basic sanity checks.
3333 I.getOperand(1)->getType()->isFloatingPoint() &&
3334 I.getType() == I.getOperand(1)->getType()) {
3335 SDOperand Tmp = getValue(I.getOperand(1));
3336 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3339 } else if (NameStr[0] == 'c' &&
3340 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3341 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3342 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3343 if (I.getNumOperands() == 2 && // Basic sanity checks.
3344 I.getOperand(1)->getType()->isFloatingPoint() &&
3345 I.getType() == I.getOperand(1)->getType()) {
3346 SDOperand Tmp = getValue(I.getOperand(1));
3347 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3352 } else if (isa<InlineAsm>(I.getOperand(0))) {
3359 Callee = getValue(I.getOperand(0));
3361 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3363 LowerCallTo(&I, Callee, I.isTailCall());
3367 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3368 if (isa<UndefValue>(I.getOperand(0))) {
3369 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3370 setValue(&I, Undef);
3372 SDOperand Call = getValue(I.getOperand(0));
3374 // To add support for individual return values with aggregate types,
3375 // we'd need a way to take a getresult index and determine which
3376 // values of the Call SDNode are associated with it.
3377 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3378 "Individual return values must not be aggregates!");
3380 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3385 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3386 /// this value and returns the result as a ValueVT value. This uses
3387 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3388 /// If the Flag pointer is NULL, no flag is used.
3389 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3390 SDOperand &Chain, SDOperand *Flag)const{
3391 // Assemble the legal parts into the final values.
3392 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3393 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3394 // Copy the legal parts from the registers.
3395 MVT::ValueType ValueVT = ValueVTs[Value];
3396 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3397 MVT::ValueType RegisterVT = RegVTs[Value];
3399 SmallVector<SDOperand, 8> Parts(NumRegs);
3400 for (unsigned i = 0; i != NumRegs; ++i) {
3401 SDOperand P = Flag ?
3402 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag) :
3403 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3404 Chain = P.getValue(1);
3406 *Flag = P.getValue(2);
3410 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3414 return DAG.getNode(ISD::MERGE_VALUES,
3415 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3416 &Values[0], ValueVTs.size());
3419 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3420 /// specified value into the registers specified by this object. This uses
3421 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3422 /// If the Flag pointer is NULL, no flag is used.
3423 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3424 SDOperand &Chain, SDOperand *Flag) const {
3425 // Get the list of the values's legal parts.
3426 unsigned NumRegs = Regs.size();
3427 SmallVector<SDOperand, 8> Parts(NumRegs);
3428 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3429 MVT::ValueType ValueVT = ValueVTs[Value];
3430 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3431 MVT::ValueType RegisterVT = RegVTs[Value];
3433 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3434 &Parts[Part], NumParts, RegisterVT);
3438 // Copy the parts into the registers.
3439 SmallVector<SDOperand, 8> Chains(NumRegs);
3440 for (unsigned i = 0; i != NumRegs; ++i) {
3441 SDOperand Part = Flag ?
3442 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3443 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3444 Chains[i] = Part.getValue(0);
3446 *Flag = Part.getValue(1);
3448 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3451 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3452 /// operand list. This adds the code marker and includes the number of
3453 /// values added into it.
3454 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3455 std::vector<SDOperand> &Ops) const {
3456 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3457 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3458 for (unsigned Value = 0, Reg = 0; Value != ValueVTs.size(); ++Value) {
3459 MVT::ValueType ValueVT = ValueVTs[Value];
3460 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3461 MVT::ValueType RegisterVT = RegVTs[Value];
3462 for (unsigned i = 0; i != NumRegs; ++i) {
3463 SDOperand RegOp = DAG.getRegister(Regs[Reg+i], RegisterVT);
3464 Ops.push_back(RegOp);
3470 /// isAllocatableRegister - If the specified register is safe to allocate,
3471 /// i.e. it isn't a stack pointer or some other special register, return the
3472 /// register class for the register. Otherwise, return null.
3473 static const TargetRegisterClass *
3474 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3475 const TargetLowering &TLI,
3476 const TargetRegisterInfo *TRI) {
3477 MVT::ValueType FoundVT = MVT::Other;
3478 const TargetRegisterClass *FoundRC = 0;
3479 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3480 E = TRI->regclass_end(); RCI != E; ++RCI) {
3481 MVT::ValueType ThisVT = MVT::Other;
3483 const TargetRegisterClass *RC = *RCI;
3484 // If none of the the value types for this register class are valid, we
3485 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3486 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3488 if (TLI.isTypeLegal(*I)) {
3489 // If we have already found this register in a different register class,
3490 // choose the one with the largest VT specified. For example, on
3491 // PowerPC, we favor f64 register classes over f32.
3492 if (FoundVT == MVT::Other ||
3493 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3500 if (ThisVT == MVT::Other) continue;
3502 // NOTE: This isn't ideal. In particular, this might allocate the
3503 // frame pointer in functions that need it (due to them not being taken
3504 // out of allocation, because a variable sized allocation hasn't been seen
3505 // yet). This is a slight code pessimization, but should still work.
3506 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3507 E = RC->allocation_order_end(MF); I != E; ++I)
3509 // We found a matching register class. Keep looking at others in case
3510 // we find one with larger registers that this physreg is also in.
3521 /// AsmOperandInfo - This contains information for each constraint that we are
3523 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3524 /// CallOperand - If this is the result output operand or a clobber
3525 /// this is null, otherwise it is the incoming operand to the CallInst.
3526 /// This gets modified as the asm is processed.
3527 SDOperand CallOperand;
3529 /// AssignedRegs - If this is a register or register class operand, this
3530 /// contains the set of register corresponding to the operand.
3531 RegsForValue AssignedRegs;
3533 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3534 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3537 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3538 /// busy in OutputRegs/InputRegs.
3539 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3540 std::set<unsigned> &OutputRegs,
3541 std::set<unsigned> &InputRegs,
3542 const TargetRegisterInfo &TRI) const {
3544 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3545 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3548 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3549 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3554 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3556 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3557 const TargetRegisterInfo &TRI) {
3558 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3560 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3561 for (; *Aliases; ++Aliases)
3562 Regs.insert(*Aliases);
3565 } // end anon namespace.
3568 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3569 /// specified operand. We prefer to assign virtual registers, to allow the
3570 /// register allocator handle the assignment process. However, if the asm uses
3571 /// features that we can't model on machineinstrs, we have SDISel do the
3572 /// allocation. This produces generally horrible, but correct, code.
3574 /// OpInfo describes the operand.
3575 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3576 /// or any explicitly clobbered registers.
3577 /// Input and OutputRegs are the set of already allocated physical registers.
3579 void SelectionDAGLowering::
3580 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3581 std::set<unsigned> &OutputRegs,
3582 std::set<unsigned> &InputRegs) {
3583 // Compute whether this value requires an input register, an output register,
3585 bool isOutReg = false;
3586 bool isInReg = false;
3587 switch (OpInfo.Type) {
3588 case InlineAsm::isOutput:
3591 // If this is an early-clobber output, or if there is an input
3592 // constraint that matches this, we need to reserve the input register
3593 // so no other inputs allocate to it.
3594 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3596 case InlineAsm::isInput:
3600 case InlineAsm::isClobber:
3607 MachineFunction &MF = DAG.getMachineFunction();
3608 SmallVector<unsigned, 4> Regs;
3610 // If this is a constraint for a single physreg, or a constraint for a
3611 // register class, find it.
3612 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3613 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3614 OpInfo.ConstraintVT);
3616 unsigned NumRegs = 1;
3617 if (OpInfo.ConstraintVT != MVT::Other)
3618 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3619 MVT::ValueType RegVT;
3620 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3623 // If this is a constraint for a specific physical register, like {r17},
3625 if (PhysReg.first) {
3626 if (OpInfo.ConstraintVT == MVT::Other)
3627 ValueVT = *PhysReg.second->vt_begin();
3629 // Get the actual register value type. This is important, because the user
3630 // may have asked for (e.g.) the AX register in i32 type. We need to
3631 // remember that AX is actually i16 to get the right extension.
3632 RegVT = *PhysReg.second->vt_begin();
3634 // This is a explicit reference to a physical register.
3635 Regs.push_back(PhysReg.first);
3637 // If this is an expanded reference, add the rest of the regs to Regs.
3639 TargetRegisterClass::iterator I = PhysReg.second->begin();
3640 TargetRegisterClass::iterator E = PhysReg.second->end();
3641 for (; *I != PhysReg.first; ++I)
3642 assert(I != E && "Didn't find reg!");
3644 // Already added the first reg.
3646 for (; NumRegs; --NumRegs, ++I) {
3647 assert(I != E && "Ran out of registers to allocate!");
3651 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3652 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3653 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3657 // Otherwise, if this was a reference to an LLVM register class, create vregs
3658 // for this reference.
3659 std::vector<unsigned> RegClassRegs;
3660 const TargetRegisterClass *RC = PhysReg.second;
3662 // If this is an early clobber or tied register, our regalloc doesn't know
3663 // how to maintain the constraint. If it isn't, go ahead and create vreg
3664 // and let the regalloc do the right thing.
3665 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3666 // If there is some other early clobber and this is an input register,
3667 // then we are forced to pre-allocate the input reg so it doesn't
3668 // conflict with the earlyclobber.
3669 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3670 RegVT = *PhysReg.second->vt_begin();
3672 if (OpInfo.ConstraintVT == MVT::Other)
3675 // Create the appropriate number of virtual registers.
3676 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3677 for (; NumRegs; --NumRegs)
3678 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3680 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3684 // Otherwise, we can't allocate it. Let the code below figure out how to
3685 // maintain these constraints.
3686 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3689 // This is a reference to a register class that doesn't directly correspond
3690 // to an LLVM register class. Allocate NumRegs consecutive, available,
3691 // registers from the class.
3692 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3693 OpInfo.ConstraintVT);
3696 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3697 unsigned NumAllocated = 0;
3698 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3699 unsigned Reg = RegClassRegs[i];
3700 // See if this register is available.
3701 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3702 (isInReg && InputRegs.count(Reg))) { // Already used.
3703 // Make sure we find consecutive registers.
3708 // Check to see if this register is allocatable (i.e. don't give out the
3711 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3712 if (!RC) { // Couldn't allocate this register.
3713 // Reset NumAllocated to make sure we return consecutive registers.
3719 // Okay, this register is good, we can use it.
3722 // If we allocated enough consecutive registers, succeed.
3723 if (NumAllocated == NumRegs) {
3724 unsigned RegStart = (i-NumAllocated)+1;
3725 unsigned RegEnd = i+1;
3726 // Mark all of the allocated registers used.
3727 for (unsigned i = RegStart; i != RegEnd; ++i)
3728 Regs.push_back(RegClassRegs[i]);
3730 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
3731 OpInfo.ConstraintVT);
3732 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3737 // Otherwise, we couldn't allocate enough registers for this.
3742 /// visitInlineAsm - Handle a call to an InlineAsm object.
3744 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3745 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3747 /// ConstraintOperands - Information about all of the constraints.
3748 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3750 SDOperand Chain = getRoot();
3753 std::set<unsigned> OutputRegs, InputRegs;
3755 // Do a prepass over the constraints, canonicalizing them, and building up the
3756 // ConstraintOperands list.
3757 std::vector<InlineAsm::ConstraintInfo>
3758 ConstraintInfos = IA->ParseConstraints();
3760 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3761 // constraint. If so, we can't let the register allocator allocate any input
3762 // registers, because it will not know to avoid the earlyclobbered output reg.
3763 bool SawEarlyClobber = false;
3765 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3766 unsigned ResNo = 0; // ResNo - The result number of the next output.
3767 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3768 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3769 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3771 MVT::ValueType OpVT = MVT::Other;
3773 // Compute the value type for each operand.
3774 switch (OpInfo.Type) {
3775 case InlineAsm::isOutput:
3776 // Indirect outputs just consume an argument.
3777 if (OpInfo.isIndirect) {
3778 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3781 // The return value of the call is this value. As such, there is no
3782 // corresponding argument.
3783 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3784 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3785 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3787 assert(ResNo == 0 && "Asm only has one result!");
3788 OpVT = TLI.getValueType(CS.getType());
3792 case InlineAsm::isInput:
3793 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3795 case InlineAsm::isClobber:
3800 // If this is an input or an indirect output, process the call argument.
3801 // BasicBlocks are labels, currently appearing only in asm's.
3802 if (OpInfo.CallOperandVal) {
3803 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3804 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3806 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3807 const Type *OpTy = OpInfo.CallOperandVal->getType();
3808 // If this is an indirect operand, the operand is a pointer to the
3810 if (OpInfo.isIndirect)
3811 OpTy = cast<PointerType>(OpTy)->getElementType();
3813 // If OpTy is not a first-class value, it may be a struct/union that we
3814 // can tile with integers.
3815 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3816 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3824 OpTy = IntegerType::get(BitSize);
3829 OpVT = TLI.getValueType(OpTy, true);
3833 OpInfo.ConstraintVT = OpVT;
3835 // Compute the constraint code and ConstraintType to use.
3836 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
3838 // Keep track of whether we see an earlyclobber.
3839 SawEarlyClobber |= OpInfo.isEarlyClobber;
3841 // If we see a clobber of a register, it is an early clobber.
3842 if (!SawEarlyClobber &&
3843 OpInfo.Type == InlineAsm::isClobber &&
3844 OpInfo.ConstraintType == TargetLowering::C_Register) {
3845 // Note that we want to ignore things that we don't trick here, like
3846 // dirflag, fpsr, flags, etc.
3847 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3848 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3849 OpInfo.ConstraintVT);
3850 if (PhysReg.first || PhysReg.second) {
3851 // This is a register we know of.
3852 SawEarlyClobber = true;
3856 // If this is a memory input, and if the operand is not indirect, do what we
3857 // need to to provide an address for the memory input.
3858 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3859 !OpInfo.isIndirect) {
3860 assert(OpInfo.Type == InlineAsm::isInput &&
3861 "Can only indirectify direct input operands!");
3863 // Memory operands really want the address of the value. If we don't have
3864 // an indirect input, put it in the constpool if we can, otherwise spill
3865 // it to a stack slot.
3867 // If the operand is a float, integer, or vector constant, spill to a
3868 // constant pool entry to get its address.
3869 Value *OpVal = OpInfo.CallOperandVal;
3870 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3871 isa<ConstantVector>(OpVal)) {
3872 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3873 TLI.getPointerTy());
3875 // Otherwise, create a stack slot and emit a store to it before the
3877 const Type *Ty = OpVal->getType();
3878 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3879 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3880 MachineFunction &MF = DAG.getMachineFunction();
3881 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3882 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3883 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3884 OpInfo.CallOperand = StackSlot;
3887 // There is no longer a Value* corresponding to this operand.
3888 OpInfo.CallOperandVal = 0;
3889 // It is now an indirect operand.
3890 OpInfo.isIndirect = true;
3893 // If this constraint is for a specific register, allocate it before
3895 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3896 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3898 ConstraintInfos.clear();
3901 // Second pass - Loop over all of the operands, assigning virtual or physregs
3902 // to registerclass operands.
3903 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3904 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3906 // C_Register operands have already been allocated, Other/Memory don't need
3908 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3909 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3912 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3913 std::vector<SDOperand> AsmNodeOperands;
3914 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3915 AsmNodeOperands.push_back(
3916 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3919 // Loop over all of the inputs, copying the operand values into the
3920 // appropriate registers and processing the output regs.
3921 RegsForValue RetValRegs;
3923 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3924 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3926 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3927 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3929 switch (OpInfo.Type) {
3930 case InlineAsm::isOutput: {
3931 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3932 OpInfo.ConstraintType != TargetLowering::C_Register) {
3933 // Memory output, or 'other' output (e.g. 'X' constraint).
3934 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3936 // Add information to the INLINEASM node to know about this output.
3937 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3938 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3939 TLI.getPointerTy()));
3940 AsmNodeOperands.push_back(OpInfo.CallOperand);
3944 // Otherwise, this is a register or register class output.
3946 // Copy the output from the appropriate register. Find a register that
3948 if (OpInfo.AssignedRegs.Regs.empty()) {
3949 cerr << "Couldn't allocate output reg for contraint '"
3950 << OpInfo.ConstraintCode << "'!\n";
3954 if (!OpInfo.isIndirect) {
3955 // This is the result value of the call.
3956 assert(RetValRegs.Regs.empty() &&
3957 "Cannot have multiple output constraints yet!");
3958 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3959 RetValRegs = OpInfo.AssignedRegs;
3961 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3962 OpInfo.CallOperandVal));
3965 // Add information to the INLINEASM node to know that this register is
3967 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3971 case InlineAsm::isInput: {
3972 SDOperand InOperandVal = OpInfo.CallOperand;
3974 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3975 // If this is required to match an output register we have already set,
3976 // just use its register.
3977 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3979 // Scan until we find the definition we already emitted of this operand.
3980 // When we find it, create a RegsForValue operand.
3981 unsigned CurOp = 2; // The first operand.
3982 for (; OperandNo; --OperandNo) {
3983 // Advance to the next operand.
3985 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3986 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3987 (NumOps & 7) == 4 /*MEM*/) &&
3988 "Skipped past definitions?");
3989 CurOp += (NumOps>>3)+1;
3993 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3994 if ((NumOps & 7) == 2 /*REGDEF*/) {
3995 // Add NumOps>>3 registers to MatchedRegs.
3996 RegsForValue MatchedRegs;
3997 MatchedRegs.TLI = &TLI;
3998 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
3999 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
4000 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4002 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4003 MatchedRegs.Regs.push_back(Reg);
4006 // Use the produced MatchedRegs object to
4007 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4008 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4011 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4012 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4013 // Add information to the INLINEASM node to know about this input.
4014 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4015 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4016 TLI.getPointerTy()));
4017 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4022 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4023 assert(!OpInfo.isIndirect &&
4024 "Don't know how to handle indirect other inputs yet!");
4026 std::vector<SDOperand> Ops;
4027 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4030 cerr << "Invalid operand for inline asm constraint '"
4031 << OpInfo.ConstraintCode << "'!\n";
4035 // Add information to the INLINEASM node to know about this input.
4036 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4037 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4038 TLI.getPointerTy()));
4039 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4041 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4042 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4043 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4044 "Memory operands expect pointer values");
4046 // Add information to the INLINEASM node to know about this input.
4047 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4048 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4049 TLI.getPointerTy()));
4050 AsmNodeOperands.push_back(InOperandVal);
4054 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4055 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4056 "Unknown constraint type!");
4057 assert(!OpInfo.isIndirect &&
4058 "Don't know how to handle indirect register inputs yet!");
4060 // Copy the input into the appropriate registers.
4061 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4062 "Couldn't allocate input reg!");
4064 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4066 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4070 case InlineAsm::isClobber: {
4071 // Add the clobbered value to the operand list, so that the register
4072 // allocator is aware that the physreg got clobbered.
4073 if (!OpInfo.AssignedRegs.Regs.empty())
4074 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4081 // Finish up input operands.
4082 AsmNodeOperands[0] = Chain;
4083 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4085 Chain = DAG.getNode(ISD::INLINEASM,
4086 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4087 &AsmNodeOperands[0], AsmNodeOperands.size());
4088 Flag = Chain.getValue(1);
4090 // If this asm returns a register value, copy the result from that register
4091 // and set it as the value of the call.
4092 if (!RetValRegs.Regs.empty()) {
4093 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4095 // If the result of the inline asm is a vector, it may have the wrong
4096 // width/num elts. Make sure to convert it to the right type with
4098 if (MVT::isVector(Val.getValueType())) {
4099 const VectorType *VTy = cast<VectorType>(CS.getType());
4100 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
4102 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
4105 setValue(CS.getInstruction(), Val);
4108 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4110 // Process indirect outputs, first output all of the flagged copies out of
4112 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4113 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4114 Value *Ptr = IndirectStoresToEmit[i].second;
4115 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4116 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4119 // Emit the non-flagged stores from the physregs.
4120 SmallVector<SDOperand, 8> OutChains;
4121 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4122 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4123 getValue(StoresToEmit[i].second),
4124 StoresToEmit[i].second, 0));
4125 if (!OutChains.empty())
4126 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4127 &OutChains[0], OutChains.size());
4132 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4133 SDOperand Src = getValue(I.getOperand(0));
4135 MVT::ValueType IntPtr = TLI.getPointerTy();
4137 if (IntPtr < Src.getValueType())
4138 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4139 else if (IntPtr > Src.getValueType())
4140 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4142 // Scale the source by the type size.
4143 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4144 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4145 Src, DAG.getIntPtrConstant(ElementSize));
4147 TargetLowering::ArgListTy Args;
4148 TargetLowering::ArgListEntry Entry;
4150 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4151 Args.push_back(Entry);
4153 std::pair<SDOperand,SDOperand> Result =
4154 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4155 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4156 setValue(&I, Result.first); // Pointers always fit in registers
4157 DAG.setRoot(Result.second);
4160 void SelectionDAGLowering::visitFree(FreeInst &I) {
4161 TargetLowering::ArgListTy Args;
4162 TargetLowering::ArgListEntry Entry;
4163 Entry.Node = getValue(I.getOperand(0));
4164 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4165 Args.push_back(Entry);
4166 MVT::ValueType IntPtr = TLI.getPointerTy();
4167 std::pair<SDOperand,SDOperand> Result =
4168 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4169 CallingConv::C, true,
4170 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4171 DAG.setRoot(Result.second);
4174 // EmitInstrWithCustomInserter - This method should be implemented by targets
4175 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4176 // instructions are special in various ways, which require special support to
4177 // insert. The specified MachineInstr is created but not inserted into any
4178 // basic blocks, and the scheduler passes ownership of it to this method.
4179 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4180 MachineBasicBlock *MBB) {
4181 cerr << "If a target marks an instruction with "
4182 << "'usesCustomDAGSchedInserter', it must implement "
4183 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4188 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4189 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4190 getValue(I.getOperand(1)),
4191 DAG.getSrcValue(I.getOperand(1))));
4194 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4195 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4196 getValue(I.getOperand(0)),
4197 DAG.getSrcValue(I.getOperand(0)));
4199 DAG.setRoot(V.getValue(1));
4202 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4203 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4204 getValue(I.getOperand(1)),
4205 DAG.getSrcValue(I.getOperand(1))));
4208 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4209 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4210 getValue(I.getOperand(1)),
4211 getValue(I.getOperand(2)),
4212 DAG.getSrcValue(I.getOperand(1)),
4213 DAG.getSrcValue(I.getOperand(2))));
4216 /// TargetLowering::LowerArguments - This is the default LowerArguments
4217 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4218 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4219 /// integrated into SDISel.
4220 std::vector<SDOperand>
4221 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4222 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4223 std::vector<SDOperand> Ops;
4224 Ops.push_back(DAG.getRoot());
4225 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4226 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4228 // Add one result value for each formal argument.
4229 std::vector<MVT::ValueType> RetVals;
4231 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4233 MVT::ValueType VT = getValueType(I->getType());
4234 ISD::ArgFlagsTy Flags;
4235 unsigned OriginalAlignment =
4236 getTargetData()->getABITypeAlignment(I->getType());
4238 if (F.paramHasAttr(j, ParamAttr::ZExt))
4240 if (F.paramHasAttr(j, ParamAttr::SExt))
4242 if (F.paramHasAttr(j, ParamAttr::InReg))
4244 if (F.paramHasAttr(j, ParamAttr::StructRet))
4246 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4248 const PointerType *Ty = cast<PointerType>(I->getType());
4249 const Type *ElementTy = Ty->getElementType();
4250 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4251 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4252 // For ByVal, alignment should be passed from FE. BE will guess if
4253 // this info is not there but there are cases it cannot get right.
4254 if (F.getParamAlignment(j))
4255 FrameAlign = F.getParamAlignment(j);
4256 Flags.setByValAlign(FrameAlign);
4257 Flags.setByValSize(FrameSize);
4259 if (F.paramHasAttr(j, ParamAttr::Nest))
4261 Flags.setOrigAlign(OriginalAlignment);
4263 MVT::ValueType RegisterVT = getRegisterType(VT);
4264 unsigned NumRegs = getNumRegisters(VT);
4265 for (unsigned i = 0; i != NumRegs; ++i) {
4266 RetVals.push_back(RegisterVT);
4267 ISD::ArgFlagsTy MyFlags = Flags;
4268 if (NumRegs > 1 && i == 0)
4270 // if it isn't first piece, alignment must be 1
4272 MyFlags.setOrigAlign(1);
4273 Ops.push_back(DAG.getArgFlags(MyFlags));
4277 RetVals.push_back(MVT::Other);
4280 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4281 DAG.getVTList(&RetVals[0], RetVals.size()),
4282 &Ops[0], Ops.size()).Val;
4284 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4285 // allows exposing the loads that may be part of the argument access to the
4286 // first DAGCombiner pass.
4287 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4289 // The number of results should match up, except that the lowered one may have
4290 // an extra flag result.
4291 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4292 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4293 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4294 && "Lowering produced unexpected number of results!");
4295 Result = TmpRes.Val;
4297 unsigned NumArgRegs = Result->getNumValues() - 1;
4298 DAG.setRoot(SDOperand(Result, NumArgRegs));
4300 // Set up the return result vector.
4304 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4306 MVT::ValueType VT = getValueType(I->getType());
4307 MVT::ValueType PartVT = getRegisterType(VT);
4309 unsigned NumParts = getNumRegisters(VT);
4310 SmallVector<SDOperand, 4> Parts(NumParts);
4311 for (unsigned j = 0; j != NumParts; ++j)
4312 Parts[j] = SDOperand(Result, i++);
4314 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4315 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4316 AssertOp = ISD::AssertSext;
4317 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4318 AssertOp = ISD::AssertZext;
4320 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4323 assert(i == NumArgRegs && "Argument register count mismatch!");
4328 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4329 /// implementation, which just inserts an ISD::CALL node, which is later custom
4330 /// lowered by the target to something concrete. FIXME: When all targets are
4331 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4332 std::pair<SDOperand, SDOperand>
4333 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4334 bool RetSExt, bool RetZExt, bool isVarArg,
4335 unsigned CallingConv, bool isTailCall,
4337 ArgListTy &Args, SelectionDAG &DAG) {
4338 SmallVector<SDOperand, 32> Ops;
4339 Ops.push_back(Chain); // Op#0 - Chain
4340 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4341 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4342 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4343 Ops.push_back(Callee);
4345 // Handle all of the outgoing arguments.
4346 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4347 MVT::ValueType VT = getValueType(Args[i].Ty);
4348 SDOperand Op = Args[i].Node;
4349 ISD::ArgFlagsTy Flags;
4350 unsigned OriginalAlignment =
4351 getTargetData()->getABITypeAlignment(Args[i].Ty);
4357 if (Args[i].isInReg)
4361 if (Args[i].isByVal) {
4363 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4364 const Type *ElementTy = Ty->getElementType();
4365 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4366 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4367 // For ByVal, alignment should come from FE. BE will guess if this
4368 // info is not there but there are cases it cannot get right.
4369 if (Args[i].Alignment)
4370 FrameAlign = Args[i].Alignment;
4371 Flags.setByValAlign(FrameAlign);
4372 Flags.setByValSize(FrameSize);
4376 Flags.setOrigAlign(OriginalAlignment);
4378 MVT::ValueType PartVT = getRegisterType(VT);
4379 unsigned NumParts = getNumRegisters(VT);
4380 SmallVector<SDOperand, 4> Parts(NumParts);
4381 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4384 ExtendKind = ISD::SIGN_EXTEND;
4385 else if (Args[i].isZExt)
4386 ExtendKind = ISD::ZERO_EXTEND;
4388 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4390 for (unsigned i = 0; i != NumParts; ++i) {
4391 // if it isn't first piece, alignment must be 1
4392 ISD::ArgFlagsTy MyFlags = Flags;
4393 if (NumParts > 1 && i == 0)
4396 MyFlags.setOrigAlign(1);
4398 Ops.push_back(Parts[i]);
4399 Ops.push_back(DAG.getArgFlags(MyFlags));
4403 // Figure out the result value types. We start by making a list of
4404 // the potentially illegal return value types.
4405 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4406 SmallVector<MVT::ValueType, 4> RetTys;
4407 ComputeValueVTs(*this, RetTy, RetTys);
4409 // Then we translate that to a list of legal types.
4410 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4411 MVT::ValueType VT = RetTys[I];
4412 MVT::ValueType RegisterVT = getRegisterType(VT);
4413 unsigned NumRegs = getNumRegisters(VT);
4414 for (unsigned i = 0; i != NumRegs; ++i)
4415 LoweredRetTys.push_back(RegisterVT);
4418 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4420 // Create the CALL node.
4421 SDOperand Res = DAG.getNode(ISD::CALL,
4422 DAG.getVTList(&LoweredRetTys[0],
4423 LoweredRetTys.size()),
4424 &Ops[0], Ops.size());
4425 Chain = Res.getValue(LoweredRetTys.size() - 1);
4427 // Gather up the call result into a single value.
4428 if (RetTy != Type::VoidTy) {
4429 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4432 AssertOp = ISD::AssertSext;
4434 AssertOp = ISD::AssertZext;
4436 SmallVector<SDOperand, 4> ReturnValues;
4438 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4439 MVT::ValueType VT = RetTys[I];
4440 MVT::ValueType RegisterVT = getRegisterType(VT);
4441 unsigned NumRegs = getNumRegisters(VT);
4442 unsigned RegNoEnd = NumRegs + RegNo;
4443 SmallVector<SDOperand, 4> Results;
4444 for (; RegNo != RegNoEnd; ++RegNo)
4445 Results.push_back(Res.getValue(RegNo));
4446 SDOperand ReturnValue =
4447 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4449 ReturnValues.push_back(ReturnValue);
4451 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4452 DAG.getNode(ISD::MERGE_VALUES,
4453 DAG.getVTList(&RetTys[0], RetTys.size()),
4454 &ReturnValues[0], ReturnValues.size());
4457 return std::make_pair(Res, Chain);
4460 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4461 assert(0 && "LowerOperation not implemented for this target!");
4466 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4467 SelectionDAG &DAG) {
4468 assert(0 && "CustomPromoteOperation not implemented for this target!");
4473 //===----------------------------------------------------------------------===//
4474 // SelectionDAGISel code
4475 //===----------------------------------------------------------------------===//
4477 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4478 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4481 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4482 AU.addRequired<AliasAnalysis>();
4483 AU.addRequired<CollectorModuleMetadata>();
4484 AU.setPreservesAll();
4489 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4490 // Get alias analysis for load/store combining.
4491 AA = &getAnalysis<AliasAnalysis>();
4493 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4494 if (MF.getFunction()->hasCollector())
4495 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4498 RegInfo = &MF.getRegInfo();
4499 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4501 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4503 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4504 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4505 // Mark landing pad.
4506 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4508 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4509 SelectBasicBlock(I, MF, FuncInfo);
4511 // Add function live-ins to entry block live-in set.
4512 BasicBlock *EntryBB = &Fn.getEntryBlock();
4513 BB = FuncInfo.MBBMap[EntryBB];
4514 if (!RegInfo->livein_empty())
4515 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4516 E = RegInfo->livein_end(); I != E; ++I)
4517 BB->addLiveIn(I->first);
4520 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4521 "Not all catch info was assigned to a landing pad!");
4527 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4529 SDOperand Op = getValue(V);
4530 assert((Op.getOpcode() != ISD::CopyFromReg ||
4531 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4532 "Copy from a reg to the same reg!");
4533 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4535 RegsForValue RFV(TLI, Reg, V->getType());
4536 SDOperand Chain = DAG.getEntryNode();
4537 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4538 PendingExports.push_back(Chain);
4541 void SelectionDAGISel::
4542 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4543 // If this is the entry block, emit arguments.
4544 Function &F = *LLVMBB->getParent();
4545 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4546 SDOperand OldRoot = SDL.DAG.getRoot();
4547 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4550 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4552 if (!AI->use_empty()) {
4553 SDL.setValue(AI, Args[a]);
4555 // If this argument is live outside of the entry block, insert a copy from
4556 // whereever we got it to the vreg that other BB's will reference it as.
4557 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4558 if (VMI != FuncInfo.ValueMap.end()) {
4559 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4563 // Finally, if the target has anything special to do, allow it to do so.
4564 // FIXME: this should insert code into the DAG!
4565 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4568 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4569 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4570 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4571 if (isSelector(I)) {
4572 // Apply the catch info to DestBB.
4573 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4575 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4576 FLI.CatchInfoFound.insert(I);
4581 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4582 /// DAG and fixes their tailcall attribute operand.
4583 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4584 TargetLowering& TLI) {
4585 SDNode * Ret = NULL;
4586 SDOperand Terminator = DAG.getRoot();
4589 if (Terminator.getOpcode() == ISD::RET) {
4590 Ret = Terminator.Val;
4593 // Fix tail call attribute of CALL nodes.
4594 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4595 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4596 if (BI->getOpcode() == ISD::CALL) {
4597 SDOperand OpRet(Ret, 0);
4598 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4599 bool isMarkedTailCall =
4600 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4601 // If CALL node has tail call attribute set to true and the call is not
4602 // eligible (no RET or the target rejects) the attribute is fixed to
4603 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4604 // must correctly identify tail call optimizable calls.
4605 if (isMarkedTailCall &&
4607 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4608 SmallVector<SDOperand, 32> Ops;
4610 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4611 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4615 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4617 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4623 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4624 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4625 FunctionLoweringInfo &FuncInfo) {
4626 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
4628 // Lower any arguments needed in this block if this is the entry block.
4629 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4630 LowerArguments(LLVMBB, SDL);
4632 BB = FuncInfo.MBBMap[LLVMBB];
4633 SDL.setCurrentBasicBlock(BB);
4635 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4637 if (MMI && BB->isLandingPad()) {
4638 // Add a label to mark the beginning of the landing pad. Deletion of the
4639 // landing pad can thus be detected via the MachineModuleInfo.
4640 unsigned LabelID = MMI->addLandingPad(BB);
4641 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4642 DAG.getConstant(LabelID, MVT::i32),
4643 DAG.getConstant(1, MVT::i32)));
4645 // Mark exception register as live in.
4646 unsigned Reg = TLI.getExceptionAddressRegister();
4647 if (Reg) BB->addLiveIn(Reg);
4649 // Mark exception selector register as live in.
4650 Reg = TLI.getExceptionSelectorRegister();
4651 if (Reg) BB->addLiveIn(Reg);
4653 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4654 // function and list of typeids logically belong to the invoke (or, if you
4655 // like, the basic block containing the invoke), and need to be associated
4656 // with it in the dwarf exception handling tables. Currently however the
4657 // information is provided by an intrinsic (eh.selector) that can be moved
4658 // to unexpected places by the optimizers: if the unwind edge is critical,
4659 // then breaking it can result in the intrinsics being in the successor of
4660 // the landing pad, not the landing pad itself. This results in exceptions
4661 // not being caught because no typeids are associated with the invoke.
4662 // This may not be the only way things can go wrong, but it is the only way
4663 // we try to work around for the moment.
4664 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4666 if (Br && Br->isUnconditional()) { // Critical edge?
4667 BasicBlock::iterator I, E;
4668 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4673 // No catch info found - try to extract some from the successor.
4674 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4678 // Lower all of the non-terminator instructions.
4679 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4683 // Ensure that all instructions which are used outside of their defining
4684 // blocks are available as virtual registers. Invoke is handled elsewhere.
4685 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4686 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4687 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4688 if (VMI != FuncInfo.ValueMap.end())
4689 SDL.CopyValueToVirtualRegister(I, VMI->second);
4692 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4693 // ensure constants are generated when needed. Remember the virtual registers
4694 // that need to be added to the Machine PHI nodes as input. We cannot just
4695 // directly add them, because expansion might result in multiple MBB's for one
4696 // BB. As such, the start of the BB might correspond to a different MBB than
4699 TerminatorInst *TI = LLVMBB->getTerminator();
4701 // Emit constants only once even if used by multiple PHI nodes.
4702 std::map<Constant*, unsigned> ConstantsOut;
4704 // Vector bool would be better, but vector<bool> is really slow.
4705 std::vector<unsigned char> SuccsHandled;
4706 if (TI->getNumSuccessors())
4707 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4709 // Check successor nodes' PHI nodes that expect a constant to be available
4711 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4712 BasicBlock *SuccBB = TI->getSuccessor(succ);
4713 if (!isa<PHINode>(SuccBB->begin())) continue;
4714 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4716 // If this terminator has multiple identical successors (common for
4717 // switches), only handle each succ once.
4718 unsigned SuccMBBNo = SuccMBB->getNumber();
4719 if (SuccsHandled[SuccMBBNo]) continue;
4720 SuccsHandled[SuccMBBNo] = true;
4722 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4725 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4726 // nodes and Machine PHI nodes, but the incoming operands have not been
4728 for (BasicBlock::iterator I = SuccBB->begin();
4729 (PN = dyn_cast<PHINode>(I)); ++I) {
4730 // Ignore dead phi's.
4731 if (PN->use_empty()) continue;
4734 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4736 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4737 unsigned &RegOut = ConstantsOut[C];
4739 RegOut = FuncInfo.CreateRegForValue(C);
4740 SDL.CopyValueToVirtualRegister(C, RegOut);
4744 Reg = FuncInfo.ValueMap[PHIOp];
4746 assert(isa<AllocaInst>(PHIOp) &&
4747 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4748 "Didn't codegen value into a register!??");
4749 Reg = FuncInfo.CreateRegForValue(PHIOp);
4750 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
4754 // Remember that this register needs to added to the machine PHI node as
4755 // the input for this MBB.
4756 MVT::ValueType VT = TLI.getValueType(PN->getType());
4757 unsigned NumRegisters = TLI.getNumRegisters(VT);
4758 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4759 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4762 ConstantsOut.clear();
4764 // Lower the terminator after the copies are emitted.
4765 SDL.visit(*LLVMBB->getTerminator());
4767 // Copy over any CaseBlock records that may now exist due to SwitchInst
4768 // lowering, as well as any jump table information.
4769 SwitchCases.clear();
4770 SwitchCases = SDL.SwitchCases;
4772 JTCases = SDL.JTCases;
4773 BitTestCases.clear();
4774 BitTestCases = SDL.BitTestCases;
4776 // Make sure the root of the DAG is up-to-date.
4777 DAG.setRoot(SDL.getControlRoot());
4779 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4780 // with correct tailcall attribute so that the target can rely on the tailcall
4781 // attribute indicating whether the call is really eligible for tail call
4783 CheckDAGForTailCallsAndFixThem(DAG, TLI);
4786 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4787 DOUT << "Lowered selection DAG:\n";
4790 // Run the DAG combiner in pre-legalize mode.
4791 DAG.Combine(false, *AA);
4793 DOUT << "Optimized lowered selection DAG:\n";
4796 // Second step, hack on the DAG until it only uses operations and types that
4797 // the target supports.
4798 #if 0 // Enable this some day.
4799 DAG.LegalizeTypes();
4800 // Someday even later, enable a dag combine pass here.
4804 DOUT << "Legalized selection DAG:\n";
4807 // Run the DAG combiner in post-legalize mode.
4808 DAG.Combine(true, *AA);
4810 DOUT << "Optimized legalized selection DAG:\n";
4813 if (ViewISelDAGs) DAG.viewGraph();
4815 // Third, instruction select all of the operations to machine code, adding the
4816 // code to the MachineBasicBlock.
4817 InstructionSelectBasicBlock(DAG);
4819 DOUT << "Selected machine code:\n";
4823 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4824 FunctionLoweringInfo &FuncInfo) {
4825 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4827 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4830 // First step, lower LLVM code to some DAG. This DAG may use operations and
4831 // types that are not supported by the target.
4832 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4834 // Second step, emit the lowered DAG as machine code.
4835 CodeGenAndEmitDAG(DAG);
4838 DOUT << "Total amount of phi nodes to update: "
4839 << PHINodesToUpdate.size() << "\n";
4840 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4841 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4842 << ", " << PHINodesToUpdate[i].second << ")\n";);
4844 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4845 // PHI nodes in successors.
4846 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4847 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4848 MachineInstr *PHI = PHINodesToUpdate[i].first;
4849 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4850 "This is not a machine PHI node that we are updating!");
4851 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4853 PHI->addOperand(MachineOperand::CreateMBB(BB));
4858 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4859 // Lower header first, if it wasn't already lowered
4860 if (!BitTestCases[i].Emitted) {
4861 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4863 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4864 // Set the current basic block to the mbb we wish to insert the code into
4865 BB = BitTestCases[i].Parent;
4866 HSDL.setCurrentBasicBlock(BB);
4868 HSDL.visitBitTestHeader(BitTestCases[i]);
4869 HSDAG.setRoot(HSDL.getRoot());
4870 CodeGenAndEmitDAG(HSDAG);
4873 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4874 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4876 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
4877 // Set the current basic block to the mbb we wish to insert the code into
4878 BB = BitTestCases[i].Cases[j].ThisBB;
4879 BSDL.setCurrentBasicBlock(BB);
4882 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4883 BitTestCases[i].Reg,
4884 BitTestCases[i].Cases[j]);
4886 BSDL.visitBitTestCase(BitTestCases[i].Default,
4887 BitTestCases[i].Reg,
4888 BitTestCases[i].Cases[j]);
4891 BSDAG.setRoot(BSDL.getRoot());
4892 CodeGenAndEmitDAG(BSDAG);
4896 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4897 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4898 MachineBasicBlock *PHIBB = PHI->getParent();
4899 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4900 "This is not a machine PHI node that we are updating!");
4901 // This is "default" BB. We have two jumps to it. From "header" BB and
4902 // from last "case" BB.
4903 if (PHIBB == BitTestCases[i].Default) {
4904 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4906 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4907 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4909 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4912 // One of "cases" BB.
4913 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4914 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4915 if (cBB->succ_end() !=
4916 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4917 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4919 PHI->addOperand(MachineOperand::CreateMBB(cBB));
4925 // If the JumpTable record is filled in, then we need to emit a jump table.
4926 // Updating the PHI nodes is tricky in this case, since we need to determine
4927 // whether the PHI is a successor of the range check MBB or the jump table MBB
4928 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4929 // Lower header first, if it wasn't already lowered
4930 if (!JTCases[i].first.Emitted) {
4931 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4933 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4934 // Set the current basic block to the mbb we wish to insert the code into
4935 BB = JTCases[i].first.HeaderBB;
4936 HSDL.setCurrentBasicBlock(BB);
4938 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4939 HSDAG.setRoot(HSDL.getRoot());
4940 CodeGenAndEmitDAG(HSDAG);
4943 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4945 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
4946 // Set the current basic block to the mbb we wish to insert the code into
4947 BB = JTCases[i].second.MBB;
4948 JSDL.setCurrentBasicBlock(BB);
4950 JSDL.visitJumpTable(JTCases[i].second);
4951 JSDAG.setRoot(JSDL.getRoot());
4952 CodeGenAndEmitDAG(JSDAG);
4955 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4956 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4957 MachineBasicBlock *PHIBB = PHI->getParent();
4958 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4959 "This is not a machine PHI node that we are updating!");
4960 // "default" BB. We can go there only from header BB.
4961 if (PHIBB == JTCases[i].second.Default) {
4962 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4964 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
4966 // JT BB. Just iterate over successors here
4967 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4968 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4970 PHI->addOperand(MachineOperand::CreateMBB(BB));
4975 // If the switch block involved a branch to one of the actual successors, we
4976 // need to update PHI nodes in that block.
4977 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4978 MachineInstr *PHI = PHINodesToUpdate[i].first;
4979 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4980 "This is not a machine PHI node that we are updating!");
4981 if (BB->isSuccessor(PHI->getParent())) {
4982 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4984 PHI->addOperand(MachineOperand::CreateMBB(BB));
4988 // If we generated any switch lowering information, build and codegen any
4989 // additional DAGs necessary.
4990 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4991 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4993 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
4995 // Set the current basic block to the mbb we wish to insert the code into
4996 BB = SwitchCases[i].ThisBB;
4997 SDL.setCurrentBasicBlock(BB);
5000 SDL.visitSwitchCase(SwitchCases[i]);
5001 SDAG.setRoot(SDL.getRoot());
5002 CodeGenAndEmitDAG(SDAG);
5004 // Handle any PHI nodes in successors of this chunk, as if we were coming
5005 // from the original BB before switch expansion. Note that PHI nodes can
5006 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5007 // handle them the right number of times.
5008 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5009 for (MachineBasicBlock::iterator Phi = BB->begin();
5010 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5011 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5012 for (unsigned pn = 0; ; ++pn) {
5013 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5014 if (PHINodesToUpdate[pn].first == Phi) {
5015 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5017 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5023 // Don't process RHS if same block as LHS.
5024 if (BB == SwitchCases[i].FalseBB)
5025 SwitchCases[i].FalseBB = 0;
5027 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5028 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5029 SwitchCases[i].FalseBB = 0;
5031 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5036 //===----------------------------------------------------------------------===//
5037 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5038 /// target node in the graph.
5039 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5040 if (ViewSchedDAGs) DAG.viewGraph();
5042 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5046 RegisterScheduler::setDefault(Ctor);
5049 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5052 if (ViewSUnitDAGs) SL->viewGraph();
5058 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5059 return new HazardRecognizer();
5062 //===----------------------------------------------------------------------===//
5063 // Helper functions used by the generated instruction selector.
5064 //===----------------------------------------------------------------------===//
5065 // Calls to these methods are generated by tblgen.
5067 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5068 /// the dag combiner simplified the 255, we still want to match. RHS is the
5069 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5070 /// specified in the .td file (e.g. 255).
5071 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5072 int64_t DesiredMaskS) const {
5073 const APInt &ActualMask = RHS->getAPIntValue();
5074 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5076 // If the actual mask exactly matches, success!
5077 if (ActualMask == DesiredMask)
5080 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5081 if (ActualMask.intersects(~DesiredMask))
5084 // Otherwise, the DAG Combiner may have proven that the value coming in is
5085 // either already zero or is not demanded. Check for known zero input bits.
5086 APInt NeededMask = DesiredMask & ~ActualMask;
5087 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5090 // TODO: check to see if missing bits are just not demanded.
5092 // Otherwise, this pattern doesn't match.
5096 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5097 /// the dag combiner simplified the 255, we still want to match. RHS is the
5098 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5099 /// specified in the .td file (e.g. 255).
5100 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5101 int64_t DesiredMaskS) const {
5102 const APInt &ActualMask = RHS->getAPIntValue();
5103 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5105 // If the actual mask exactly matches, success!
5106 if (ActualMask == DesiredMask)
5109 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5110 if (ActualMask.intersects(~DesiredMask))
5113 // Otherwise, the DAG Combiner may have proven that the value coming in is
5114 // either already zero or is not demanded. Check for known zero input bits.
5115 APInt NeededMask = DesiredMask & ~ActualMask;
5117 APInt KnownZero, KnownOne;
5118 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5120 // If all the missing bits in the or are already known to be set, match!
5121 if ((NeededMask & KnownOne) == NeededMask)
5124 // TODO: check to see if missing bits are just not demanded.
5126 // Otherwise, this pattern doesn't match.
5131 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5132 /// by tblgen. Others should not call it.
5133 void SelectionDAGISel::
5134 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5135 std::vector<SDOperand> InOps;
5136 std::swap(InOps, Ops);
5138 Ops.push_back(InOps[0]); // input chain.
5139 Ops.push_back(InOps[1]); // input asm string.
5141 unsigned i = 2, e = InOps.size();
5142 if (InOps[e-1].getValueType() == MVT::Flag)
5143 --e; // Don't process a flag operand if it is here.
5146 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5147 if ((Flags & 7) != 4 /*MEM*/) {
5148 // Just skip over this operand, copying the operands verbatim.
5149 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5150 i += (Flags >> 3) + 1;
5152 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5153 // Otherwise, this is a memory operand. Ask the target to select it.
5154 std::vector<SDOperand> SelOps;
5155 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5156 cerr << "Could not match memory address. Inline asm failure!\n";
5160 // Add this to the output node.
5161 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5162 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5164 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5169 // Add the flag input back if present.
5170 if (e != InOps.size())
5171 Ops.push_back(InOps.back());
5174 char SelectionDAGISel::ID = 0;