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 //===---------------------------------------------------------------------===//
77 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79 ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
84 static RegisterScheduler
85 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
88 namespace { struct SDISelAsmOperandInfo; }
90 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
91 /// MVT::ValueTypes that represent all the individual underlying
92 /// non-aggregate types that comprise it.
93 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
94 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
95 // Given a struct type, recursively traverse the elements.
96 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
97 for (StructType::element_iterator EI = STy->element_begin(),
98 EB = STy->element_end();
100 ComputeValueVTs(TLI, *EI, ValueVTs);
103 // Given an array type, recursively traverse the elements.
104 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
105 const Type *EltTy = ATy->getElementType();
106 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
107 ComputeValueVTs(TLI, EltTy, ValueVTs);
110 // Base case: we can get an MVT::ValueType for this LLVM IR type.
111 ValueVTs.push_back(TLI.getValueType(Ty));
115 /// RegsForValue - This struct represents the registers (physical or virtual)
116 /// that a particular set of values is assigned, and the type information about
117 /// the value. The most common situation is to represent one value at a time,
118 /// but struct or array values are handled element-wise as multiple values.
119 /// The splitting of aggregates is performed recursively, so that we never
120 /// have aggregate-typed registers. The values at this point do not necessarily
121 /// have legal types, so each value may require one or more registers of some
124 struct VISIBILITY_HIDDEN RegsForValue {
125 /// TLI - The TargetLowering object.
127 const TargetLowering *TLI;
129 /// ValueVTs - The value types of the values, which may not be legal, and
130 /// may need be promoted or synthesized from one or more registers.
132 SmallVector<MVT::ValueType, 4> ValueVTs;
134 /// RegVTs - The value types of the registers. This is the same size as
135 /// ValueVTs and it records, for each value, what the type of the assigned
136 /// register or registers are. (Individual values are never synthesized
137 /// from more than one type of register.)
139 /// With virtual registers, the contents of RegVTs is redundant with TLI's
140 /// getRegisterType member function, however when with physical registers
141 /// it is necessary to have a separate record of the types.
143 SmallVector<MVT::ValueType, 4> RegVTs;
145 /// Regs - This list holds the registers assigned to the values.
146 /// Each legal or promoted value requires one register, and each
147 /// expanded value requires multiple registers.
149 SmallVector<unsigned, 4> Regs;
151 RegsForValue() : TLI(0) {}
153 RegsForValue(const TargetLowering &tli,
154 const SmallVector<unsigned, 4> ®s,
155 MVT::ValueType regvt, MVT::ValueType valuevt)
156 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
157 RegsForValue(const TargetLowering &tli,
158 const SmallVector<unsigned, 4> ®s,
159 const SmallVector<MVT::ValueType, 4> ®vts,
160 const SmallVector<MVT::ValueType, 4> &valuevts)
161 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
162 RegsForValue(const TargetLowering &tli,
163 unsigned Reg, const Type *Ty) : TLI(&tli) {
164 ComputeValueVTs(tli, Ty, ValueVTs);
166 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
167 MVT::ValueType ValueVT = ValueVTs[Value];
168 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
169 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
170 for (unsigned i = 0; i != NumRegs; ++i)
171 Regs.push_back(Reg + i);
172 RegVTs.push_back(RegisterVT);
177 /// append - Add the specified values to this one.
178 void append(const RegsForValue &RHS) {
180 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
181 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
182 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
186 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
187 /// this value and returns the result as a ValueVTs value. This uses
188 /// Chain/Flag as the input and updates them for the output Chain/Flag.
189 /// If the Flag pointer is NULL, no flag is used.
190 SDOperand getCopyFromRegs(SelectionDAG &DAG,
191 SDOperand &Chain, SDOperand *Flag) const;
193 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
194 /// specified value into the registers specified by this object. This uses
195 /// Chain/Flag as the input and updates them for the output Chain/Flag.
196 /// If the Flag pointer is NULL, no flag is used.
197 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
198 SDOperand &Chain, SDOperand *Flag) const;
200 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
201 /// operand list. This adds the code marker and includes the number of
202 /// values added into it.
203 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
204 std::vector<SDOperand> &Ops) const;
209 //===--------------------------------------------------------------------===//
210 /// createDefaultScheduler - This creates an instruction scheduler appropriate
212 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
214 MachineBasicBlock *BB) {
215 TargetLowering &TLI = IS->getTargetLowering();
217 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
218 return createTDListDAGScheduler(IS, DAG, BB);
220 assert(TLI.getSchedulingPreference() ==
221 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
222 return createBURRListDAGScheduler(IS, DAG, BB);
227 //===--------------------------------------------------------------------===//
228 /// FunctionLoweringInfo - This contains information that is global to a
229 /// function that is used when lowering a region of the function.
230 class FunctionLoweringInfo {
235 MachineRegisterInfo &RegInfo;
237 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
239 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
240 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
242 /// ValueMap - Since we emit code for the function a basic block at a time,
243 /// we must remember which virtual registers hold the values for
244 /// cross-basic-block values.
245 DenseMap<const Value*, unsigned> ValueMap;
247 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
248 /// the entry block. This allows the allocas to be efficiently referenced
249 /// anywhere in the function.
250 std::map<const AllocaInst*, int> StaticAllocaMap;
253 SmallSet<Instruction*, 8> CatchInfoLost;
254 SmallSet<Instruction*, 8> CatchInfoFound;
257 unsigned MakeReg(MVT::ValueType VT) {
258 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
261 /// isExportedInst - Return true if the specified value is an instruction
262 /// exported from its block.
263 bool isExportedInst(const Value *V) {
264 return ValueMap.count(V);
267 unsigned CreateRegForValue(const Value *V);
269 unsigned InitializeRegForValue(const Value *V) {
270 unsigned &R = ValueMap[V];
271 assert(R == 0 && "Already initialized this value register!");
272 return R = CreateRegForValue(V);
277 /// isSelector - Return true if this instruction is a call to the
278 /// eh.selector intrinsic.
279 static bool isSelector(Instruction *I) {
280 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
281 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
282 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
286 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
287 /// PHI nodes or outside of the basic block that defines it, or used by a
288 /// switch or atomic instruction, which may expand to multiple basic blocks.
289 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
290 if (isa<PHINode>(I)) return true;
291 BasicBlock *BB = I->getParent();
292 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
293 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
294 // FIXME: Remove switchinst special case.
295 isa<SwitchInst>(*UI))
300 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
301 /// entry block, return true. This includes arguments used by switches, since
302 /// the switch may expand into multiple basic blocks.
303 static bool isOnlyUsedInEntryBlock(Argument *A) {
304 BasicBlock *Entry = A->getParent()->begin();
305 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
306 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
307 return false; // Use not in entry block.
311 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
312 Function &fn, MachineFunction &mf)
313 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
315 // Create a vreg for each argument register that is not dead and is used
316 // outside of the entry block for the function.
317 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
319 if (!isOnlyUsedInEntryBlock(AI))
320 InitializeRegForValue(AI);
322 // Initialize the mapping of values to registers. This is only set up for
323 // instruction values that are used outside of the block that defines
325 Function::iterator BB = Fn.begin(), EB = Fn.end();
326 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
327 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
328 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
329 const Type *Ty = AI->getAllocatedType();
330 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
332 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
335 TySize *= CUI->getZExtValue(); // Get total allocated size.
336 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
337 StaticAllocaMap[AI] =
338 MF.getFrameInfo()->CreateStackObject(TySize, Align);
341 for (; BB != EB; ++BB)
342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
343 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
344 if (!isa<AllocaInst>(I) ||
345 !StaticAllocaMap.count(cast<AllocaInst>(I)))
346 InitializeRegForValue(I);
348 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
349 // also creates the initial PHI MachineInstrs, though none of the input
350 // operands are populated.
351 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
352 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
354 MF.getBasicBlockList().push_back(MBB);
356 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
359 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
360 if (PN->use_empty()) continue;
362 MVT::ValueType VT = TLI.getValueType(PN->getType());
363 unsigned NumRegisters = TLI.getNumRegisters(VT);
364 unsigned PHIReg = ValueMap[PN];
365 assert(PHIReg && "PHI node does not have an assigned virtual register!");
366 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
367 for (unsigned i = 0; i != NumRegisters; ++i)
368 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
373 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
374 /// the correctly promoted or expanded types. Assign these registers
375 /// consecutive vreg numbers and return the first assigned number.
377 /// In the case that the given value has struct or array type, this function
378 /// will assign registers for each member or element.
380 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
381 SmallVector<MVT::ValueType, 4> ValueVTs;
382 ComputeValueVTs(TLI, V->getType(), ValueVTs);
384 unsigned FirstReg = 0;
385 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
386 MVT::ValueType ValueVT = ValueVTs[Value];
387 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
389 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
390 for (unsigned i = 0; i != NumRegs; ++i) {
391 unsigned R = MakeReg(RegisterVT);
392 if (!FirstReg) FirstReg = R;
398 //===----------------------------------------------------------------------===//
399 /// SelectionDAGLowering - This is the common target-independent lowering
400 /// implementation that is parameterized by a TargetLowering object.
401 /// Also, targets can overload any lowering method.
404 class SelectionDAGLowering {
405 MachineBasicBlock *CurMBB;
407 DenseMap<const Value*, SDOperand> NodeMap;
409 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
410 /// them up and then emit token factor nodes when possible. This allows us to
411 /// get simple disambiguation between loads without worrying about alias
413 std::vector<SDOperand> PendingLoads;
415 /// PendingExports - CopyToReg nodes that copy values to virtual registers
416 /// for export to other blocks need to be emitted before any terminator
417 /// instruction, but they have no other ordering requirements. We bunch them
418 /// up and the emit a single tokenfactor for them just before terminator
420 std::vector<SDOperand> PendingExports;
422 /// Case - A struct to record the Value for a switch case, and the
423 /// case's target basic block.
427 MachineBasicBlock* BB;
429 Case() : Low(0), High(0), BB(0) { }
430 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
431 Low(low), High(high), BB(bb) { }
432 uint64_t size() const {
433 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
434 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
435 return (rHigh - rLow + 1ULL);
441 MachineBasicBlock* BB;
444 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
445 Mask(mask), BB(bb), Bits(bits) { }
448 typedef std::vector<Case> CaseVector;
449 typedef std::vector<CaseBits> CaseBitsVector;
450 typedef CaseVector::iterator CaseItr;
451 typedef std::pair<CaseItr, CaseItr> CaseRange;
453 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
454 /// of conditional branches.
456 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
457 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
459 /// CaseBB - The MBB in which to emit the compare and branch
460 MachineBasicBlock *CaseBB;
461 /// LT, GE - If nonzero, we know the current case value must be less-than or
462 /// greater-than-or-equal-to these Constants.
465 /// Range - A pair of iterators representing the range of case values to be
466 /// processed at this point in the binary search tree.
470 typedef std::vector<CaseRec> CaseRecVector;
472 /// The comparison function for sorting the switch case values in the vector.
473 /// WARNING: Case ranges should be disjoint!
475 bool operator () (const Case& C1, const Case& C2) {
476 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
477 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
478 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
479 return CI1->getValue().slt(CI2->getValue());
484 bool operator () (const CaseBits& C1, const CaseBits& C2) {
485 return C1.Bits > C2.Bits;
489 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
492 // TLI - This is information that describes the available target features we
493 // need for lowering. This indicates when operations are unavailable,
494 // implemented with a libcall, etc.
497 const TargetData *TD;
500 /// SwitchCases - Vector of CaseBlock structures used to communicate
501 /// SwitchInst code generation information.
502 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
503 /// JTCases - Vector of JumpTable structures used to communicate
504 /// SwitchInst code generation information.
505 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
506 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
508 /// FuncInfo - Information about the function as a whole.
510 FunctionLoweringInfo &FuncInfo;
512 /// GCI - Garbage collection metadata for the function.
513 CollectorMetadata *GCI;
515 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
517 FunctionLoweringInfo &funcinfo,
518 CollectorMetadata *gci)
519 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
520 FuncInfo(funcinfo), GCI(gci) {
523 /// getRoot - Return the current virtual root of the Selection DAG,
524 /// flushing any PendingLoad items. This must be done before emitting
525 /// a store or any other node that may need to be ordered after any
526 /// prior load instructions.
528 SDOperand getRoot() {
529 if (PendingLoads.empty())
530 return DAG.getRoot();
532 if (PendingLoads.size() == 1) {
533 SDOperand Root = PendingLoads[0];
535 PendingLoads.clear();
539 // Otherwise, we have to make a token factor node.
540 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
541 &PendingLoads[0], PendingLoads.size());
542 PendingLoads.clear();
547 /// getControlRoot - Similar to getRoot, but instead of flushing all the
548 /// PendingLoad items, flush all the PendingExports items. It is necessary
549 /// to do this before emitting a terminator instruction.
551 SDOperand getControlRoot() {
552 SDOperand Root = DAG.getRoot();
554 if (PendingExports.empty())
557 // Turn all of the CopyToReg chains into one factored node.
558 if (Root.getOpcode() != ISD::EntryToken) {
559 unsigned i = 0, e = PendingExports.size();
560 for (; i != e; ++i) {
561 assert(PendingExports[i].Val->getNumOperands() > 1);
562 if (PendingExports[i].Val->getOperand(0) == Root)
563 break; // Don't add the root if we already indirectly depend on it.
567 PendingExports.push_back(Root);
570 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
572 PendingExports.size());
573 PendingExports.clear();
578 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
580 void visit(Instruction &I) { visit(I.getOpcode(), I); }
582 void visit(unsigned Opcode, User &I) {
583 // Note: this doesn't use InstVisitor, because it has to work with
584 // ConstantExpr's in addition to instructions.
586 default: assert(0 && "Unknown instruction type encountered!");
588 // Build the switch statement using the Instruction.def file.
589 #define HANDLE_INST(NUM, OPCODE, CLASS) \
590 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
591 #include "llvm/Instruction.def"
595 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
597 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
598 const Value *SV, SDOperand Root,
599 bool isVolatile, unsigned Alignment);
601 SDOperand getValue(const Value *V);
603 void setValue(const Value *V, SDOperand NewN) {
604 SDOperand &N = NodeMap[V];
605 assert(N.Val == 0 && "Already set a value for this node!");
609 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
610 std::set<unsigned> &OutputRegs,
611 std::set<unsigned> &InputRegs);
613 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
614 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
616 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
617 void ExportFromCurrentBlock(Value *V);
618 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
619 MachineBasicBlock *LandingPad = NULL);
621 // Terminator instructions.
622 void visitRet(ReturnInst &I);
623 void visitBr(BranchInst &I);
624 void visitSwitch(SwitchInst &I);
625 void visitUnreachable(UnreachableInst &I) { /* noop */ }
627 // Helpers for visitSwitch
628 bool handleSmallSwitchRange(CaseRec& CR,
629 CaseRecVector& WorkList,
631 MachineBasicBlock* Default);
632 bool handleJTSwitchCase(CaseRec& CR,
633 CaseRecVector& WorkList,
635 MachineBasicBlock* Default);
636 bool handleBTSplitSwitchCase(CaseRec& CR,
637 CaseRecVector& WorkList,
639 MachineBasicBlock* Default);
640 bool handleBitTestsSwitchCase(CaseRec& CR,
641 CaseRecVector& WorkList,
643 MachineBasicBlock* Default);
644 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
645 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
646 void visitBitTestCase(MachineBasicBlock* NextMBB,
648 SelectionDAGISel::BitTestCase &B);
649 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
650 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
651 SelectionDAGISel::JumpTableHeader &JTH);
653 // These all get lowered before this pass.
654 void visitInvoke(InvokeInst &I);
655 void visitUnwind(UnwindInst &I);
657 void visitBinary(User &I, unsigned OpCode);
658 void visitShift(User &I, unsigned Opcode);
659 void visitAdd(User &I) {
660 if (I.getType()->isFPOrFPVector())
661 visitBinary(I, ISD::FADD);
663 visitBinary(I, ISD::ADD);
665 void visitSub(User &I);
666 void visitMul(User &I) {
667 if (I.getType()->isFPOrFPVector())
668 visitBinary(I, ISD::FMUL);
670 visitBinary(I, ISD::MUL);
672 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
673 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
674 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
675 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
676 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
677 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
678 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
679 void visitOr (User &I) { visitBinary(I, ISD::OR); }
680 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
681 void visitShl (User &I) { visitShift(I, ISD::SHL); }
682 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
683 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
684 void visitICmp(User &I);
685 void visitFCmp(User &I);
686 void visitVICmp(User &I);
687 void visitVFCmp(User &I);
688 // Visit the conversion instructions
689 void visitTrunc(User &I);
690 void visitZExt(User &I);
691 void visitSExt(User &I);
692 void visitFPTrunc(User &I);
693 void visitFPExt(User &I);
694 void visitFPToUI(User &I);
695 void visitFPToSI(User &I);
696 void visitUIToFP(User &I);
697 void visitSIToFP(User &I);
698 void visitPtrToInt(User &I);
699 void visitIntToPtr(User &I);
700 void visitBitCast(User &I);
702 void visitExtractElement(User &I);
703 void visitInsertElement(User &I);
704 void visitShuffleVector(User &I);
706 void visitExtractValue(User &I);
707 void visitInsertValue(User &I);
709 void visitGetElementPtr(User &I);
710 void visitSelect(User &I);
712 void visitMalloc(MallocInst &I);
713 void visitFree(FreeInst &I);
714 void visitAlloca(AllocaInst &I);
715 void visitLoad(LoadInst &I);
716 void visitStore(StoreInst &I);
717 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
718 void visitCall(CallInst &I);
719 void visitInlineAsm(CallSite CS);
720 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
721 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
723 void visitVAStart(CallInst &I);
724 void visitVAArg(VAArgInst &I);
725 void visitVAEnd(CallInst &I);
726 void visitVACopy(CallInst &I);
728 void visitGetResult(GetResultInst &I);
730 void visitUserOp1(Instruction &I) {
731 assert(0 && "UserOp1 should not exist at instruction selection time!");
734 void visitUserOp2(Instruction &I) {
735 assert(0 && "UserOp2 should not exist at instruction selection time!");
740 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
743 } // end namespace llvm
746 /// getCopyFromParts - Create a value that contains the specified legal parts
747 /// combined into the value they represent. If the parts combine to a type
748 /// larger then ValueVT then AssertOp can be used to specify whether the extra
749 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
750 /// (ISD::AssertSext).
751 static SDOperand getCopyFromParts(SelectionDAG &DAG,
752 const SDOperand *Parts,
754 MVT::ValueType PartVT,
755 MVT::ValueType ValueVT,
756 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
757 assert(NumParts > 0 && "No parts to assemble!");
758 TargetLowering &TLI = DAG.getTargetLoweringInfo();
759 SDOperand Val = Parts[0];
762 // Assemble the value from multiple parts.
763 if (!MVT::isVector(ValueVT)) {
764 unsigned PartBits = MVT::getSizeInBits(PartVT);
765 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
767 // Assemble the power of 2 part.
768 unsigned RoundParts = NumParts & (NumParts - 1) ?
769 1 << Log2_32(NumParts) : NumParts;
770 unsigned RoundBits = PartBits * RoundParts;
771 MVT::ValueType RoundVT = RoundBits == ValueBits ?
772 ValueVT : MVT::getIntegerType(RoundBits);
775 if (RoundParts > 2) {
776 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
777 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
778 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
784 if (TLI.isBigEndian())
786 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
788 if (RoundParts < NumParts) {
789 // Assemble the trailing non-power-of-2 part.
790 unsigned OddParts = NumParts - RoundParts;
791 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
792 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
794 // Combine the round and odd parts.
796 if (TLI.isBigEndian())
798 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
799 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
800 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
801 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
802 TLI.getShiftAmountTy()));
803 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
804 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
807 // Handle a multi-element vector.
808 MVT::ValueType IntermediateVT, RegisterVT;
809 unsigned NumIntermediates;
811 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
813 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
814 NumParts = NumRegs; // Silence a compiler warning.
815 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
816 assert(RegisterVT == Parts[0].getValueType() &&
817 "Part type doesn't match part!");
819 // Assemble the parts into intermediate operands.
820 SmallVector<SDOperand, 8> Ops(NumIntermediates);
821 if (NumIntermediates == NumParts) {
822 // If the register was not expanded, truncate or copy the value,
824 for (unsigned i = 0; i != NumParts; ++i)
825 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
826 PartVT, IntermediateVT);
827 } else if (NumParts > 0) {
828 // If the intermediate type was expanded, build the intermediate operands
830 assert(NumParts % NumIntermediates == 0 &&
831 "Must expand into a divisible number of parts!");
832 unsigned Factor = NumParts / NumIntermediates;
833 for (unsigned i = 0; i != NumIntermediates; ++i)
834 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
835 PartVT, IntermediateVT);
838 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
840 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
841 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
842 ValueVT, &Ops[0], NumIntermediates);
846 // There is now one part, held in Val. Correct it to match ValueVT.
847 PartVT = Val.getValueType();
849 if (PartVT == ValueVT)
852 if (MVT::isVector(PartVT)) {
853 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
854 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
857 if (MVT::isVector(ValueVT)) {
858 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
859 MVT::getVectorNumElements(ValueVT) == 1 &&
860 "Only trivial scalar-to-vector conversions should get here!");
861 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
864 if (MVT::isInteger(PartVT) &&
865 MVT::isInteger(ValueVT)) {
866 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
867 // For a truncate, see if we have any information to
868 // indicate whether the truncated bits will always be
869 // zero or sign-extension.
870 if (AssertOp != ISD::DELETED_NODE)
871 Val = DAG.getNode(AssertOp, PartVT, Val,
872 DAG.getValueType(ValueVT));
873 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
875 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
879 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
880 if (ValueVT < Val.getValueType())
881 // FP_ROUND's are always exact here.
882 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
883 DAG.getIntPtrConstant(1));
884 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
887 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
888 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
890 assert(0 && "Unknown mismatch!");
894 /// getCopyToParts - Create a series of nodes that contain the specified value
895 /// split into legal parts. If the parts contain more bits than Val, then, for
896 /// integers, ExtendKind can be used to specify how to generate the extra bits.
897 static void getCopyToParts(SelectionDAG &DAG,
901 MVT::ValueType PartVT,
902 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
903 TargetLowering &TLI = DAG.getTargetLoweringInfo();
904 MVT::ValueType PtrVT = TLI.getPointerTy();
905 MVT::ValueType ValueVT = Val.getValueType();
906 unsigned PartBits = MVT::getSizeInBits(PartVT);
907 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
912 if (!MVT::isVector(ValueVT)) {
913 if (PartVT == ValueVT) {
914 assert(NumParts == 1 && "No-op copy with multiple parts!");
919 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
920 // If the parts cover more bits than the value has, promote the value.
921 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
922 assert(NumParts == 1 && "Do not know what to promote to!");
923 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
924 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
925 ValueVT = MVT::getIntegerType(NumParts * PartBits);
926 Val = DAG.getNode(ExtendKind, ValueVT, Val);
928 assert(0 && "Unknown mismatch!");
930 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
931 // Different types of the same size.
932 assert(NumParts == 1 && PartVT != ValueVT);
933 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
934 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
935 // If the parts cover less bits than value has, truncate the value.
936 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
937 ValueVT = MVT::getIntegerType(NumParts * PartBits);
938 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
940 assert(0 && "Unknown mismatch!");
944 // The value may have changed - recompute ValueVT.
945 ValueVT = Val.getValueType();
946 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
947 "Failed to tile the value with PartVT!");
950 assert(PartVT == ValueVT && "Type conversion failed!");
955 // Expand the value into multiple parts.
956 if (NumParts & (NumParts - 1)) {
957 // The number of parts is not a power of 2. Split off and copy the tail.
958 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
959 "Do not know what to expand to!");
960 unsigned RoundParts = 1 << Log2_32(NumParts);
961 unsigned RoundBits = RoundParts * PartBits;
962 unsigned OddParts = NumParts - RoundParts;
963 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
964 DAG.getConstant(RoundBits,
965 TLI.getShiftAmountTy()));
966 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
967 if (TLI.isBigEndian())
968 // The odd parts were reversed by getCopyToParts - unreverse them.
969 std::reverse(Parts + RoundParts, Parts + NumParts);
970 NumParts = RoundParts;
971 ValueVT = MVT::getIntegerType(NumParts * PartBits);
972 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
975 // The number of parts is a power of 2. Repeatedly bisect the value using
977 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
978 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
980 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
981 for (unsigned i = 0; i < NumParts; i += StepSize) {
982 unsigned ThisBits = StepSize * PartBits / 2;
983 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
984 SDOperand &Part0 = Parts[i];
985 SDOperand &Part1 = Parts[i+StepSize/2];
987 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
988 DAG.getConstant(1, PtrVT));
989 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
990 DAG.getConstant(0, PtrVT));
992 if (ThisBits == PartBits && ThisVT != PartVT) {
993 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
994 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
999 if (TLI.isBigEndian())
1000 std::reverse(Parts, Parts + NumParts);
1006 if (NumParts == 1) {
1007 if (PartVT != ValueVT) {
1008 if (MVT::isVector(PartVT)) {
1009 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1011 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
1012 MVT::getVectorNumElements(ValueVT) == 1 &&
1013 "Only trivial vector-to-scalar conversions should get here!");
1014 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1015 DAG.getConstant(0, PtrVT));
1023 // Handle a multi-element vector.
1024 MVT::ValueType IntermediateVT, RegisterVT;
1025 unsigned NumIntermediates;
1027 DAG.getTargetLoweringInfo()
1028 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1030 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1032 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1033 NumParts = NumRegs; // Silence a compiler warning.
1034 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1036 // Split the vector into intermediate operands.
1037 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1038 for (unsigned i = 0; i != NumIntermediates; ++i)
1039 if (MVT::isVector(IntermediateVT))
1040 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1041 IntermediateVT, Val,
1042 DAG.getConstant(i * (NumElements / NumIntermediates),
1045 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1046 IntermediateVT, Val,
1047 DAG.getConstant(i, PtrVT));
1049 // Split the intermediate operands into legal parts.
1050 if (NumParts == NumIntermediates) {
1051 // If the register was not expanded, promote or copy the value,
1053 for (unsigned i = 0; i != NumParts; ++i)
1054 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1055 } else if (NumParts > 0) {
1056 // If the intermediate type was expanded, split each the value into
1058 assert(NumParts % NumIntermediates == 0 &&
1059 "Must expand into a divisible number of parts!");
1060 unsigned Factor = NumParts / NumIntermediates;
1061 for (unsigned i = 0; i != NumIntermediates; ++i)
1062 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1067 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1068 SDOperand &N = NodeMap[V];
1069 if (N.Val) return N;
1071 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1072 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
1074 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1075 return N = DAG.getConstant(CI->getValue(), VT);
1077 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1078 return N = DAG.getGlobalAddress(GV, VT);
1080 if (isa<ConstantPointerNull>(C))
1081 return N = DAG.getConstant(0, TLI.getPointerTy());
1083 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1084 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1086 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1087 return N = DAG.getNode(ISD::UNDEF, VT);
1089 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1090 visit(CE->getOpcode(), *CE);
1091 SDOperand N1 = NodeMap[V];
1092 assert(N1.Val && "visit didn't populate the ValueMap!");
1096 const VectorType *VecTy = cast<VectorType>(V->getType());
1097 unsigned NumElements = VecTy->getNumElements();
1099 // Now that we know the number and type of the elements, get that number of
1100 // elements into the Ops array based on what kind of constant it is.
1101 SmallVector<SDOperand, 16> Ops;
1102 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1103 for (unsigned i = 0; i != NumElements; ++i)
1104 Ops.push_back(getValue(CP->getOperand(i)));
1106 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1107 "Unknown vector constant!");
1108 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1111 if (isa<UndefValue>(C))
1112 Op = DAG.getNode(ISD::UNDEF, EltVT);
1113 else if (MVT::isFloatingPoint(EltVT))
1114 Op = DAG.getConstantFP(0, EltVT);
1116 Op = DAG.getConstant(0, EltVT);
1117 Ops.assign(NumElements, Op);
1120 // Create a BUILD_VECTOR node.
1121 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1124 // If this is a static alloca, generate it as the frameindex instead of
1126 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1127 std::map<const AllocaInst*, int>::iterator SI =
1128 FuncInfo.StaticAllocaMap.find(AI);
1129 if (SI != FuncInfo.StaticAllocaMap.end())
1130 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1133 unsigned InReg = FuncInfo.ValueMap[V];
1134 assert(InReg && "Value not in map!");
1136 RegsForValue RFV(TLI, InReg, V->getType());
1137 SDOperand Chain = DAG.getEntryNode();
1138 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1142 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1143 if (I.getNumOperands() == 0) {
1144 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1148 SmallVector<SDOperand, 8> NewValues;
1149 NewValues.push_back(getControlRoot());
1150 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1151 SDOperand RetOp = getValue(I.getOperand(i));
1152 MVT::ValueType VT = RetOp.getValueType();
1154 // FIXME: C calling convention requires the return type to be promoted to
1155 // at least 32-bit. But this is not necessary for non-C calling conventions.
1156 if (MVT::isInteger(VT)) {
1157 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1158 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1162 unsigned NumParts = TLI.getNumRegisters(VT);
1163 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1164 SmallVector<SDOperand, 4> Parts(NumParts);
1165 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1167 const Function *F = I.getParent()->getParent();
1168 if (F->paramHasAttr(0, ParamAttr::SExt))
1169 ExtendKind = ISD::SIGN_EXTEND;
1170 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1171 ExtendKind = ISD::ZERO_EXTEND;
1173 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1175 for (unsigned i = 0; i < NumParts; ++i) {
1176 NewValues.push_back(Parts[i]);
1177 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1180 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1181 &NewValues[0], NewValues.size()));
1184 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1185 /// the current basic block, add it to ValueMap now so that we'll get a
1187 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1188 // No need to export constants.
1189 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1191 // Already exported?
1192 if (FuncInfo.isExportedInst(V)) return;
1194 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1195 CopyValueToVirtualRegister(V, Reg);
1198 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1199 const BasicBlock *FromBB) {
1200 // The operands of the setcc have to be in this block. We don't know
1201 // how to export them from some other block.
1202 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1203 // Can export from current BB.
1204 if (VI->getParent() == FromBB)
1207 // Is already exported, noop.
1208 return FuncInfo.isExportedInst(V);
1211 // If this is an argument, we can export it if the BB is the entry block or
1212 // if it is already exported.
1213 if (isa<Argument>(V)) {
1214 if (FromBB == &FromBB->getParent()->getEntryBlock())
1217 // Otherwise, can only export this if it is already exported.
1218 return FuncInfo.isExportedInst(V);
1221 // Otherwise, constants can always be exported.
1225 static bool InBlock(const Value *V, const BasicBlock *BB) {
1226 if (const Instruction *I = dyn_cast<Instruction>(V))
1227 return I->getParent() == BB;
1231 /// FindMergedConditions - If Cond is an expression like
1232 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1233 MachineBasicBlock *TBB,
1234 MachineBasicBlock *FBB,
1235 MachineBasicBlock *CurBB,
1237 // If this node is not part of the or/and tree, emit it as a branch.
1238 Instruction *BOp = dyn_cast<Instruction>(Cond);
1240 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1241 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1242 BOp->getParent() != CurBB->getBasicBlock() ||
1243 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1244 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1245 const BasicBlock *BB = CurBB->getBasicBlock();
1247 // If the leaf of the tree is a comparison, merge the condition into
1249 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1250 // The operands of the cmp have to be in this block. We don't know
1251 // how to export them from some other block. If this is the first block
1252 // of the sequence, no exporting is needed.
1254 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1255 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1256 BOp = cast<Instruction>(Cond);
1257 ISD::CondCode Condition;
1258 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1259 switch (IC->getPredicate()) {
1260 default: assert(0 && "Unknown icmp predicate opcode!");
1261 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1262 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1263 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1264 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1265 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1266 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1267 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1268 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1269 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1270 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1272 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1273 ISD::CondCode FPC, FOC;
1274 switch (FC->getPredicate()) {
1275 default: assert(0 && "Unknown fcmp predicate opcode!");
1276 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1277 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1278 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1279 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1280 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1281 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1282 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1283 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1284 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1285 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1286 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1287 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1288 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1289 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1290 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1291 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1293 if (FiniteOnlyFPMath())
1298 Condition = ISD::SETEQ; // silence warning.
1299 assert(0 && "Unknown compare instruction");
1302 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1303 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1304 SwitchCases.push_back(CB);
1308 // Create a CaseBlock record representing this branch.
1309 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1310 NULL, TBB, FBB, CurBB);
1311 SwitchCases.push_back(CB);
1316 // Create TmpBB after CurBB.
1317 MachineFunction::iterator BBI = CurBB;
1318 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1319 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1321 if (Opc == Instruction::Or) {
1322 // Codegen X | Y as:
1330 // Emit the LHS condition.
1331 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1333 // Emit the RHS condition into TmpBB.
1334 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1336 assert(Opc == Instruction::And && "Unknown merge op!");
1337 // Codegen X & Y as:
1344 // This requires creation of TmpBB after CurBB.
1346 // Emit the LHS condition.
1347 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1349 // Emit the RHS condition into TmpBB.
1350 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1354 /// If the set of cases should be emitted as a series of branches, return true.
1355 /// If we should emit this as a bunch of and/or'd together conditions, return
1358 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1359 if (Cases.size() != 2) return true;
1361 // If this is two comparisons of the same values or'd or and'd together, they
1362 // will get folded into a single comparison, so don't emit two blocks.
1363 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1364 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1365 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1366 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1373 void SelectionDAGLowering::visitBr(BranchInst &I) {
1374 // Update machine-CFG edges.
1375 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1377 // Figure out which block is immediately after the current one.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1383 if (I.isUnconditional()) {
1384 // If this is not a fall-through branch, emit the branch.
1385 if (Succ0MBB != NextBlock)
1386 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1387 DAG.getBasicBlock(Succ0MBB)));
1389 // Update machine-CFG edges.
1390 CurMBB->addSuccessor(Succ0MBB);
1394 // If this condition is one of the special cases we handle, do special stuff
1396 Value *CondVal = I.getCondition();
1397 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1399 // If this is a series of conditions that are or'd or and'd together, emit
1400 // this as a sequence of branches instead of setcc's with and/or operations.
1401 // For example, instead of something like:
1414 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1415 if (BOp->hasOneUse() &&
1416 (BOp->getOpcode() == Instruction::And ||
1417 BOp->getOpcode() == Instruction::Or)) {
1418 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1419 // If the compares in later blocks need to use values not currently
1420 // exported from this block, export them now. This block should always
1421 // be the first entry.
1422 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1424 // Allow some cases to be rejected.
1425 if (ShouldEmitAsBranches(SwitchCases)) {
1426 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1427 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1428 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1431 // Emit the branch for this block.
1432 visitSwitchCase(SwitchCases[0]);
1433 SwitchCases.erase(SwitchCases.begin());
1437 // Okay, we decided not to do this, remove any inserted MBB's and clear
1439 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1440 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1442 SwitchCases.clear();
1446 // Create a CaseBlock record representing this branch.
1447 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1448 NULL, Succ0MBB, Succ1MBB, CurMBB);
1449 // Use visitSwitchCase to actually insert the fast branch sequence for this
1451 visitSwitchCase(CB);
1454 /// visitSwitchCase - Emits the necessary code to represent a single node in
1455 /// the binary search tree resulting from lowering a switch instruction.
1456 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1458 SDOperand CondLHS = getValue(CB.CmpLHS);
1460 // Build the setcc now.
1461 if (CB.CmpMHS == NULL) {
1462 // Fold "(X == true)" to X and "(X == false)" to !X to
1463 // handle common cases produced by branch lowering.
1464 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1466 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1467 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1468 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1470 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1472 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1474 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1475 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1477 SDOperand CmpOp = getValue(CB.CmpMHS);
1478 MVT::ValueType VT = CmpOp.getValueType();
1480 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1481 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1483 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1484 Cond = DAG.getSetCC(MVT::i1, SUB,
1485 DAG.getConstant(High-Low, VT), ISD::SETULE);
1490 // Set NextBlock to be the MBB immediately after the current one, if any.
1491 // This is used to avoid emitting unnecessary branches to the next block.
1492 MachineBasicBlock *NextBlock = 0;
1493 MachineFunction::iterator BBI = CurMBB;
1494 if (++BBI != CurMBB->getParent()->end())
1497 // If the lhs block is the next block, invert the condition so that we can
1498 // fall through to the lhs instead of the rhs block.
1499 if (CB.TrueBB == NextBlock) {
1500 std::swap(CB.TrueBB, CB.FalseBB);
1501 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1502 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1504 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1505 DAG.getBasicBlock(CB.TrueBB));
1506 if (CB.FalseBB == NextBlock)
1507 DAG.setRoot(BrCond);
1509 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1510 DAG.getBasicBlock(CB.FalseBB)));
1511 // Update successor info
1512 CurMBB->addSuccessor(CB.TrueBB);
1513 CurMBB->addSuccessor(CB.FalseBB);
1516 /// visitJumpTable - Emit JumpTable node in the current MBB
1517 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1518 // Emit the code for the jump table
1519 assert(JT.Reg != -1U && "Should lower JT Header first!");
1520 MVT::ValueType PTy = TLI.getPointerTy();
1521 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1522 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1523 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1528 /// visitJumpTableHeader - This function emits necessary code to produce index
1529 /// in the JumpTable from switch case.
1530 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1531 SelectionDAGISel::JumpTableHeader &JTH) {
1532 // Subtract the lowest switch case value from the value being switched on
1533 // and conditional branch to default mbb if the result is greater than the
1534 // difference between smallest and largest cases.
1535 SDOperand SwitchOp = getValue(JTH.SValue);
1536 MVT::ValueType VT = SwitchOp.getValueType();
1537 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1538 DAG.getConstant(JTH.First, VT));
1540 // The SDNode we just created, which holds the value being switched on
1541 // minus the the smallest case value, needs to be copied to a virtual
1542 // register so it can be used as an index into the jump table in a
1543 // subsequent basic block. This value may be smaller or larger than the
1544 // target's pointer type, and therefore require extension or truncating.
1545 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1546 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1548 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1550 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1551 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1552 JT.Reg = JumpTableReg;
1554 // Emit the range check for the jump table, and branch to the default
1555 // block for the switch statement if the value being switched on exceeds
1556 // the largest case in the switch.
1557 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1558 DAG.getConstant(JTH.Last-JTH.First,VT),
1561 // Set NextBlock to be the MBB immediately after the current one, if any.
1562 // This is used to avoid emitting unnecessary branches to the next block.
1563 MachineBasicBlock *NextBlock = 0;
1564 MachineFunction::iterator BBI = CurMBB;
1565 if (++BBI != CurMBB->getParent()->end())
1568 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1569 DAG.getBasicBlock(JT.Default));
1571 if (JT.MBB == NextBlock)
1572 DAG.setRoot(BrCond);
1574 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1575 DAG.getBasicBlock(JT.MBB)));
1580 /// visitBitTestHeader - This function emits necessary code to produce value
1581 /// suitable for "bit tests"
1582 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1583 // Subtract the minimum value
1584 SDOperand SwitchOp = getValue(B.SValue);
1585 MVT::ValueType VT = SwitchOp.getValueType();
1586 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1587 DAG.getConstant(B.First, VT));
1590 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1591 DAG.getConstant(B.Range, VT),
1595 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1596 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1598 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1600 // Make desired shift
1601 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1602 DAG.getConstant(1, TLI.getPointerTy()),
1605 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1606 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1609 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1610 DAG.getBasicBlock(B.Default));
1612 // Set NextBlock to be the MBB immediately after the current one, if any.
1613 // This is used to avoid emitting unnecessary branches to the next block.
1614 MachineBasicBlock *NextBlock = 0;
1615 MachineFunction::iterator BBI = CurMBB;
1616 if (++BBI != CurMBB->getParent()->end())
1619 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1620 if (MBB == NextBlock)
1621 DAG.setRoot(BrRange);
1623 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1624 DAG.getBasicBlock(MBB)));
1626 CurMBB->addSuccessor(B.Default);
1627 CurMBB->addSuccessor(MBB);
1632 /// visitBitTestCase - this function produces one "bit test"
1633 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1635 SelectionDAGISel::BitTestCase &B) {
1636 // Emit bit tests and jumps
1637 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1639 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1641 DAG.getConstant(B.Mask,
1642 TLI.getPointerTy()));
1643 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1644 DAG.getConstant(0, TLI.getPointerTy()),
1646 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1647 AndCmp, DAG.getBasicBlock(B.TargetBB));
1649 // Set NextBlock to be the MBB immediately after the current one, if any.
1650 // This is used to avoid emitting unnecessary branches to the next block.
1651 MachineBasicBlock *NextBlock = 0;
1652 MachineFunction::iterator BBI = CurMBB;
1653 if (++BBI != CurMBB->getParent()->end())
1656 if (NextMBB == NextBlock)
1659 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1660 DAG.getBasicBlock(NextMBB)));
1662 CurMBB->addSuccessor(B.TargetBB);
1663 CurMBB->addSuccessor(NextMBB);
1668 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1669 // Retrieve successors.
1670 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1671 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1673 if (isa<InlineAsm>(I.getCalledValue()))
1676 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1678 // If the value of the invoke is used outside of its defining block, make it
1679 // available as a virtual register.
1680 if (!I.use_empty()) {
1681 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1682 if (VMI != FuncInfo.ValueMap.end())
1683 CopyValueToVirtualRegister(&I, VMI->second);
1686 // Drop into normal successor.
1687 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1688 DAG.getBasicBlock(Return)));
1690 // Update successor info
1691 CurMBB->addSuccessor(Return);
1692 CurMBB->addSuccessor(LandingPad);
1695 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1698 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1699 /// small case ranges).
1700 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1701 CaseRecVector& WorkList,
1703 MachineBasicBlock* Default) {
1704 Case& BackCase = *(CR.Range.second-1);
1706 // Size is the number of Cases represented by this range.
1707 unsigned Size = CR.Range.second - CR.Range.first;
1711 // Get the MachineFunction which holds the current MBB. This is used when
1712 // inserting any additional MBBs necessary to represent the switch.
1713 MachineFunction *CurMF = CurMBB->getParent();
1715 // Figure out which block is immediately after the current one.
1716 MachineBasicBlock *NextBlock = 0;
1717 MachineFunction::iterator BBI = CR.CaseBB;
1719 if (++BBI != CurMBB->getParent()->end())
1722 // TODO: If any two of the cases has the same destination, and if one value
1723 // is the same as the other, but has one bit unset that the other has set,
1724 // use bit manipulation to do two compares at once. For example:
1725 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1727 // Rearrange the case blocks so that the last one falls through if possible.
1728 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1729 // The last case block won't fall through into 'NextBlock' if we emit the
1730 // branches in this order. See if rearranging a case value would help.
1731 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1732 if (I->BB == NextBlock) {
1733 std::swap(*I, BackCase);
1739 // Create a CaseBlock record representing a conditional branch to
1740 // the Case's target mbb if the value being switched on SV is equal
1742 MachineBasicBlock *CurBlock = CR.CaseBB;
1743 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1744 MachineBasicBlock *FallThrough;
1746 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1747 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1749 // If the last case doesn't match, go to the default block.
1750 FallThrough = Default;
1753 Value *RHS, *LHS, *MHS;
1755 if (I->High == I->Low) {
1756 // This is just small small case range :) containing exactly 1 case
1758 LHS = SV; RHS = I->High; MHS = NULL;
1761 LHS = I->Low; MHS = SV; RHS = I->High;
1763 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1764 I->BB, FallThrough, CurBlock);
1766 // If emitting the first comparison, just call visitSwitchCase to emit the
1767 // code into the current block. Otherwise, push the CaseBlock onto the
1768 // vector to be later processed by SDISel, and insert the node's MBB
1769 // before the next MBB.
1770 if (CurBlock == CurMBB)
1771 visitSwitchCase(CB);
1773 SwitchCases.push_back(CB);
1775 CurBlock = FallThrough;
1781 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1782 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1783 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1786 /// handleJTSwitchCase - Emit jumptable for current switch case range
1787 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1788 CaseRecVector& WorkList,
1790 MachineBasicBlock* Default) {
1791 Case& FrontCase = *CR.Range.first;
1792 Case& BackCase = *(CR.Range.second-1);
1794 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1795 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1798 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1802 if (!areJTsAllowed(TLI) || TSize <= 3)
1805 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1809 DOUT << "Lowering jump table\n"
1810 << "First entry: " << First << ". Last entry: " << Last << "\n"
1811 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1813 // Get the MachineFunction which holds the current MBB. This is used when
1814 // inserting any additional MBBs necessary to represent the switch.
1815 MachineFunction *CurMF = CurMBB->getParent();
1817 // Figure out which block is immediately after the current one.
1818 MachineBasicBlock *NextBlock = 0;
1819 MachineFunction::iterator BBI = CR.CaseBB;
1821 if (++BBI != CurMBB->getParent()->end())
1824 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1826 // Create a new basic block to hold the code for loading the address
1827 // of the jump table, and jumping to it. Update successor information;
1828 // we will either branch to the default case for the switch, or the jump
1830 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1831 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1832 CR.CaseBB->addSuccessor(Default);
1833 CR.CaseBB->addSuccessor(JumpTableBB);
1835 // Build a vector of destination BBs, corresponding to each target
1836 // of the jump table. If the value of the jump table slot corresponds to
1837 // a case statement, push the case's BB onto the vector, otherwise, push
1839 std::vector<MachineBasicBlock*> DestBBs;
1840 int64_t TEI = First;
1841 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1842 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1843 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1845 if ((Low <= TEI) && (TEI <= High)) {
1846 DestBBs.push_back(I->BB);
1850 DestBBs.push_back(Default);
1854 // Update successor info. Add one edge to each unique successor.
1855 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1856 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1857 E = DestBBs.end(); I != E; ++I) {
1858 if (!SuccsHandled[(*I)->getNumber()]) {
1859 SuccsHandled[(*I)->getNumber()] = true;
1860 JumpTableBB->addSuccessor(*I);
1864 // Create a jump table index for this jump table, or return an existing
1866 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1868 // Set the jump table information so that we can codegen it as a second
1869 // MachineBasicBlock
1870 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1871 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1872 (CR.CaseBB == CurMBB));
1873 if (CR.CaseBB == CurMBB)
1874 visitJumpTableHeader(JT, JTH);
1876 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1881 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1883 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1884 CaseRecVector& WorkList,
1886 MachineBasicBlock* Default) {
1887 // Get the MachineFunction which holds the current MBB. This is used when
1888 // inserting any additional MBBs necessary to represent the switch.
1889 MachineFunction *CurMF = CurMBB->getParent();
1891 // Figure out which block is immediately after the current one.
1892 MachineBasicBlock *NextBlock = 0;
1893 MachineFunction::iterator BBI = CR.CaseBB;
1895 if (++BBI != CurMBB->getParent()->end())
1898 Case& FrontCase = *CR.Range.first;
1899 Case& BackCase = *(CR.Range.second-1);
1900 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1902 // Size is the number of Cases represented by this range.
1903 unsigned Size = CR.Range.second - CR.Range.first;
1905 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1906 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1908 CaseItr Pivot = CR.Range.first + Size/2;
1910 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1911 // (heuristically) allow us to emit JumpTable's later.
1913 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1917 uint64_t LSize = FrontCase.size();
1918 uint64_t RSize = TSize-LSize;
1919 DOUT << "Selecting best pivot: \n"
1920 << "First: " << First << ", Last: " << Last <<"\n"
1921 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1922 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1924 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1925 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1926 assert((RBegin-LEnd>=1) && "Invalid case distance");
1927 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1928 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1929 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1930 // Should always split in some non-trivial place
1932 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1933 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1934 << "Metric: " << Metric << "\n";
1935 if (FMetric < Metric) {
1938 DOUT << "Current metric set to: " << FMetric << "\n";
1944 if (areJTsAllowed(TLI)) {
1945 // If our case is dense we *really* should handle it earlier!
1946 assert((FMetric > 0) && "Should handle dense range earlier!");
1948 Pivot = CR.Range.first + Size/2;
1951 CaseRange LHSR(CR.Range.first, Pivot);
1952 CaseRange RHSR(Pivot, CR.Range.second);
1953 Constant *C = Pivot->Low;
1954 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1956 // We know that we branch to the LHS if the Value being switched on is
1957 // less than the Pivot value, C. We use this to optimize our binary
1958 // tree a bit, by recognizing that if SV is greater than or equal to the
1959 // LHS's Case Value, and that Case Value is exactly one less than the
1960 // Pivot's Value, then we can branch directly to the LHS's Target,
1961 // rather than creating a leaf node for it.
1962 if ((LHSR.second - LHSR.first) == 1 &&
1963 LHSR.first->High == CR.GE &&
1964 cast<ConstantInt>(C)->getSExtValue() ==
1965 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1966 TrueBB = LHSR.first->BB;
1968 TrueBB = new MachineBasicBlock(LLVMBB);
1969 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1970 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1973 // Similar to the optimization above, if the Value being switched on is
1974 // known to be less than the Constant CR.LT, and the current Case Value
1975 // is CR.LT - 1, then we can branch directly to the target block for
1976 // the current Case Value, rather than emitting a RHS leaf node for it.
1977 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1978 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1979 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1980 FalseBB = RHSR.first->BB;
1982 FalseBB = new MachineBasicBlock(LLVMBB);
1983 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1984 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1987 // Create a CaseBlock record representing a conditional branch to
1988 // the LHS node if the value being switched on SV is less than C.
1989 // Otherwise, branch to LHS.
1990 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1991 TrueBB, FalseBB, CR.CaseBB);
1993 if (CR.CaseBB == CurMBB)
1994 visitSwitchCase(CB);
1996 SwitchCases.push_back(CB);
2001 /// handleBitTestsSwitchCase - if current case range has few destination and
2002 /// range span less, than machine word bitwidth, encode case range into series
2003 /// of masks and emit bit tests with these masks.
2004 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2005 CaseRecVector& WorkList,
2007 MachineBasicBlock* Default){
2008 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
2010 Case& FrontCase = *CR.Range.first;
2011 Case& BackCase = *(CR.Range.second-1);
2013 // Get the MachineFunction which holds the current MBB. This is used when
2014 // inserting any additional MBBs necessary to represent the switch.
2015 MachineFunction *CurMF = CurMBB->getParent();
2017 unsigned numCmps = 0;
2018 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2020 // Single case counts one, case range - two.
2021 if (I->Low == I->High)
2027 // Count unique destinations
2028 SmallSet<MachineBasicBlock*, 4> Dests;
2029 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2030 Dests.insert(I->BB);
2031 if (Dests.size() > 3)
2032 // Don't bother the code below, if there are too much unique destinations
2035 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2036 << "Total number of comparisons: " << numCmps << "\n";
2038 // Compute span of values.
2039 Constant* minValue = FrontCase.Low;
2040 Constant* maxValue = BackCase.High;
2041 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2042 cast<ConstantInt>(minValue)->getSExtValue();
2043 DOUT << "Compare range: " << range << "\n"
2044 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2045 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2047 if (range>=IntPtrBits ||
2048 (!(Dests.size() == 1 && numCmps >= 3) &&
2049 !(Dests.size() == 2 && numCmps >= 5) &&
2050 !(Dests.size() >= 3 && numCmps >= 6)))
2053 DOUT << "Emitting bit tests\n";
2054 int64_t lowBound = 0;
2056 // Optimize the case where all the case values fit in a
2057 // word without having to subtract minValue. In this case,
2058 // we can optimize away the subtraction.
2059 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2060 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2061 range = cast<ConstantInt>(maxValue)->getSExtValue();
2063 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2066 CaseBitsVector CasesBits;
2067 unsigned i, count = 0;
2069 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2070 MachineBasicBlock* Dest = I->BB;
2071 for (i = 0; i < count; ++i)
2072 if (Dest == CasesBits[i].BB)
2076 assert((count < 3) && "Too much destinations to test!");
2077 CasesBits.push_back(CaseBits(0, Dest, 0));
2081 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2082 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2084 for (uint64_t j = lo; j <= hi; j++) {
2085 CasesBits[i].Mask |= 1ULL << j;
2086 CasesBits[i].Bits++;
2090 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2092 SelectionDAGISel::BitTestInfo BTC;
2094 // Figure out which block is immediately after the current one.
2095 MachineFunction::iterator BBI = CR.CaseBB;
2098 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2101 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2102 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2103 << ", BB: " << CasesBits[i].BB << "\n";
2105 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2106 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2107 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2112 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2113 -1U, (CR.CaseBB == CurMBB),
2114 CR.CaseBB, Default, BTC);
2116 if (CR.CaseBB == CurMBB)
2117 visitBitTestHeader(BTB);
2119 BitTestCases.push_back(BTB);
2125 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2126 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2127 const SwitchInst& SI) {
2128 unsigned numCmps = 0;
2130 // Start with "simple" cases
2131 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2132 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2133 Cases.push_back(Case(SI.getSuccessorValue(i),
2134 SI.getSuccessorValue(i),
2137 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2139 // Merge case into clusters
2140 if (Cases.size()>=2)
2141 // Must recompute end() each iteration because it may be
2142 // invalidated by erase if we hold on to it
2143 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2144 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2145 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2146 MachineBasicBlock* nextBB = J->BB;
2147 MachineBasicBlock* currentBB = I->BB;
2149 // If the two neighboring cases go to the same destination, merge them
2150 // into a single case.
2151 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2159 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2160 if (I->Low != I->High)
2161 // A range counts double, since it requires two compares.
2168 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2169 // Figure out which block is immediately after the current one.
2170 MachineBasicBlock *NextBlock = 0;
2171 MachineFunction::iterator BBI = CurMBB;
2173 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2175 // If there is only the default destination, branch to it if it is not the
2176 // next basic block. Otherwise, just fall through.
2177 if (SI.getNumOperands() == 2) {
2178 // Update machine-CFG edges.
2180 // If this is not a fall-through branch, emit the branch.
2181 if (Default != NextBlock)
2182 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2183 DAG.getBasicBlock(Default)));
2185 CurMBB->addSuccessor(Default);
2189 // If there are any non-default case statements, create a vector of Cases
2190 // representing each one, and sort the vector so that we can efficiently
2191 // create a binary search tree from them.
2193 unsigned numCmps = Clusterify(Cases, SI);
2194 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2195 << ". Total compares: " << numCmps << "\n";
2197 // Get the Value to be switched on and default basic blocks, which will be
2198 // inserted into CaseBlock records, representing basic blocks in the binary
2200 Value *SV = SI.getOperand(0);
2202 // Push the initial CaseRec onto the worklist
2203 CaseRecVector WorkList;
2204 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2206 while (!WorkList.empty()) {
2207 // Grab a record representing a case range to process off the worklist
2208 CaseRec CR = WorkList.back();
2209 WorkList.pop_back();
2211 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2214 // If the range has few cases (two or less) emit a series of specific
2216 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2219 // If the switch has more than 5 blocks, and at least 40% dense, and the
2220 // target supports indirect branches, then emit a jump table rather than
2221 // lowering the switch to a binary tree of conditional branches.
2222 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2225 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2226 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2227 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2232 void SelectionDAGLowering::visitSub(User &I) {
2233 // -0.0 - X --> fneg
2234 const Type *Ty = I.getType();
2235 if (isa<VectorType>(Ty)) {
2236 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2237 const VectorType *DestTy = cast<VectorType>(I.getType());
2238 const Type *ElTy = DestTy->getElementType();
2239 if (ElTy->isFloatingPoint()) {
2240 unsigned VL = DestTy->getNumElements();
2241 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2242 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2244 SDOperand Op2 = getValue(I.getOperand(1));
2245 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2251 if (Ty->isFloatingPoint()) {
2252 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2253 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2254 SDOperand Op2 = getValue(I.getOperand(1));
2255 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2260 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2263 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2264 SDOperand Op1 = getValue(I.getOperand(0));
2265 SDOperand Op2 = getValue(I.getOperand(1));
2267 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2270 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2271 SDOperand Op1 = getValue(I.getOperand(0));
2272 SDOperand Op2 = getValue(I.getOperand(1));
2274 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2275 MVT::getSizeInBits(Op2.getValueType()))
2276 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2277 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2278 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2280 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2283 void SelectionDAGLowering::visitICmp(User &I) {
2284 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2285 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2286 predicate = IC->getPredicate();
2287 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2288 predicate = ICmpInst::Predicate(IC->getPredicate());
2289 SDOperand Op1 = getValue(I.getOperand(0));
2290 SDOperand Op2 = getValue(I.getOperand(1));
2291 ISD::CondCode Opcode;
2292 switch (predicate) {
2293 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2294 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2295 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2296 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2297 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2298 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2299 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2300 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2301 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2302 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2304 assert(!"Invalid ICmp predicate value");
2305 Opcode = ISD::SETEQ;
2308 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2311 void SelectionDAGLowering::visitFCmp(User &I) {
2312 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2313 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2314 predicate = FC->getPredicate();
2315 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2316 predicate = FCmpInst::Predicate(FC->getPredicate());
2317 SDOperand Op1 = getValue(I.getOperand(0));
2318 SDOperand Op2 = getValue(I.getOperand(1));
2319 ISD::CondCode Condition, FOC, FPC;
2320 switch (predicate) {
2321 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2322 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2323 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2324 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2325 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2326 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2327 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2328 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2329 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2330 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2331 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2332 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2333 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2334 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2335 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2336 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2338 assert(!"Invalid FCmp predicate value");
2339 FOC = FPC = ISD::SETFALSE;
2342 if (FiniteOnlyFPMath())
2346 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2349 void SelectionDAGLowering::visitVICmp(User &I) {
2350 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2351 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2352 predicate = IC->getPredicate();
2353 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2354 predicate = ICmpInst::Predicate(IC->getPredicate());
2355 SDOperand Op1 = getValue(I.getOperand(0));
2356 SDOperand Op2 = getValue(I.getOperand(1));
2357 ISD::CondCode Opcode;
2358 switch (predicate) {
2359 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2360 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2361 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2362 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2363 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2364 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2365 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2366 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2367 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2368 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2370 assert(!"Invalid ICmp predicate value");
2371 Opcode = ISD::SETEQ;
2374 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2377 void SelectionDAGLowering::visitVFCmp(User &I) {
2378 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2379 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2380 predicate = FC->getPredicate();
2381 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2382 predicate = FCmpInst::Predicate(FC->getPredicate());
2383 SDOperand Op1 = getValue(I.getOperand(0));
2384 SDOperand Op2 = getValue(I.getOperand(1));
2385 ISD::CondCode Condition, FOC, FPC;
2386 switch (predicate) {
2387 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2388 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2389 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2390 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2391 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2392 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2393 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2394 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2395 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2396 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2397 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2398 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2399 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2400 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2401 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2402 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2404 assert(!"Invalid VFCmp predicate value");
2405 FOC = FPC = ISD::SETFALSE;
2408 if (FiniteOnlyFPMath())
2413 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2415 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2418 void SelectionDAGLowering::visitSelect(User &I) {
2419 SDOperand Cond = getValue(I.getOperand(0));
2420 SDOperand TrueVal = getValue(I.getOperand(1));
2421 SDOperand FalseVal = getValue(I.getOperand(2));
2422 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2423 TrueVal, FalseVal));
2427 void SelectionDAGLowering::visitTrunc(User &I) {
2428 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2429 SDOperand N = getValue(I.getOperand(0));
2430 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2431 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2434 void SelectionDAGLowering::visitZExt(User &I) {
2435 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2436 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2437 SDOperand N = getValue(I.getOperand(0));
2438 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2439 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2442 void SelectionDAGLowering::visitSExt(User &I) {
2443 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2444 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2445 SDOperand N = getValue(I.getOperand(0));
2446 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2447 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2450 void SelectionDAGLowering::visitFPTrunc(User &I) {
2451 // FPTrunc is never a no-op cast, no need to check
2452 SDOperand N = getValue(I.getOperand(0));
2453 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2454 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2457 void SelectionDAGLowering::visitFPExt(User &I){
2458 // FPTrunc is never a no-op cast, no need to check
2459 SDOperand N = getValue(I.getOperand(0));
2460 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2461 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2464 void SelectionDAGLowering::visitFPToUI(User &I) {
2465 // FPToUI is never a no-op cast, no need to check
2466 SDOperand N = getValue(I.getOperand(0));
2467 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2468 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2471 void SelectionDAGLowering::visitFPToSI(User &I) {
2472 // FPToSI is never a no-op cast, no need to check
2473 SDOperand N = getValue(I.getOperand(0));
2474 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2475 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2478 void SelectionDAGLowering::visitUIToFP(User &I) {
2479 // UIToFP is never a no-op cast, no need to check
2480 SDOperand N = getValue(I.getOperand(0));
2481 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2482 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2485 void SelectionDAGLowering::visitSIToFP(User &I){
2486 // UIToFP is never a no-op cast, no need to check
2487 SDOperand N = getValue(I.getOperand(0));
2488 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2489 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2492 void SelectionDAGLowering::visitPtrToInt(User &I) {
2493 // What to do depends on the size of the integer and the size of the pointer.
2494 // We can either truncate, zero extend, or no-op, accordingly.
2495 SDOperand N = getValue(I.getOperand(0));
2496 MVT::ValueType SrcVT = N.getValueType();
2497 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2499 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2500 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2502 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2503 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2504 setValue(&I, Result);
2507 void SelectionDAGLowering::visitIntToPtr(User &I) {
2508 // What to do depends on the size of the integer and the size of the pointer.
2509 // We can either truncate, zero extend, or no-op, accordingly.
2510 SDOperand N = getValue(I.getOperand(0));
2511 MVT::ValueType SrcVT = N.getValueType();
2512 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2513 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2514 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2516 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2517 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2520 void SelectionDAGLowering::visitBitCast(User &I) {
2521 SDOperand N = getValue(I.getOperand(0));
2522 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2524 // BitCast assures us that source and destination are the same size so this
2525 // is either a BIT_CONVERT or a no-op.
2526 if (DestVT != N.getValueType())
2527 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2529 setValue(&I, N); // noop cast.
2532 void SelectionDAGLowering::visitInsertElement(User &I) {
2533 SDOperand InVec = getValue(I.getOperand(0));
2534 SDOperand InVal = getValue(I.getOperand(1));
2535 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2536 getValue(I.getOperand(2)));
2538 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2539 TLI.getValueType(I.getType()),
2540 InVec, InVal, InIdx));
2543 void SelectionDAGLowering::visitExtractElement(User &I) {
2544 SDOperand InVec = getValue(I.getOperand(0));
2545 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2546 getValue(I.getOperand(1)));
2547 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2548 TLI.getValueType(I.getType()), InVec, InIdx));
2551 void SelectionDAGLowering::visitShuffleVector(User &I) {
2552 SDOperand V1 = getValue(I.getOperand(0));
2553 SDOperand V2 = getValue(I.getOperand(1));
2554 SDOperand Mask = getValue(I.getOperand(2));
2556 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2557 TLI.getValueType(I.getType()),
2561 void SelectionDAGLowering::visitInsertValue(User &I) {
2562 assert(0 && "insertvalue instruction not implemented");
2566 void SelectionDAGLowering::visitExtractValue(User &I) {
2567 assert(0 && "extractvalue instruction not implemented");
2572 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2573 SDOperand N = getValue(I.getOperand(0));
2574 const Type *Ty = I.getOperand(0)->getType();
2576 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2579 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2580 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2583 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2584 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2585 DAG.getIntPtrConstant(Offset));
2587 Ty = StTy->getElementType(Field);
2589 Ty = cast<SequentialType>(Ty)->getElementType();
2591 // If this is a constant subscript, handle it quickly.
2592 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2593 if (CI->getZExtValue() == 0) continue;
2595 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2596 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2597 DAG.getIntPtrConstant(Offs));
2601 // N = N + Idx * ElementSize;
2602 uint64_t ElementSize = TD->getABITypeSize(Ty);
2603 SDOperand IdxN = getValue(Idx);
2605 // If the index is smaller or larger than intptr_t, truncate or extend
2607 if (IdxN.getValueType() < N.getValueType()) {
2608 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2609 } else if (IdxN.getValueType() > N.getValueType())
2610 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2612 // If this is a multiply by a power of two, turn it into a shl
2613 // immediately. This is a very common case.
2614 if (isPowerOf2_64(ElementSize)) {
2615 unsigned Amt = Log2_64(ElementSize);
2616 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2617 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2618 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2622 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2623 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2624 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2630 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2631 // If this is a fixed sized alloca in the entry block of the function,
2632 // allocate it statically on the stack.
2633 if (FuncInfo.StaticAllocaMap.count(&I))
2634 return; // getValue will auto-populate this.
2636 const Type *Ty = I.getAllocatedType();
2637 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2639 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2642 SDOperand AllocSize = getValue(I.getArraySize());
2643 MVT::ValueType IntPtr = TLI.getPointerTy();
2644 if (IntPtr < AllocSize.getValueType())
2645 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2646 else if (IntPtr > AllocSize.getValueType())
2647 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2649 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2650 DAG.getIntPtrConstant(TySize));
2652 // Handle alignment. If the requested alignment is less than or equal to
2653 // the stack alignment, ignore it. If the size is greater than or equal to
2654 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2655 unsigned StackAlign =
2656 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2657 if (Align <= StackAlign)
2660 // Round the size of the allocation up to the stack alignment size
2661 // by add SA-1 to the size.
2662 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2663 DAG.getIntPtrConstant(StackAlign-1));
2664 // Mask out the low bits for alignment purposes.
2665 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2666 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2668 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2669 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2671 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2673 DAG.setRoot(DSA.getValue(1));
2675 // Inform the Frame Information that we have just allocated a variable-sized
2677 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2680 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2681 SDOperand Ptr = getValue(I.getOperand(0));
2687 // Do not serialize non-volatile loads against each other.
2688 Root = DAG.getRoot();
2691 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2692 Root, I.isVolatile(), I.getAlignment()));
2695 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2696 const Value *SV, SDOperand Root,
2698 unsigned Alignment) {
2700 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2701 isVolatile, Alignment);
2704 DAG.setRoot(L.getValue(1));
2706 PendingLoads.push_back(L.getValue(1));
2712 void SelectionDAGLowering::visitStore(StoreInst &I) {
2713 Value *SrcV = I.getOperand(0);
2714 SDOperand Src = getValue(SrcV);
2715 SDOperand Ptr = getValue(I.getOperand(1));
2716 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2717 I.isVolatile(), I.getAlignment()));
2720 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2722 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2723 unsigned Intrinsic) {
2724 bool HasChain = !I.doesNotAccessMemory();
2725 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2727 // Build the operand list.
2728 SmallVector<SDOperand, 8> Ops;
2729 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2731 // We don't need to serialize loads against other loads.
2732 Ops.push_back(DAG.getRoot());
2734 Ops.push_back(getRoot());
2738 // Add the intrinsic ID as an integer operand.
2739 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2741 // Add all operands of the call to the operand list.
2742 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2743 SDOperand Op = getValue(I.getOperand(i));
2744 assert(TLI.isTypeLegal(Op.getValueType()) &&
2745 "Intrinsic uses a non-legal type?");
2749 std::vector<MVT::ValueType> VTs;
2750 if (I.getType() != Type::VoidTy) {
2751 MVT::ValueType VT = TLI.getValueType(I.getType());
2752 if (MVT::isVector(VT)) {
2753 const VectorType *DestTy = cast<VectorType>(I.getType());
2754 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2756 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2757 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2760 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2764 VTs.push_back(MVT::Other);
2766 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2771 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2772 &Ops[0], Ops.size());
2773 else if (I.getType() != Type::VoidTy)
2774 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2775 &Ops[0], Ops.size());
2777 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2778 &Ops[0], Ops.size());
2781 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2783 PendingLoads.push_back(Chain);
2787 if (I.getType() != Type::VoidTy) {
2788 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2789 MVT::ValueType VT = TLI.getValueType(PTy);
2790 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2792 setValue(&I, Result);
2796 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2797 static GlobalVariable *ExtractTypeInfo (Value *V) {
2798 V = V->stripPointerCasts();
2799 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2800 assert ((GV || isa<ConstantPointerNull>(V)) &&
2801 "TypeInfo must be a global variable or NULL");
2805 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2806 /// call, and add them to the specified machine basic block.
2807 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2808 MachineBasicBlock *MBB) {
2809 // Inform the MachineModuleInfo of the personality for this landing pad.
2810 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2811 assert(CE->getOpcode() == Instruction::BitCast &&
2812 isa<Function>(CE->getOperand(0)) &&
2813 "Personality should be a function");
2814 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2816 // Gather all the type infos for this landing pad and pass them along to
2817 // MachineModuleInfo.
2818 std::vector<GlobalVariable *> TyInfo;
2819 unsigned N = I.getNumOperands();
2821 for (unsigned i = N - 1; i > 2; --i) {
2822 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2823 unsigned FilterLength = CI->getZExtValue();
2824 unsigned FirstCatch = i + FilterLength + !FilterLength;
2825 assert (FirstCatch <= N && "Invalid filter length");
2827 if (FirstCatch < N) {
2828 TyInfo.reserve(N - FirstCatch);
2829 for (unsigned j = FirstCatch; j < N; ++j)
2830 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2831 MMI->addCatchTypeInfo(MBB, TyInfo);
2835 if (!FilterLength) {
2837 MMI->addCleanup(MBB);
2840 TyInfo.reserve(FilterLength - 1);
2841 for (unsigned j = i + 1; j < FirstCatch; ++j)
2842 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2843 MMI->addFilterTypeInfo(MBB, TyInfo);
2852 TyInfo.reserve(N - 3);
2853 for (unsigned j = 3; j < N; ++j)
2854 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2855 MMI->addCatchTypeInfo(MBB, TyInfo);
2860 /// Inlined utility function to implement binary input atomic intrinsics for
2861 // visitIntrinsicCall: I is a call instruction
2862 // Op is the associated NodeType for I
2864 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2865 SDOperand Root = getRoot();
2866 SDOperand O2 = getValue(I.getOperand(2));
2867 SDOperand L = DAG.getAtomic(Op, Root,
2868 getValue(I.getOperand(1)),
2869 O2, O2.getValueType());
2871 DAG.setRoot(L.getValue(1));
2875 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2876 /// we want to emit this as a call to a named external function, return the name
2877 /// otherwise lower it and return null.
2879 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2880 switch (Intrinsic) {
2882 // By default, turn this into a target intrinsic node.
2883 visitTargetIntrinsic(I, Intrinsic);
2885 case Intrinsic::vastart: visitVAStart(I); return 0;
2886 case Intrinsic::vaend: visitVAEnd(I); return 0;
2887 case Intrinsic::vacopy: visitVACopy(I); return 0;
2888 case Intrinsic::returnaddress:
2889 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2890 getValue(I.getOperand(1))));
2892 case Intrinsic::frameaddress:
2893 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2894 getValue(I.getOperand(1))));
2896 case Intrinsic::setjmp:
2897 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2899 case Intrinsic::longjmp:
2900 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2902 case Intrinsic::memcpy_i32:
2903 case Intrinsic::memcpy_i64: {
2904 SDOperand Op1 = getValue(I.getOperand(1));
2905 SDOperand Op2 = getValue(I.getOperand(2));
2906 SDOperand Op3 = getValue(I.getOperand(3));
2907 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2908 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2909 I.getOperand(1), 0, I.getOperand(2), 0));
2912 case Intrinsic::memset_i32:
2913 case Intrinsic::memset_i64: {
2914 SDOperand Op1 = getValue(I.getOperand(1));
2915 SDOperand Op2 = getValue(I.getOperand(2));
2916 SDOperand Op3 = getValue(I.getOperand(3));
2917 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2918 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2919 I.getOperand(1), 0));
2922 case Intrinsic::memmove_i32:
2923 case Intrinsic::memmove_i64: {
2924 SDOperand Op1 = getValue(I.getOperand(1));
2925 SDOperand Op2 = getValue(I.getOperand(2));
2926 SDOperand Op3 = getValue(I.getOperand(3));
2927 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2929 // If the source and destination are known to not be aliases, we can
2930 // lower memmove as memcpy.
2931 uint64_t Size = -1ULL;
2932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2933 Size = C->getValue();
2934 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2935 AliasAnalysis::NoAlias) {
2936 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2937 I.getOperand(1), 0, I.getOperand(2), 0));
2941 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2942 I.getOperand(1), 0, I.getOperand(2), 0));
2945 case Intrinsic::dbg_stoppoint: {
2946 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2947 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2948 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2952 Ops[1] = getValue(SPI.getLineValue());
2953 Ops[2] = getValue(SPI.getColumnValue());
2955 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2956 assert(DD && "Not a debug information descriptor");
2957 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2959 Ops[3] = DAG.getString(CompileUnit->getFileName());
2960 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2962 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2967 case Intrinsic::dbg_region_start: {
2968 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2969 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2970 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2971 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2972 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2973 DAG.getConstant(LabelID, MVT::i32),
2974 DAG.getConstant(0, MVT::i32)));
2979 case Intrinsic::dbg_region_end: {
2980 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2981 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2982 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2983 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2984 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2985 DAG.getConstant(LabelID, MVT::i32),
2986 DAG.getConstant(0, MVT::i32)));
2991 case Intrinsic::dbg_func_start: {
2992 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2994 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2995 Value *SP = FSI.getSubprogram();
2996 if (SP && MMI->Verify(SP)) {
2997 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2998 // what (most?) gdb expects.
2999 DebugInfoDesc *DD = MMI->getDescFor(SP);
3000 assert(DD && "Not a debug information descriptor");
3001 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3002 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3003 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
3004 CompileUnit->getFileName());
3005 // Record the source line but does create a label. It will be emitted
3006 // at asm emission time.
3007 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3012 case Intrinsic::dbg_declare: {
3013 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3014 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3015 Value *Variable = DI.getVariable();
3016 if (MMI && Variable && MMI->Verify(Variable))
3017 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3018 getValue(DI.getAddress()), getValue(Variable)));
3022 case Intrinsic::eh_exception: {
3023 if (!CurMBB->isLandingPad()) {
3024 // FIXME: Mark exception register as live in. Hack for PR1508.
3025 unsigned Reg = TLI.getExceptionAddressRegister();
3026 if (Reg) CurMBB->addLiveIn(Reg);
3028 // Insert the EXCEPTIONADDR instruction.
3029 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3031 Ops[0] = DAG.getRoot();
3032 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3034 DAG.setRoot(Op.getValue(1));
3038 case Intrinsic::eh_selector_i32:
3039 case Intrinsic::eh_selector_i64: {
3040 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3041 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3042 MVT::i32 : MVT::i64);
3045 if (CurMBB->isLandingPad())
3046 addCatchInfo(I, MMI, CurMBB);
3049 FuncInfo.CatchInfoLost.insert(&I);
3051 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3052 unsigned Reg = TLI.getExceptionSelectorRegister();
3053 if (Reg) CurMBB->addLiveIn(Reg);
3056 // Insert the EHSELECTION instruction.
3057 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3059 Ops[0] = getValue(I.getOperand(1));
3061 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3063 DAG.setRoot(Op.getValue(1));
3065 setValue(&I, DAG.getConstant(0, VT));
3071 case Intrinsic::eh_typeid_for_i32:
3072 case Intrinsic::eh_typeid_for_i64: {
3073 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3074 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3075 MVT::i32 : MVT::i64);
3078 // Find the type id for the given typeinfo.
3079 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3081 unsigned TypeID = MMI->getTypeIDFor(GV);
3082 setValue(&I, DAG.getConstant(TypeID, VT));
3084 // Return something different to eh_selector.
3085 setValue(&I, DAG.getConstant(1, VT));
3091 case Intrinsic::eh_return: {
3092 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3095 MMI->setCallsEHReturn(true);
3096 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3099 getValue(I.getOperand(1)),
3100 getValue(I.getOperand(2))));
3102 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3108 case Intrinsic::eh_unwind_init: {
3109 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3110 MMI->setCallsUnwindInit(true);
3116 case Intrinsic::eh_dwarf_cfa: {
3117 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3119 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3120 CfaArg = DAG.getNode(ISD::TRUNCATE,
3121 TLI.getPointerTy(), getValue(I.getOperand(1)));
3123 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3124 TLI.getPointerTy(), getValue(I.getOperand(1)));
3126 SDOperand Offset = DAG.getNode(ISD::ADD,
3128 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3129 TLI.getPointerTy()),
3131 setValue(&I, DAG.getNode(ISD::ADD,
3133 DAG.getNode(ISD::FRAMEADDR,
3136 TLI.getPointerTy())),
3141 case Intrinsic::sqrt:
3142 setValue(&I, DAG.getNode(ISD::FSQRT,
3143 getValue(I.getOperand(1)).getValueType(),
3144 getValue(I.getOperand(1))));
3146 case Intrinsic::powi:
3147 setValue(&I, DAG.getNode(ISD::FPOWI,
3148 getValue(I.getOperand(1)).getValueType(),
3149 getValue(I.getOperand(1)),
3150 getValue(I.getOperand(2))));
3152 case Intrinsic::sin:
3153 setValue(&I, DAG.getNode(ISD::FSIN,
3154 getValue(I.getOperand(1)).getValueType(),
3155 getValue(I.getOperand(1))));
3157 case Intrinsic::cos:
3158 setValue(&I, DAG.getNode(ISD::FCOS,
3159 getValue(I.getOperand(1)).getValueType(),
3160 getValue(I.getOperand(1))));
3162 case Intrinsic::pow:
3163 setValue(&I, DAG.getNode(ISD::FPOW,
3164 getValue(I.getOperand(1)).getValueType(),
3165 getValue(I.getOperand(1)),
3166 getValue(I.getOperand(2))));
3168 case Intrinsic::pcmarker: {
3169 SDOperand Tmp = getValue(I.getOperand(1));
3170 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3173 case Intrinsic::readcyclecounter: {
3174 SDOperand Op = getRoot();
3175 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3176 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3179 DAG.setRoot(Tmp.getValue(1));
3182 case Intrinsic::part_select: {
3183 // Currently not implemented: just abort
3184 assert(0 && "part_select intrinsic not implemented");
3187 case Intrinsic::part_set: {
3188 // Currently not implemented: just abort
3189 assert(0 && "part_set intrinsic not implemented");
3192 case Intrinsic::bswap:
3193 setValue(&I, DAG.getNode(ISD::BSWAP,
3194 getValue(I.getOperand(1)).getValueType(),
3195 getValue(I.getOperand(1))));
3197 case Intrinsic::cttz: {
3198 SDOperand Arg = getValue(I.getOperand(1));
3199 MVT::ValueType Ty = Arg.getValueType();
3200 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3201 setValue(&I, result);
3204 case Intrinsic::ctlz: {
3205 SDOperand Arg = getValue(I.getOperand(1));
3206 MVT::ValueType Ty = Arg.getValueType();
3207 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3208 setValue(&I, result);
3211 case Intrinsic::ctpop: {
3212 SDOperand Arg = getValue(I.getOperand(1));
3213 MVT::ValueType Ty = Arg.getValueType();
3214 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3215 setValue(&I, result);
3218 case Intrinsic::stacksave: {
3219 SDOperand Op = getRoot();
3220 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3221 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3223 DAG.setRoot(Tmp.getValue(1));
3226 case Intrinsic::stackrestore: {
3227 SDOperand Tmp = getValue(I.getOperand(1));
3228 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3231 case Intrinsic::var_annotation:
3232 // Discard annotate attributes
3235 case Intrinsic::init_trampoline: {
3236 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3240 Ops[1] = getValue(I.getOperand(1));
3241 Ops[2] = getValue(I.getOperand(2));
3242 Ops[3] = getValue(I.getOperand(3));
3243 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3244 Ops[5] = DAG.getSrcValue(F);
3246 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3247 DAG.getNodeValueTypes(TLI.getPointerTy(),
3252 DAG.setRoot(Tmp.getValue(1));
3256 case Intrinsic::gcroot:
3258 Value *Alloca = I.getOperand(1);
3259 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3261 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3262 GCI->addStackRoot(FI->getIndex(), TypeMap);
3266 case Intrinsic::gcread:
3267 case Intrinsic::gcwrite:
3268 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3271 case Intrinsic::flt_rounds: {
3272 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3276 case Intrinsic::trap: {
3277 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3280 case Intrinsic::prefetch: {
3283 Ops[1] = getValue(I.getOperand(1));
3284 Ops[2] = getValue(I.getOperand(2));
3285 Ops[3] = getValue(I.getOperand(3));
3286 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3290 case Intrinsic::memory_barrier: {
3293 for (int x = 1; x < 6; ++x)
3294 Ops[x] = getValue(I.getOperand(x));
3296 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3299 case Intrinsic::atomic_lcs: {
3300 SDOperand Root = getRoot();
3301 SDOperand O3 = getValue(I.getOperand(3));
3302 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3303 getValue(I.getOperand(1)),
3304 getValue(I.getOperand(2)),
3305 O3, O3.getValueType());
3307 DAG.setRoot(L.getValue(1));
3310 case Intrinsic::atomic_las:
3311 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3312 case Intrinsic::atomic_lss:
3313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3314 case Intrinsic::atomic_load_and:
3315 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3316 case Intrinsic::atomic_load_or:
3317 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3318 case Intrinsic::atomic_load_xor:
3319 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3320 case Intrinsic::atomic_load_min:
3321 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3322 case Intrinsic::atomic_load_max:
3323 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3324 case Intrinsic::atomic_load_umin:
3325 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3326 case Intrinsic::atomic_load_umax:
3327 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3328 case Intrinsic::atomic_swap:
3329 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
3334 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3336 MachineBasicBlock *LandingPad) {
3337 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3338 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3339 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3340 unsigned BeginLabel = 0, EndLabel = 0;
3342 TargetLowering::ArgListTy Args;
3343 TargetLowering::ArgListEntry Entry;
3344 Args.reserve(CS.arg_size());
3345 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3347 SDOperand ArgNode = getValue(*i);
3348 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3350 unsigned attrInd = i - CS.arg_begin() + 1;
3351 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3352 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3353 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3354 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3355 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3356 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3357 Entry.Alignment = CS.getParamAlignment(attrInd);
3358 Args.push_back(Entry);
3361 if (LandingPad && MMI) {
3362 // Insert a label before the invoke call to mark the try range. This can be
3363 // used to detect deletion of the invoke via the MachineModuleInfo.
3364 BeginLabel = MMI->NextLabelID();
3365 // Both PendingLoads and PendingExports must be flushed here;
3366 // this call might not return.
3368 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3369 DAG.getConstant(BeginLabel, MVT::i32),
3370 DAG.getConstant(1, MVT::i32)));
3373 std::pair<SDOperand,SDOperand> Result =
3374 TLI.LowerCallTo(getRoot(), CS.getType(),
3375 CS.paramHasAttr(0, ParamAttr::SExt),
3376 CS.paramHasAttr(0, ParamAttr::ZExt),
3377 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3379 if (CS.getType() != Type::VoidTy)
3380 setValue(CS.getInstruction(), Result.first);
3381 DAG.setRoot(Result.second);
3383 if (LandingPad && MMI) {
3384 // Insert a label at the end of the invoke call to mark the try range. This
3385 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3386 EndLabel = MMI->NextLabelID();
3387 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3388 DAG.getConstant(EndLabel, MVT::i32),
3389 DAG.getConstant(1, MVT::i32)));
3391 // Inform MachineModuleInfo of range.
3392 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3397 void SelectionDAGLowering::visitCall(CallInst &I) {
3398 const char *RenameFn = 0;
3399 if (Function *F = I.getCalledFunction()) {
3400 if (F->isDeclaration()) {
3401 if (unsigned IID = F->getIntrinsicID()) {
3402 RenameFn = visitIntrinsicCall(I, IID);
3408 // Check for well-known libc/libm calls. If the function is internal, it
3409 // can't be a library call.
3410 unsigned NameLen = F->getNameLen();
3411 if (!F->hasInternalLinkage() && NameLen) {
3412 const char *NameStr = F->getNameStart();
3413 if (NameStr[0] == 'c' &&
3414 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3415 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3416 if (I.getNumOperands() == 3 && // Basic sanity checks.
3417 I.getOperand(1)->getType()->isFloatingPoint() &&
3418 I.getType() == I.getOperand(1)->getType() &&
3419 I.getType() == I.getOperand(2)->getType()) {
3420 SDOperand LHS = getValue(I.getOperand(1));
3421 SDOperand RHS = getValue(I.getOperand(2));
3422 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3426 } else if (NameStr[0] == 'f' &&
3427 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3428 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3429 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3430 if (I.getNumOperands() == 2 && // Basic sanity checks.
3431 I.getOperand(1)->getType()->isFloatingPoint() &&
3432 I.getType() == I.getOperand(1)->getType()) {
3433 SDOperand Tmp = getValue(I.getOperand(1));
3434 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3437 } else if (NameStr[0] == 's' &&
3438 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3439 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3440 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3441 if (I.getNumOperands() == 2 && // Basic sanity checks.
3442 I.getOperand(1)->getType()->isFloatingPoint() &&
3443 I.getType() == I.getOperand(1)->getType()) {
3444 SDOperand Tmp = getValue(I.getOperand(1));
3445 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3448 } else if (NameStr[0] == 'c' &&
3449 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3450 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3451 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3452 if (I.getNumOperands() == 2 && // Basic sanity checks.
3453 I.getOperand(1)->getType()->isFloatingPoint() &&
3454 I.getType() == I.getOperand(1)->getType()) {
3455 SDOperand Tmp = getValue(I.getOperand(1));
3456 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3461 } else if (isa<InlineAsm>(I.getOperand(0))) {
3468 Callee = getValue(I.getOperand(0));
3470 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3472 LowerCallTo(&I, Callee, I.isTailCall());
3476 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3477 if (isa<UndefValue>(I.getOperand(0))) {
3478 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3479 setValue(&I, Undef);
3483 // To add support for individual return values with aggregate types,
3484 // we'd need a way to take a getresult index and determine which
3485 // values of the Call SDNode are associated with it.
3486 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3487 "Individual return values must not be aggregates!");
3489 SDOperand Call = getValue(I.getOperand(0));
3490 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3494 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3495 /// this value and returns the result as a ValueVT value. This uses
3496 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3497 /// If the Flag pointer is NULL, no flag is used.
3498 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3500 SDOperand *Flag) const {
3501 // Assemble the legal parts into the final values.
3502 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3503 SmallVector<SDOperand, 8> Parts;
3504 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3505 // Copy the legal parts from the registers.
3506 MVT::ValueType ValueVT = ValueVTs[Value];
3507 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3508 MVT::ValueType RegisterVT = RegVTs[Value];
3510 Parts.resize(NumRegs);
3511 for (unsigned i = 0; i != NumRegs; ++i) {
3514 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3516 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3517 *Flag = P.getValue(2);
3519 Chain = P.getValue(1);
3523 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3528 if (ValueVTs.size() == 1)
3531 return DAG.getNode(ISD::MERGE_VALUES,
3532 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3533 &Values[0], ValueVTs.size());
3536 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3537 /// specified value into the registers specified by this object. This uses
3538 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3539 /// If the Flag pointer is NULL, no flag is used.
3540 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3541 SDOperand &Chain, SDOperand *Flag) const {
3542 // Get the list of the values's legal parts.
3543 unsigned NumRegs = Regs.size();
3544 SmallVector<SDOperand, 8> Parts(NumRegs);
3545 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3546 MVT::ValueType ValueVT = ValueVTs[Value];
3547 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3548 MVT::ValueType RegisterVT = RegVTs[Value];
3550 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3551 &Parts[Part], NumParts, RegisterVT);
3555 // Copy the parts into the registers.
3556 SmallVector<SDOperand, 8> Chains(NumRegs);
3557 for (unsigned i = 0; i != NumRegs; ++i) {
3560 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3562 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3563 *Flag = Part.getValue(1);
3565 Chains[i] = Part.getValue(0);
3568 if (NumRegs == 1 || Flag)
3569 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3570 // flagged to it. That is the CopyToReg nodes and the user are considered
3571 // a single scheduling unit. If we create a TokenFactor and return it as
3572 // chain, then the TokenFactor is both a predecessor (operand) of the
3573 // user as well as a successor (the TF operands are flagged to the user).
3574 // c1, f1 = CopyToReg
3575 // c2, f2 = CopyToReg
3576 // c3 = TokenFactor c1, c2
3579 Chain = Chains[NumRegs-1];
3581 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3584 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3585 /// operand list. This adds the code marker and includes the number of
3586 /// values added into it.
3587 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3588 std::vector<SDOperand> &Ops) const {
3589 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3590 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3591 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3592 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3593 MVT::ValueType RegisterVT = RegVTs[Value];
3594 for (unsigned i = 0; i != NumRegs; ++i)
3595 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3599 /// isAllocatableRegister - If the specified register is safe to allocate,
3600 /// i.e. it isn't a stack pointer or some other special register, return the
3601 /// register class for the register. Otherwise, return null.
3602 static const TargetRegisterClass *
3603 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3604 const TargetLowering &TLI,
3605 const TargetRegisterInfo *TRI) {
3606 MVT::ValueType FoundVT = MVT::Other;
3607 const TargetRegisterClass *FoundRC = 0;
3608 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3609 E = TRI->regclass_end(); RCI != E; ++RCI) {
3610 MVT::ValueType ThisVT = MVT::Other;
3612 const TargetRegisterClass *RC = *RCI;
3613 // If none of the the value types for this register class are valid, we
3614 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3615 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3617 if (TLI.isTypeLegal(*I)) {
3618 // If we have already found this register in a different register class,
3619 // choose the one with the largest VT specified. For example, on
3620 // PowerPC, we favor f64 register classes over f32.
3621 if (FoundVT == MVT::Other ||
3622 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3629 if (ThisVT == MVT::Other) continue;
3631 // NOTE: This isn't ideal. In particular, this might allocate the
3632 // frame pointer in functions that need it (due to them not being taken
3633 // out of allocation, because a variable sized allocation hasn't been seen
3634 // yet). This is a slight code pessimization, but should still work.
3635 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3636 E = RC->allocation_order_end(MF); I != E; ++I)
3638 // We found a matching register class. Keep looking at others in case
3639 // we find one with larger registers that this physreg is also in.
3650 /// AsmOperandInfo - This contains information for each constraint that we are
3652 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3653 /// CallOperand - If this is the result output operand or a clobber
3654 /// this is null, otherwise it is the incoming operand to the CallInst.
3655 /// This gets modified as the asm is processed.
3656 SDOperand CallOperand;
3658 /// AssignedRegs - If this is a register or register class operand, this
3659 /// contains the set of register corresponding to the operand.
3660 RegsForValue AssignedRegs;
3662 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3663 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3666 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3667 /// busy in OutputRegs/InputRegs.
3668 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3669 std::set<unsigned> &OutputRegs,
3670 std::set<unsigned> &InputRegs,
3671 const TargetRegisterInfo &TRI) const {
3673 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3674 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3677 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3678 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3683 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3685 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3686 const TargetRegisterInfo &TRI) {
3687 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3689 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3690 for (; *Aliases; ++Aliases)
3691 Regs.insert(*Aliases);
3694 } // end anon namespace.
3697 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3698 /// specified operand. We prefer to assign virtual registers, to allow the
3699 /// register allocator handle the assignment process. However, if the asm uses
3700 /// features that we can't model on machineinstrs, we have SDISel do the
3701 /// allocation. This produces generally horrible, but correct, code.
3703 /// OpInfo describes the operand.
3704 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3705 /// or any explicitly clobbered registers.
3706 /// Input and OutputRegs are the set of already allocated physical registers.
3708 void SelectionDAGLowering::
3709 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3710 std::set<unsigned> &OutputRegs,
3711 std::set<unsigned> &InputRegs) {
3712 // Compute whether this value requires an input register, an output register,
3714 bool isOutReg = false;
3715 bool isInReg = false;
3716 switch (OpInfo.Type) {
3717 case InlineAsm::isOutput:
3720 // If this is an early-clobber output, or if there is an input
3721 // constraint that matches this, we need to reserve the input register
3722 // so no other inputs allocate to it.
3723 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3725 case InlineAsm::isInput:
3729 case InlineAsm::isClobber:
3736 MachineFunction &MF = DAG.getMachineFunction();
3737 SmallVector<unsigned, 4> Regs;
3739 // If this is a constraint for a single physreg, or a constraint for a
3740 // register class, find it.
3741 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3742 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3743 OpInfo.ConstraintVT);
3745 unsigned NumRegs = 1;
3746 if (OpInfo.ConstraintVT != MVT::Other)
3747 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3748 MVT::ValueType RegVT;
3749 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3752 // If this is a constraint for a specific physical register, like {r17},
3754 if (PhysReg.first) {
3755 if (OpInfo.ConstraintVT == MVT::Other)
3756 ValueVT = *PhysReg.second->vt_begin();
3758 // Get the actual register value type. This is important, because the user
3759 // may have asked for (e.g.) the AX register in i32 type. We need to
3760 // remember that AX is actually i16 to get the right extension.
3761 RegVT = *PhysReg.second->vt_begin();
3763 // This is a explicit reference to a physical register.
3764 Regs.push_back(PhysReg.first);
3766 // If this is an expanded reference, add the rest of the regs to Regs.
3768 TargetRegisterClass::iterator I = PhysReg.second->begin();
3769 for (; *I != PhysReg.first; ++I)
3770 assert(I != PhysReg.second->end() && "Didn't find reg!");
3772 // Already added the first reg.
3774 for (; NumRegs; --NumRegs, ++I) {
3775 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
3779 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3780 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3781 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3785 // Otherwise, if this was a reference to an LLVM register class, create vregs
3786 // for this reference.
3787 std::vector<unsigned> RegClassRegs;
3788 const TargetRegisterClass *RC = PhysReg.second;
3790 // If this is an early clobber or tied register, our regalloc doesn't know
3791 // how to maintain the constraint. If it isn't, go ahead and create vreg
3792 // and let the regalloc do the right thing.
3793 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3794 // If there is some other early clobber and this is an input register,
3795 // then we are forced to pre-allocate the input reg so it doesn't
3796 // conflict with the earlyclobber.
3797 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3798 RegVT = *PhysReg.second->vt_begin();
3800 if (OpInfo.ConstraintVT == MVT::Other)
3803 // Create the appropriate number of virtual registers.
3804 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3805 for (; NumRegs; --NumRegs)
3806 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3808 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3812 // Otherwise, we can't allocate it. Let the code below figure out how to
3813 // maintain these constraints.
3814 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3817 // This is a reference to a register class that doesn't directly correspond
3818 // to an LLVM register class. Allocate NumRegs consecutive, available,
3819 // registers from the class.
3820 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3821 OpInfo.ConstraintVT);
3824 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3825 unsigned NumAllocated = 0;
3826 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3827 unsigned Reg = RegClassRegs[i];
3828 // See if this register is available.
3829 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3830 (isInReg && InputRegs.count(Reg))) { // Already used.
3831 // Make sure we find consecutive registers.
3836 // Check to see if this register is allocatable (i.e. don't give out the
3839 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3840 if (!RC) { // Couldn't allocate this register.
3841 // Reset NumAllocated to make sure we return consecutive registers.
3847 // Okay, this register is good, we can use it.
3850 // If we allocated enough consecutive registers, succeed.
3851 if (NumAllocated == NumRegs) {
3852 unsigned RegStart = (i-NumAllocated)+1;
3853 unsigned RegEnd = i+1;
3854 // Mark all of the allocated registers used.
3855 for (unsigned i = RegStart; i != RegEnd; ++i)
3856 Regs.push_back(RegClassRegs[i]);
3858 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
3859 OpInfo.ConstraintVT);
3860 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3865 // Otherwise, we couldn't allocate enough registers for this.
3869 /// visitInlineAsm - Handle a call to an InlineAsm object.
3871 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3872 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3874 /// ConstraintOperands - Information about all of the constraints.
3875 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3877 SDOperand Chain = getRoot();
3880 std::set<unsigned> OutputRegs, InputRegs;
3882 // Do a prepass over the constraints, canonicalizing them, and building up the
3883 // ConstraintOperands list.
3884 std::vector<InlineAsm::ConstraintInfo>
3885 ConstraintInfos = IA->ParseConstraints();
3887 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3888 // constraint. If so, we can't let the register allocator allocate any input
3889 // registers, because it will not know to avoid the earlyclobbered output reg.
3890 bool SawEarlyClobber = false;
3892 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3893 unsigned ResNo = 0; // ResNo - The result number of the next output.
3894 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3895 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3896 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3898 MVT::ValueType OpVT = MVT::Other;
3900 // Compute the value type for each operand.
3901 switch (OpInfo.Type) {
3902 case InlineAsm::isOutput:
3903 // Indirect outputs just consume an argument.
3904 if (OpInfo.isIndirect) {
3905 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3908 // The return value of the call is this value. As such, there is no
3909 // corresponding argument.
3910 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3911 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3912 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3914 assert(ResNo == 0 && "Asm only has one result!");
3915 OpVT = TLI.getValueType(CS.getType());
3919 case InlineAsm::isInput:
3920 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3922 case InlineAsm::isClobber:
3927 // If this is an input or an indirect output, process the call argument.
3928 // BasicBlocks are labels, currently appearing only in asm's.
3929 if (OpInfo.CallOperandVal) {
3930 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3931 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3933 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3934 const Type *OpTy = OpInfo.CallOperandVal->getType();
3935 // If this is an indirect operand, the operand is a pointer to the
3937 if (OpInfo.isIndirect)
3938 OpTy = cast<PointerType>(OpTy)->getElementType();
3940 // If OpTy is not a single value, it may be a struct/union that we
3941 // can tile with integers.
3942 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
3943 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3951 OpTy = IntegerType::get(BitSize);
3956 OpVT = TLI.getValueType(OpTy, true);
3960 OpInfo.ConstraintVT = OpVT;
3962 // Compute the constraint code and ConstraintType to use.
3963 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
3965 // Keep track of whether we see an earlyclobber.
3966 SawEarlyClobber |= OpInfo.isEarlyClobber;
3968 // If we see a clobber of a register, it is an early clobber.
3969 if (!SawEarlyClobber &&
3970 OpInfo.Type == InlineAsm::isClobber &&
3971 OpInfo.ConstraintType == TargetLowering::C_Register) {
3972 // Note that we want to ignore things that we don't trick here, like
3973 // dirflag, fpsr, flags, etc.
3974 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3975 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3976 OpInfo.ConstraintVT);
3977 if (PhysReg.first || PhysReg.second) {
3978 // This is a register we know of.
3979 SawEarlyClobber = true;
3983 // If this is a memory input, and if the operand is not indirect, do what we
3984 // need to to provide an address for the memory input.
3985 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3986 !OpInfo.isIndirect) {
3987 assert(OpInfo.Type == InlineAsm::isInput &&
3988 "Can only indirectify direct input operands!");
3990 // Memory operands really want the address of the value. If we don't have
3991 // an indirect input, put it in the constpool if we can, otherwise spill
3992 // it to a stack slot.
3994 // If the operand is a float, integer, or vector constant, spill to a
3995 // constant pool entry to get its address.
3996 Value *OpVal = OpInfo.CallOperandVal;
3997 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3998 isa<ConstantVector>(OpVal)) {
3999 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4000 TLI.getPointerTy());
4002 // Otherwise, create a stack slot and emit a store to it before the
4004 const Type *Ty = OpVal->getType();
4005 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4006 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4007 MachineFunction &MF = DAG.getMachineFunction();
4008 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4009 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4010 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4011 OpInfo.CallOperand = StackSlot;
4014 // There is no longer a Value* corresponding to this operand.
4015 OpInfo.CallOperandVal = 0;
4016 // It is now an indirect operand.
4017 OpInfo.isIndirect = true;
4020 // If this constraint is for a specific register, allocate it before
4022 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4023 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4025 ConstraintInfos.clear();
4028 // Second pass - Loop over all of the operands, assigning virtual or physregs
4029 // to registerclass operands.
4030 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4031 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4033 // C_Register operands have already been allocated, Other/Memory don't need
4035 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4036 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4039 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4040 std::vector<SDOperand> AsmNodeOperands;
4041 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4042 AsmNodeOperands.push_back(
4043 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4046 // Loop over all of the inputs, copying the operand values into the
4047 // appropriate registers and processing the output regs.
4048 RegsForValue RetValRegs;
4050 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4051 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4053 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4054 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4056 switch (OpInfo.Type) {
4057 case InlineAsm::isOutput: {
4058 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4059 OpInfo.ConstraintType != TargetLowering::C_Register) {
4060 // Memory output, or 'other' output (e.g. 'X' constraint).
4061 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4063 // Add information to the INLINEASM node to know about this output.
4064 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4065 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4066 TLI.getPointerTy()));
4067 AsmNodeOperands.push_back(OpInfo.CallOperand);
4071 // Otherwise, this is a register or register class output.
4073 // Copy the output from the appropriate register. Find a register that
4075 if (OpInfo.AssignedRegs.Regs.empty()) {
4076 cerr << "Couldn't allocate output reg for contraint '"
4077 << OpInfo.ConstraintCode << "'!\n";
4081 // If this is an indirect operand, store through the pointer after the
4083 if (OpInfo.isIndirect) {
4084 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4085 OpInfo.CallOperandVal));
4087 // This is the result value of the call.
4088 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4089 // Concatenate this output onto the outputs list.
4090 RetValRegs.append(OpInfo.AssignedRegs);
4093 // Add information to the INLINEASM node to know that this register is
4095 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4099 case InlineAsm::isInput: {
4100 SDOperand InOperandVal = OpInfo.CallOperand;
4102 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4103 // If this is required to match an output register we have already set,
4104 // just use its register.
4105 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4107 // Scan until we find the definition we already emitted of this operand.
4108 // When we find it, create a RegsForValue operand.
4109 unsigned CurOp = 2; // The first operand.
4110 for (; OperandNo; --OperandNo) {
4111 // Advance to the next operand.
4113 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4114 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4115 (NumOps & 7) == 4 /*MEM*/) &&
4116 "Skipped past definitions?");
4117 CurOp += (NumOps>>3)+1;
4121 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4122 if ((NumOps & 7) == 2 /*REGDEF*/) {
4123 // Add NumOps>>3 registers to MatchedRegs.
4124 RegsForValue MatchedRegs;
4125 MatchedRegs.TLI = &TLI;
4126 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4127 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4128 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4130 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4131 MatchedRegs.Regs.push_back(Reg);
4134 // Use the produced MatchedRegs object to
4135 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4136 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4139 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4140 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4141 // Add information to the INLINEASM node to know about this input.
4142 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4143 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4144 TLI.getPointerTy()));
4145 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4150 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4151 assert(!OpInfo.isIndirect &&
4152 "Don't know how to handle indirect other inputs yet!");
4154 std::vector<SDOperand> Ops;
4155 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4158 cerr << "Invalid operand for inline asm constraint '"
4159 << OpInfo.ConstraintCode << "'!\n";
4163 // Add information to the INLINEASM node to know about this input.
4164 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4165 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4166 TLI.getPointerTy()));
4167 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4169 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4170 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4171 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4172 "Memory operands expect pointer values");
4174 // Add information to the INLINEASM node to know about this input.
4175 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4176 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4177 TLI.getPointerTy()));
4178 AsmNodeOperands.push_back(InOperandVal);
4182 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4183 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4184 "Unknown constraint type!");
4185 assert(!OpInfo.isIndirect &&
4186 "Don't know how to handle indirect register inputs yet!");
4188 // Copy the input into the appropriate registers.
4189 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4190 "Couldn't allocate input reg!");
4192 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4194 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4198 case InlineAsm::isClobber: {
4199 // Add the clobbered value to the operand list, so that the register
4200 // allocator is aware that the physreg got clobbered.
4201 if (!OpInfo.AssignedRegs.Regs.empty())
4202 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4209 // Finish up input operands.
4210 AsmNodeOperands[0] = Chain;
4211 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4213 Chain = DAG.getNode(ISD::INLINEASM,
4214 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4215 &AsmNodeOperands[0], AsmNodeOperands.size());
4216 Flag = Chain.getValue(1);
4218 // If this asm returns a register value, copy the result from that register
4219 // and set it as the value of the call.
4220 if (!RetValRegs.Regs.empty()) {
4221 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4223 // If any of the results of the inline asm is a vector, it may have the
4224 // wrong width/num elts. This can happen for register classes that can
4225 // contain multiple different value types. The preg or vreg allocated may
4226 // not have the same VT as was expected. Convert it to the right type with
4228 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4229 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4230 if (MVT::isVector(Val.Val->getValueType(i)))
4231 Val = DAG.getNode(ISD::BIT_CONVERT,
4232 TLI.getValueType(ResSTy->getElementType(i)), Val);
4235 if (MVT::isVector(Val.getValueType()))
4236 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4240 setValue(CS.getInstruction(), Val);
4243 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4245 // Process indirect outputs, first output all of the flagged copies out of
4247 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4248 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4249 Value *Ptr = IndirectStoresToEmit[i].second;
4250 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4251 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4254 // Emit the non-flagged stores from the physregs.
4255 SmallVector<SDOperand, 8> OutChains;
4256 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4257 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4258 getValue(StoresToEmit[i].second),
4259 StoresToEmit[i].second, 0));
4260 if (!OutChains.empty())
4261 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4262 &OutChains[0], OutChains.size());
4267 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4268 SDOperand Src = getValue(I.getOperand(0));
4270 MVT::ValueType IntPtr = TLI.getPointerTy();
4272 if (IntPtr < Src.getValueType())
4273 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4274 else if (IntPtr > Src.getValueType())
4275 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4277 // Scale the source by the type size.
4278 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4279 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4280 Src, DAG.getIntPtrConstant(ElementSize));
4282 TargetLowering::ArgListTy Args;
4283 TargetLowering::ArgListEntry Entry;
4285 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4286 Args.push_back(Entry);
4288 std::pair<SDOperand,SDOperand> Result =
4289 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4290 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4291 setValue(&I, Result.first); // Pointers always fit in registers
4292 DAG.setRoot(Result.second);
4295 void SelectionDAGLowering::visitFree(FreeInst &I) {
4296 TargetLowering::ArgListTy Args;
4297 TargetLowering::ArgListEntry Entry;
4298 Entry.Node = getValue(I.getOperand(0));
4299 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4300 Args.push_back(Entry);
4301 MVT::ValueType IntPtr = TLI.getPointerTy();
4302 std::pair<SDOperand,SDOperand> Result =
4303 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4304 CallingConv::C, true,
4305 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4306 DAG.setRoot(Result.second);
4309 // EmitInstrWithCustomInserter - This method should be implemented by targets
4310 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4311 // instructions are special in various ways, which require special support to
4312 // insert. The specified MachineInstr is created but not inserted into any
4313 // basic blocks, and the scheduler passes ownership of it to this method.
4314 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4315 MachineBasicBlock *MBB) {
4316 cerr << "If a target marks an instruction with "
4317 << "'usesCustomDAGSchedInserter', it must implement "
4318 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4323 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4324 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4325 getValue(I.getOperand(1)),
4326 DAG.getSrcValue(I.getOperand(1))));
4329 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4330 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4331 getValue(I.getOperand(0)),
4332 DAG.getSrcValue(I.getOperand(0)));
4334 DAG.setRoot(V.getValue(1));
4337 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4338 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4339 getValue(I.getOperand(1)),
4340 DAG.getSrcValue(I.getOperand(1))));
4343 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4344 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4345 getValue(I.getOperand(1)),
4346 getValue(I.getOperand(2)),
4347 DAG.getSrcValue(I.getOperand(1)),
4348 DAG.getSrcValue(I.getOperand(2))));
4351 /// TargetLowering::LowerArguments - This is the default LowerArguments
4352 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4353 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4354 /// integrated into SDISel.
4355 std::vector<SDOperand>
4356 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4357 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4358 std::vector<SDOperand> Ops;
4359 Ops.push_back(DAG.getRoot());
4360 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4361 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4363 // Add one result value for each formal argument.
4364 std::vector<MVT::ValueType> RetVals;
4366 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4368 MVT::ValueType VT = getValueType(I->getType());
4369 ISD::ArgFlagsTy Flags;
4370 unsigned OriginalAlignment =
4371 getTargetData()->getABITypeAlignment(I->getType());
4373 if (F.paramHasAttr(j, ParamAttr::ZExt))
4375 if (F.paramHasAttr(j, ParamAttr::SExt))
4377 if (F.paramHasAttr(j, ParamAttr::InReg))
4379 if (F.paramHasAttr(j, ParamAttr::StructRet))
4381 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4383 const PointerType *Ty = cast<PointerType>(I->getType());
4384 const Type *ElementTy = Ty->getElementType();
4385 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4386 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4387 // For ByVal, alignment should be passed from FE. BE will guess if
4388 // this info is not there but there are cases it cannot get right.
4389 if (F.getParamAlignment(j))
4390 FrameAlign = F.getParamAlignment(j);
4391 Flags.setByValAlign(FrameAlign);
4392 Flags.setByValSize(FrameSize);
4394 if (F.paramHasAttr(j, ParamAttr::Nest))
4396 Flags.setOrigAlign(OriginalAlignment);
4398 MVT::ValueType RegisterVT = getRegisterType(VT);
4399 unsigned NumRegs = getNumRegisters(VT);
4400 for (unsigned i = 0; i != NumRegs; ++i) {
4401 RetVals.push_back(RegisterVT);
4402 ISD::ArgFlagsTy MyFlags = Flags;
4403 if (NumRegs > 1 && i == 0)
4405 // if it isn't first piece, alignment must be 1
4407 MyFlags.setOrigAlign(1);
4408 Ops.push_back(DAG.getArgFlags(MyFlags));
4412 RetVals.push_back(MVT::Other);
4415 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4416 DAG.getVTList(&RetVals[0], RetVals.size()),
4417 &Ops[0], Ops.size()).Val;
4419 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4420 // allows exposing the loads that may be part of the argument access to the
4421 // first DAGCombiner pass.
4422 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4424 // The number of results should match up, except that the lowered one may have
4425 // an extra flag result.
4426 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4427 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4428 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4429 && "Lowering produced unexpected number of results!");
4430 Result = TmpRes.Val;
4432 unsigned NumArgRegs = Result->getNumValues() - 1;
4433 DAG.setRoot(SDOperand(Result, NumArgRegs));
4435 // Set up the return result vector.
4439 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4441 MVT::ValueType VT = getValueType(I->getType());
4442 MVT::ValueType PartVT = getRegisterType(VT);
4444 unsigned NumParts = getNumRegisters(VT);
4445 SmallVector<SDOperand, 4> Parts(NumParts);
4446 for (unsigned j = 0; j != NumParts; ++j)
4447 Parts[j] = SDOperand(Result, i++);
4449 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4450 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4451 AssertOp = ISD::AssertSext;
4452 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4453 AssertOp = ISD::AssertZext;
4455 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4458 assert(i == NumArgRegs && "Argument register count mismatch!");
4463 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4464 /// implementation, which just inserts an ISD::CALL node, which is later custom
4465 /// lowered by the target to something concrete. FIXME: When all targets are
4466 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4467 std::pair<SDOperand, SDOperand>
4468 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4469 bool RetSExt, bool RetZExt, bool isVarArg,
4470 unsigned CallingConv, bool isTailCall,
4472 ArgListTy &Args, SelectionDAG &DAG) {
4473 SmallVector<SDOperand, 32> Ops;
4474 Ops.push_back(Chain); // Op#0 - Chain
4475 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4476 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4477 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4478 Ops.push_back(Callee);
4480 // Handle all of the outgoing arguments.
4481 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4482 MVT::ValueType VT = getValueType(Args[i].Ty);
4483 SDOperand Op = Args[i].Node;
4484 ISD::ArgFlagsTy Flags;
4485 unsigned OriginalAlignment =
4486 getTargetData()->getABITypeAlignment(Args[i].Ty);
4492 if (Args[i].isInReg)
4496 if (Args[i].isByVal) {
4498 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4499 const Type *ElementTy = Ty->getElementType();
4500 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4501 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4502 // For ByVal, alignment should come from FE. BE will guess if this
4503 // info is not there but there are cases it cannot get right.
4504 if (Args[i].Alignment)
4505 FrameAlign = Args[i].Alignment;
4506 Flags.setByValAlign(FrameAlign);
4507 Flags.setByValSize(FrameSize);
4511 Flags.setOrigAlign(OriginalAlignment);
4513 MVT::ValueType PartVT = getRegisterType(VT);
4514 unsigned NumParts = getNumRegisters(VT);
4515 SmallVector<SDOperand, 4> Parts(NumParts);
4516 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4519 ExtendKind = ISD::SIGN_EXTEND;
4520 else if (Args[i].isZExt)
4521 ExtendKind = ISD::ZERO_EXTEND;
4523 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4525 for (unsigned i = 0; i != NumParts; ++i) {
4526 // if it isn't first piece, alignment must be 1
4527 ISD::ArgFlagsTy MyFlags = Flags;
4528 if (NumParts > 1 && i == 0)
4531 MyFlags.setOrigAlign(1);
4533 Ops.push_back(Parts[i]);
4534 Ops.push_back(DAG.getArgFlags(MyFlags));
4538 // Figure out the result value types. We start by making a list of
4539 // the potentially illegal return value types.
4540 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4541 SmallVector<MVT::ValueType, 4> RetTys;
4542 ComputeValueVTs(*this, RetTy, RetTys);
4544 // Then we translate that to a list of legal types.
4545 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4546 MVT::ValueType VT = RetTys[I];
4547 MVT::ValueType RegisterVT = getRegisterType(VT);
4548 unsigned NumRegs = getNumRegisters(VT);
4549 for (unsigned i = 0; i != NumRegs; ++i)
4550 LoweredRetTys.push_back(RegisterVT);
4553 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4555 // Create the CALL node.
4556 SDOperand Res = DAG.getNode(ISD::CALL,
4557 DAG.getVTList(&LoweredRetTys[0],
4558 LoweredRetTys.size()),
4559 &Ops[0], Ops.size());
4560 Chain = Res.getValue(LoweredRetTys.size() - 1);
4562 // Gather up the call result into a single value.
4563 if (RetTy != Type::VoidTy) {
4564 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4567 AssertOp = ISD::AssertSext;
4569 AssertOp = ISD::AssertZext;
4571 SmallVector<SDOperand, 4> ReturnValues;
4573 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4574 MVT::ValueType VT = RetTys[I];
4575 MVT::ValueType RegisterVT = getRegisterType(VT);
4576 unsigned NumRegs = getNumRegisters(VT);
4577 unsigned RegNoEnd = NumRegs + RegNo;
4578 SmallVector<SDOperand, 4> Results;
4579 for (; RegNo != RegNoEnd; ++RegNo)
4580 Results.push_back(Res.getValue(RegNo));
4581 SDOperand ReturnValue =
4582 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4584 ReturnValues.push_back(ReturnValue);
4586 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4587 DAG.getNode(ISD::MERGE_VALUES,
4588 DAG.getVTList(&RetTys[0], RetTys.size()),
4589 &ReturnValues[0], ReturnValues.size());
4592 return std::make_pair(Res, Chain);
4595 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4596 assert(0 && "LowerOperation not implemented for this target!");
4601 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4602 SelectionDAG &DAG) {
4603 assert(0 && "CustomPromoteOperation not implemented for this target!");
4608 //===----------------------------------------------------------------------===//
4609 // SelectionDAGISel code
4610 //===----------------------------------------------------------------------===//
4612 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4613 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4616 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4617 AU.addRequired<AliasAnalysis>();
4618 AU.addRequired<CollectorModuleMetadata>();
4619 AU.setPreservesAll();
4622 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4623 // Get alias analysis for load/store combining.
4624 AA = &getAnalysis<AliasAnalysis>();
4626 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4627 if (MF.getFunction()->hasCollector())
4628 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4631 RegInfo = &MF.getRegInfo();
4632 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4634 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4636 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4637 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4638 // Mark landing pad.
4639 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4641 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4642 SelectBasicBlock(I, MF, FuncInfo);
4644 // Add function live-ins to entry block live-in set.
4645 BasicBlock *EntryBB = &Fn.getEntryBlock();
4646 BB = FuncInfo.MBBMap[EntryBB];
4647 if (!RegInfo->livein_empty())
4648 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4649 E = RegInfo->livein_end(); I != E; ++I)
4650 BB->addLiveIn(I->first);
4653 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4654 "Not all catch info was assigned to a landing pad!");
4660 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4661 SDOperand Op = getValue(V);
4662 assert((Op.getOpcode() != ISD::CopyFromReg ||
4663 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4664 "Copy from a reg to the same reg!");
4665 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4667 RegsForValue RFV(TLI, Reg, V->getType());
4668 SDOperand Chain = DAG.getEntryNode();
4669 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4670 PendingExports.push_back(Chain);
4673 void SelectionDAGISel::
4674 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4675 // If this is the entry block, emit arguments.
4676 Function &F = *LLVMBB->getParent();
4677 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4678 SDOperand OldRoot = SDL.DAG.getRoot();
4679 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4682 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4684 if (!AI->use_empty()) {
4685 SDL.setValue(AI, Args[a]);
4687 // If this argument is live outside of the entry block, insert a copy from
4688 // whereever we got it to the vreg that other BB's will reference it as.
4689 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4690 if (VMI != FuncInfo.ValueMap.end()) {
4691 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4695 // Finally, if the target has anything special to do, allow it to do so.
4696 // FIXME: this should insert code into the DAG!
4697 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4700 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4701 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4702 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4703 if (isSelector(I)) {
4704 // Apply the catch info to DestBB.
4705 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4707 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4708 FLI.CatchInfoFound.insert(I);
4713 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4714 /// whether object offset >= 0.
4716 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4717 if (!isa<FrameIndexSDNode>(Op)) return false;
4719 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4720 int FrameIdx = FrameIdxNode->getIndex();
4721 return MFI->isFixedObjectIndex(FrameIdx) &&
4722 MFI->getObjectOffset(FrameIdx) >= 0;
4725 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4726 /// possibly be overwritten when lowering the outgoing arguments in a tail
4727 /// call. Currently the implementation of this call is very conservative and
4728 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4729 /// virtual registers would be overwritten by direct lowering.
4730 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4731 MachineFrameInfo * MFI) {
4732 RegisterSDNode * OpReg = NULL;
4733 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4734 (Op.getOpcode()== ISD::CopyFromReg &&
4735 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4736 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4737 (Op.getOpcode() == ISD::LOAD &&
4738 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4739 (Op.getOpcode() == ISD::MERGE_VALUES &&
4740 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4741 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4747 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4748 /// DAG and fixes their tailcall attribute operand.
4749 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4750 TargetLowering& TLI) {
4751 SDNode * Ret = NULL;
4752 SDOperand Terminator = DAG.getRoot();
4755 if (Terminator.getOpcode() == ISD::RET) {
4756 Ret = Terminator.Val;
4759 // Fix tail call attribute of CALL nodes.
4760 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4761 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4762 if (BI->getOpcode() == ISD::CALL) {
4763 SDOperand OpRet(Ret, 0);
4764 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4765 bool isMarkedTailCall =
4766 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4767 // If CALL node has tail call attribute set to true and the call is not
4768 // eligible (no RET or the target rejects) the attribute is fixed to
4769 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4770 // must correctly identify tail call optimizable calls.
4771 if (!isMarkedTailCall) continue;
4773 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4774 // Not eligible. Mark CALL node as non tail call.
4775 SmallVector<SDOperand, 32> Ops;
4777 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4778 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4782 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4784 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4786 // Look for tail call clobbered arguments. Emit a series of
4787 // copyto/copyfrom virtual register nodes to protect them.
4788 SmallVector<SDOperand, 32> Ops;
4789 SDOperand Chain = OpCall.getOperand(0), InFlag;
4791 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4792 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4794 if (idx > 4 && (idx % 2)) {
4795 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4796 getArgFlags().isByVal();
4797 MachineFunction &MF = DAG.getMachineFunction();
4798 MachineFrameInfo *MFI = MF.getFrameInfo();
4800 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
4801 MVT::ValueType VT = Arg.getValueType();
4802 unsigned VReg = MF.getRegInfo().
4803 createVirtualRegister(TLI.getRegClassFor(VT));
4804 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4805 InFlag = Chain.getValue(1);
4806 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4807 Chain = Arg.getValue(1);
4808 InFlag = Arg.getValue(2);
4813 // Link in chain of CopyTo/CopyFromReg.
4815 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4821 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4822 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4823 FunctionLoweringInfo &FuncInfo) {
4824 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
4826 // Lower any arguments needed in this block if this is the entry block.
4827 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4828 LowerArguments(LLVMBB, SDL);
4830 BB = FuncInfo.MBBMap[LLVMBB];
4831 SDL.setCurrentBasicBlock(BB);
4833 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4835 if (MMI && BB->isLandingPad()) {
4836 // Add a label to mark the beginning of the landing pad. Deletion of the
4837 // landing pad can thus be detected via the MachineModuleInfo.
4838 unsigned LabelID = MMI->addLandingPad(BB);
4839 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4840 DAG.getConstant(LabelID, MVT::i32),
4841 DAG.getConstant(1, MVT::i32)));
4843 // Mark exception register as live in.
4844 unsigned Reg = TLI.getExceptionAddressRegister();
4845 if (Reg) BB->addLiveIn(Reg);
4847 // Mark exception selector register as live in.
4848 Reg = TLI.getExceptionSelectorRegister();
4849 if (Reg) BB->addLiveIn(Reg);
4851 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4852 // function and list of typeids logically belong to the invoke (or, if you
4853 // like, the basic block containing the invoke), and need to be associated
4854 // with it in the dwarf exception handling tables. Currently however the
4855 // information is provided by an intrinsic (eh.selector) that can be moved
4856 // to unexpected places by the optimizers: if the unwind edge is critical,
4857 // then breaking it can result in the intrinsics being in the successor of
4858 // the landing pad, not the landing pad itself. This results in exceptions
4859 // not being caught because no typeids are associated with the invoke.
4860 // This may not be the only way things can go wrong, but it is the only way
4861 // we try to work around for the moment.
4862 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4864 if (Br && Br->isUnconditional()) { // Critical edge?
4865 BasicBlock::iterator I, E;
4866 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4871 // No catch info found - try to extract some from the successor.
4872 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4876 // Lower all of the non-terminator instructions.
4877 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4881 // Ensure that all instructions which are used outside of their defining
4882 // blocks are available as virtual registers. Invoke is handled elsewhere.
4883 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4884 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4885 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4886 if (VMI != FuncInfo.ValueMap.end())
4887 SDL.CopyValueToVirtualRegister(I, VMI->second);
4890 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4891 // ensure constants are generated when needed. Remember the virtual registers
4892 // that need to be added to the Machine PHI nodes as input. We cannot just
4893 // directly add them, because expansion might result in multiple MBB's for one
4894 // BB. As such, the start of the BB might correspond to a different MBB than
4897 TerminatorInst *TI = LLVMBB->getTerminator();
4899 // Emit constants only once even if used by multiple PHI nodes.
4900 std::map<Constant*, unsigned> ConstantsOut;
4902 // Vector bool would be better, but vector<bool> is really slow.
4903 std::vector<unsigned char> SuccsHandled;
4904 if (TI->getNumSuccessors())
4905 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4907 // Check successor nodes' PHI nodes that expect a constant to be available
4909 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4910 BasicBlock *SuccBB = TI->getSuccessor(succ);
4911 if (!isa<PHINode>(SuccBB->begin())) continue;
4912 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4914 // If this terminator has multiple identical successors (common for
4915 // switches), only handle each succ once.
4916 unsigned SuccMBBNo = SuccMBB->getNumber();
4917 if (SuccsHandled[SuccMBBNo]) continue;
4918 SuccsHandled[SuccMBBNo] = true;
4920 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4923 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4924 // nodes and Machine PHI nodes, but the incoming operands have not been
4926 for (BasicBlock::iterator I = SuccBB->begin();
4927 (PN = dyn_cast<PHINode>(I)); ++I) {
4928 // Ignore dead phi's.
4929 if (PN->use_empty()) continue;
4932 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4934 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4935 unsigned &RegOut = ConstantsOut[C];
4937 RegOut = FuncInfo.CreateRegForValue(C);
4938 SDL.CopyValueToVirtualRegister(C, RegOut);
4942 Reg = FuncInfo.ValueMap[PHIOp];
4944 assert(isa<AllocaInst>(PHIOp) &&
4945 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4946 "Didn't codegen value into a register!??");
4947 Reg = FuncInfo.CreateRegForValue(PHIOp);
4948 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
4952 // Remember that this register needs to added to the machine PHI node as
4953 // the input for this MBB.
4954 MVT::ValueType VT = TLI.getValueType(PN->getType());
4955 unsigned NumRegisters = TLI.getNumRegisters(VT);
4956 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4957 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4960 ConstantsOut.clear();
4962 // Lower the terminator after the copies are emitted.
4963 SDL.visit(*LLVMBB->getTerminator());
4965 // Copy over any CaseBlock records that may now exist due to SwitchInst
4966 // lowering, as well as any jump table information.
4967 SwitchCases.clear();
4968 SwitchCases = SDL.SwitchCases;
4970 JTCases = SDL.JTCases;
4971 BitTestCases.clear();
4972 BitTestCases = SDL.BitTestCases;
4974 // Make sure the root of the DAG is up-to-date.
4975 DAG.setRoot(SDL.getControlRoot());
4977 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4978 // with correct tailcall attribute so that the target can rely on the tailcall
4979 // attribute indicating whether the call is really eligible for tail call
4981 CheckDAGForTailCallsAndFixThem(DAG, TLI);
4984 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4985 DOUT << "Lowered selection DAG:\n";
4988 // Run the DAG combiner in pre-legalize mode.
4989 DAG.Combine(false, *AA);
4991 DOUT << "Optimized lowered selection DAG:\n";
4994 // Second step, hack on the DAG until it only uses operations and types that
4995 // the target supports.
4996 #if 0 // Enable this some day.
4997 DAG.LegalizeTypes();
4998 // Someday even later, enable a dag combine pass here.
5002 DOUT << "Legalized selection DAG:\n";
5005 // Run the DAG combiner in post-legalize mode.
5006 DAG.Combine(true, *AA);
5008 DOUT << "Optimized legalized selection DAG:\n";
5011 if (ViewISelDAGs) DAG.viewGraph();
5013 // Third, instruction select all of the operations to machine code, adding the
5014 // code to the MachineBasicBlock.
5015 InstructionSelectBasicBlock(DAG);
5017 DOUT << "Selected machine code:\n";
5021 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5022 FunctionLoweringInfo &FuncInfo) {
5023 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5025 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5028 // First step, lower LLVM code to some DAG. This DAG may use operations and
5029 // types that are not supported by the target.
5030 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5032 // Second step, emit the lowered DAG as machine code.
5033 CodeGenAndEmitDAG(DAG);
5036 DOUT << "Total amount of phi nodes to update: "
5037 << PHINodesToUpdate.size() << "\n";
5038 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5039 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5040 << ", " << PHINodesToUpdate[i].second << ")\n";);
5042 // Next, now that we know what the last MBB the LLVM BB expanded is, update
5043 // PHI nodes in successors.
5044 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
5045 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5046 MachineInstr *PHI = PHINodesToUpdate[i].first;
5047 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5048 "This is not a machine PHI node that we are updating!");
5049 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5051 PHI->addOperand(MachineOperand::CreateMBB(BB));
5056 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5057 // Lower header first, if it wasn't already lowered
5058 if (!BitTestCases[i].Emitted) {
5059 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5061 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5062 // Set the current basic block to the mbb we wish to insert the code into
5063 BB = BitTestCases[i].Parent;
5064 HSDL.setCurrentBasicBlock(BB);
5066 HSDL.visitBitTestHeader(BitTestCases[i]);
5067 HSDAG.setRoot(HSDL.getRoot());
5068 CodeGenAndEmitDAG(HSDAG);
5071 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5072 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5074 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
5075 // Set the current basic block to the mbb we wish to insert the code into
5076 BB = BitTestCases[i].Cases[j].ThisBB;
5077 BSDL.setCurrentBasicBlock(BB);
5080 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5081 BitTestCases[i].Reg,
5082 BitTestCases[i].Cases[j]);
5084 BSDL.visitBitTestCase(BitTestCases[i].Default,
5085 BitTestCases[i].Reg,
5086 BitTestCases[i].Cases[j]);
5089 BSDAG.setRoot(BSDL.getRoot());
5090 CodeGenAndEmitDAG(BSDAG);
5094 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5095 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5096 MachineBasicBlock *PHIBB = PHI->getParent();
5097 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5098 "This is not a machine PHI node that we are updating!");
5099 // This is "default" BB. We have two jumps to it. From "header" BB and
5100 // from last "case" BB.
5101 if (PHIBB == BitTestCases[i].Default) {
5102 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5104 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5105 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5107 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5110 // One of "cases" BB.
5111 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5112 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5113 if (cBB->succ_end() !=
5114 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5115 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5117 PHI->addOperand(MachineOperand::CreateMBB(cBB));
5123 // If the JumpTable record is filled in, then we need to emit a jump table.
5124 // Updating the PHI nodes is tricky in this case, since we need to determine
5125 // whether the PHI is a successor of the range check MBB or the jump table MBB
5126 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5127 // Lower header first, if it wasn't already lowered
5128 if (!JTCases[i].first.Emitted) {
5129 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5131 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5132 // Set the current basic block to the mbb we wish to insert the code into
5133 BB = JTCases[i].first.HeaderBB;
5134 HSDL.setCurrentBasicBlock(BB);
5136 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5137 HSDAG.setRoot(HSDL.getRoot());
5138 CodeGenAndEmitDAG(HSDAG);
5141 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5143 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5144 // Set the current basic block to the mbb we wish to insert the code into
5145 BB = JTCases[i].second.MBB;
5146 JSDL.setCurrentBasicBlock(BB);
5148 JSDL.visitJumpTable(JTCases[i].second);
5149 JSDAG.setRoot(JSDL.getRoot());
5150 CodeGenAndEmitDAG(JSDAG);
5153 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5154 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5155 MachineBasicBlock *PHIBB = PHI->getParent();
5156 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5157 "This is not a machine PHI node that we are updating!");
5158 // "default" BB. We can go there only from header BB.
5159 if (PHIBB == JTCases[i].second.Default) {
5160 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5162 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5164 // JT BB. Just iterate over successors here
5165 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5166 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5168 PHI->addOperand(MachineOperand::CreateMBB(BB));
5173 // If the switch block involved a branch to one of the actual successors, we
5174 // need to update PHI nodes in that block.
5175 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5176 MachineInstr *PHI = PHINodesToUpdate[i].first;
5177 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5178 "This is not a machine PHI node that we are updating!");
5179 if (BB->isSuccessor(PHI->getParent())) {
5180 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5182 PHI->addOperand(MachineOperand::CreateMBB(BB));
5186 // If we generated any switch lowering information, build and codegen any
5187 // additional DAGs necessary.
5188 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5189 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5191 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5193 // Set the current basic block to the mbb we wish to insert the code into
5194 BB = SwitchCases[i].ThisBB;
5195 SDL.setCurrentBasicBlock(BB);
5198 SDL.visitSwitchCase(SwitchCases[i]);
5199 SDAG.setRoot(SDL.getRoot());
5200 CodeGenAndEmitDAG(SDAG);
5202 // Handle any PHI nodes in successors of this chunk, as if we were coming
5203 // from the original BB before switch expansion. Note that PHI nodes can
5204 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5205 // handle them the right number of times.
5206 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5207 for (MachineBasicBlock::iterator Phi = BB->begin();
5208 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5209 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5210 for (unsigned pn = 0; ; ++pn) {
5211 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5212 if (PHINodesToUpdate[pn].first == Phi) {
5213 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5215 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5221 // Don't process RHS if same block as LHS.
5222 if (BB == SwitchCases[i].FalseBB)
5223 SwitchCases[i].FalseBB = 0;
5225 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5226 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5227 SwitchCases[i].FalseBB = 0;
5229 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5234 //===----------------------------------------------------------------------===//
5235 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5236 /// target node in the graph.
5237 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5238 if (ViewSchedDAGs) DAG.viewGraph();
5240 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5244 RegisterScheduler::setDefault(Ctor);
5247 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5250 if (ViewSUnitDAGs) SL->viewGraph();
5256 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5257 return new HazardRecognizer();
5260 //===----------------------------------------------------------------------===//
5261 // Helper functions used by the generated instruction selector.
5262 //===----------------------------------------------------------------------===//
5263 // Calls to these methods are generated by tblgen.
5265 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5266 /// the dag combiner simplified the 255, we still want to match. RHS is the
5267 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5268 /// specified in the .td file (e.g. 255).
5269 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5270 int64_t DesiredMaskS) const {
5271 const APInt &ActualMask = RHS->getAPIntValue();
5272 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5274 // If the actual mask exactly matches, success!
5275 if (ActualMask == DesiredMask)
5278 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5279 if (ActualMask.intersects(~DesiredMask))
5282 // Otherwise, the DAG Combiner may have proven that the value coming in is
5283 // either already zero or is not demanded. Check for known zero input bits.
5284 APInt NeededMask = DesiredMask & ~ActualMask;
5285 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5288 // TODO: check to see if missing bits are just not demanded.
5290 // Otherwise, this pattern doesn't match.
5294 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5295 /// the dag combiner simplified the 255, we still want to match. RHS is the
5296 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5297 /// specified in the .td file (e.g. 255).
5298 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5299 int64_t DesiredMaskS) const {
5300 const APInt &ActualMask = RHS->getAPIntValue();
5301 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5303 // If the actual mask exactly matches, success!
5304 if (ActualMask == DesiredMask)
5307 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5308 if (ActualMask.intersects(~DesiredMask))
5311 // Otherwise, the DAG Combiner may have proven that the value coming in is
5312 // either already zero or is not demanded. Check for known zero input bits.
5313 APInt NeededMask = DesiredMask & ~ActualMask;
5315 APInt KnownZero, KnownOne;
5316 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5318 // If all the missing bits in the or are already known to be set, match!
5319 if ((NeededMask & KnownOne) == NeededMask)
5322 // TODO: check to see if missing bits are just not demanded.
5324 // Otherwise, this pattern doesn't match.
5329 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5330 /// by tblgen. Others should not call it.
5331 void SelectionDAGISel::
5332 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5333 std::vector<SDOperand> InOps;
5334 std::swap(InOps, Ops);
5336 Ops.push_back(InOps[0]); // input chain.
5337 Ops.push_back(InOps[1]); // input asm string.
5339 unsigned i = 2, e = InOps.size();
5340 if (InOps[e-1].getValueType() == MVT::Flag)
5341 --e; // Don't process a flag operand if it is here.
5344 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5345 if ((Flags & 7) != 4 /*MEM*/) {
5346 // Just skip over this operand, copying the operands verbatim.
5347 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5348 i += (Flags >> 3) + 1;
5350 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5351 // Otherwise, this is a memory operand. Ask the target to select it.
5352 std::vector<SDOperand> SelOps;
5353 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5354 cerr << "Could not match memory address. Inline asm failure!\n";
5358 // Add this to the output node.
5359 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5360 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5362 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5367 // Add the flag input back if present.
5368 if (e != InOps.size())
5369 Ops.push_back(InOps.back());
5372 char SelectionDAGISel::ID = 0;