1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/Collector.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Compiler.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
60 cl::desc("Pop up a window to show SUnit dags after they are processed"));
62 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
65 //===---------------------------------------------------------------------===//
67 /// RegisterScheduler class - Track the registration of instruction schedulers.
69 //===---------------------------------------------------------------------===//
70 MachinePassRegistry RegisterScheduler::Registry;
72 //===---------------------------------------------------------------------===//
74 /// ISHeuristic command line option for instruction schedulers.
76 //===---------------------------------------------------------------------===//
78 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
80 ISHeuristic("pre-RA-sched",
81 cl::init(&createDefaultScheduler),
82 cl::desc("Instruction schedulers available (before register"
85 static RegisterScheduler
86 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
90 namespace { struct SDISelAsmOperandInfo; }
92 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
93 /// MVT::ValueTypes that represent all the individual underlying
94 /// non-aggregate types that comprise it.
95 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
96 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
97 // Given a struct type, recursively traverse the elements.
98 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
99 for (StructType::element_iterator EI = STy->element_begin(),
100 EB = STy->element_end();
102 ComputeValueVTs(TLI, *EI, ValueVTs);
105 // Given an array type, recursively traverse the elements.
106 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
107 const Type *EltTy = ATy->getElementType();
108 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
109 ComputeValueVTs(TLI, EltTy, ValueVTs);
112 // Base case: we can get an MVT::ValueType for this LLVM IR type.
113 ValueVTs.push_back(TLI.getValueType(Ty));
117 /// RegsForValue - This struct represents the registers (physical or virtual)
118 /// that a particular set of values is assigned, and the type information about
119 /// the value. The most common situation is to represent one value at a time,
120 /// but struct or array values are handled element-wise as multiple values.
121 /// The splitting of aggregates is performed recursively, so that we never
122 /// have aggregate-typed registers. The values at this point do not necessarily
123 /// have legal types, so each value may require one or more registers of some
126 struct VISIBILITY_HIDDEN RegsForValue {
127 /// TLI - The TargetLowering object.
129 const TargetLowering *TLI;
131 /// ValueVTs - The value types of the values, which may not be legal, and
132 /// may need be promoted or synthesized from one or more registers.
134 SmallVector<MVT::ValueType, 4> ValueVTs;
136 /// RegVTs - The value types of the registers. This is the same size as
137 /// ValueVTs and it records, for each value, what the type of the assigned
138 /// register or registers are. (Individual values are never synthesized
139 /// from more than one type of register.)
141 /// With virtual registers, the contents of RegVTs is redundant with TLI's
142 /// getRegisterType member function, however when with physical registers
143 /// it is necessary to have a separate record of the types.
145 SmallVector<MVT::ValueType, 4> RegVTs;
147 /// Regs - This list holds the registers assigned to the values.
148 /// Each legal or promoted value requires one register, and each
149 /// expanded value requires multiple registers.
151 SmallVector<unsigned, 4> Regs;
153 RegsForValue() : TLI(0) {}
155 RegsForValue(const TargetLowering &tli,
156 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
157 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(1, Reg) {}
158 RegsForValue(const TargetLowering &tli,
159 const SmallVector<unsigned, 4> ®s,
160 MVT::ValueType regvt, MVT::ValueType valuevt)
161 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
162 RegsForValue(const TargetLowering &tli,
163 const SmallVector<unsigned, 4> ®s,
164 const SmallVector<MVT::ValueType, 4> ®vts,
165 const SmallVector<MVT::ValueType, 4> &valuevts)
166 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
167 RegsForValue(const TargetLowering &tli,
168 unsigned Reg, const Type *Ty) : TLI(&tli) {
169 ComputeValueVTs(tli, Ty, ValueVTs);
171 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
172 MVT::ValueType ValueVT = ValueVTs[Value];
173 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
174 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
175 for (unsigned i = 0; i != NumRegs; ++i)
176 Regs.push_back(Reg + i);
177 RegVTs.push_back(RegisterVT);
182 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
183 /// this value and returns the result as a ValueVTs value. This uses
184 /// Chain/Flag as the input and updates them for the output Chain/Flag.
185 /// If the Flag pointer is NULL, no flag is used.
186 SDOperand getCopyFromRegs(SelectionDAG &DAG,
187 SDOperand &Chain, SDOperand *Flag) const;
189 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
190 /// specified value into the registers specified by this object. This uses
191 /// Chain/Flag as the input and updates them for the output Chain/Flag.
192 /// If the Flag pointer is NULL, no flag is used.
193 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
194 SDOperand &Chain, SDOperand *Flag) const;
196 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
197 /// operand list. This adds the code marker and includes the number of
198 /// values added into it.
199 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
200 std::vector<SDOperand> &Ops) const;
205 //===--------------------------------------------------------------------===//
206 /// createDefaultScheduler - This creates an instruction scheduler appropriate
208 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
210 MachineBasicBlock *BB) {
211 TargetLowering &TLI = IS->getTargetLowering();
213 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
214 return createTDListDAGScheduler(IS, DAG, BB);
216 assert(TLI.getSchedulingPreference() ==
217 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
218 return createBURRListDAGScheduler(IS, DAG, BB);
223 //===--------------------------------------------------------------------===//
224 /// FunctionLoweringInfo - This contains information that is global to a
225 /// function that is used when lowering a region of the function.
226 class FunctionLoweringInfo {
231 MachineRegisterInfo &RegInfo;
233 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
235 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
236 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
238 /// ValueMap - Since we emit code for the function a basic block at a time,
239 /// we must remember which virtual registers hold the values for
240 /// cross-basic-block values.
241 DenseMap<const Value*, unsigned> ValueMap;
243 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
244 /// the entry block. This allows the allocas to be efficiently referenced
245 /// anywhere in the function.
246 std::map<const AllocaInst*, int> StaticAllocaMap;
249 SmallSet<Instruction*, 8> CatchInfoLost;
250 SmallSet<Instruction*, 8> CatchInfoFound;
253 unsigned MakeReg(MVT::ValueType VT) {
254 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
257 /// isExportedInst - Return true if the specified value is an instruction
258 /// exported from its block.
259 bool isExportedInst(const Value *V) {
260 return ValueMap.count(V);
263 unsigned CreateRegForValue(const Value *V);
265 unsigned InitializeRegForValue(const Value *V) {
266 unsigned &R = ValueMap[V];
267 assert(R == 0 && "Already initialized this value register!");
268 return R = CreateRegForValue(V);
273 /// isSelector - Return true if this instruction is a call to the
274 /// eh.selector intrinsic.
275 static bool isSelector(Instruction *I) {
276 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
277 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
278 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
282 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
283 /// PHI nodes or outside of the basic block that defines it, or used by a
284 /// switch or atomic instruction, which may expand to multiple basic blocks.
285 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
286 if (isa<PHINode>(I)) return true;
287 BasicBlock *BB = I->getParent();
288 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
289 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
290 // FIXME: Remove switchinst special case.
291 isa<SwitchInst>(*UI))
296 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
297 /// entry block, return true. This includes arguments used by switches, since
298 /// the switch may expand into multiple basic blocks.
299 static bool isOnlyUsedInEntryBlock(Argument *A) {
300 BasicBlock *Entry = A->getParent()->begin();
301 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
302 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
303 return false; // Use not in entry block.
307 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
308 Function &fn, MachineFunction &mf)
309 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
311 // Create a vreg for each argument register that is not dead and is used
312 // outside of the entry block for the function.
313 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
315 if (!isOnlyUsedInEntryBlock(AI))
316 InitializeRegForValue(AI);
318 // Initialize the mapping of values to registers. This is only set up for
319 // instruction values that are used outside of the block that defines
321 Function::iterator BB = Fn.begin(), EB = Fn.end();
322 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
323 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
324 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
325 const Type *Ty = AI->getAllocatedType();
326 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
328 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
331 TySize *= CUI->getZExtValue(); // Get total allocated size.
332 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
333 StaticAllocaMap[AI] =
334 MF.getFrameInfo()->CreateStackObject(TySize, Align);
337 for (; BB != EB; ++BB)
338 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
339 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
340 if (!isa<AllocaInst>(I) ||
341 !StaticAllocaMap.count(cast<AllocaInst>(I)))
342 InitializeRegForValue(I);
344 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
345 // also creates the initial PHI MachineInstrs, though none of the input
346 // operands are populated.
347 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
348 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
350 MF.getBasicBlockList().push_back(MBB);
352 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
355 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
356 if (PN->use_empty()) continue;
358 MVT::ValueType VT = TLI.getValueType(PN->getType());
359 unsigned NumRegisters = TLI.getNumRegisters(VT);
360 unsigned PHIReg = ValueMap[PN];
361 assert(PHIReg && "PHI node does not have an assigned virtual register!");
362 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
363 for (unsigned i = 0; i != NumRegisters; ++i)
364 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
369 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
370 /// the correctly promoted or expanded types. Assign these registers
371 /// consecutive vreg numbers and return the first assigned number.
372 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
373 SmallVector<MVT::ValueType, 4> ValueVTs;
374 ComputeValueVTs(TLI, V->getType(), ValueVTs);
376 unsigned FirstReg = 0;
377 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
378 MVT::ValueType ValueVT = ValueVTs[Value];
379 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
381 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
382 for (unsigned i = 0; i != NumRegs; ++i) {
383 unsigned R = MakeReg(RegisterVT);
384 if (!FirstReg) FirstReg = R;
390 //===----------------------------------------------------------------------===//
391 /// SelectionDAGLowering - This is the common target-independent lowering
392 /// implementation that is parameterized by a TargetLowering object.
393 /// Also, targets can overload any lowering method.
396 class SelectionDAGLowering {
397 MachineBasicBlock *CurMBB;
399 DenseMap<const Value*, SDOperand> NodeMap;
401 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
402 /// them up and then emit token factor nodes when possible. This allows us to
403 /// get simple disambiguation between loads without worrying about alias
405 std::vector<SDOperand> PendingLoads;
407 /// PendingExports - CopyToReg nodes that copy values to virtual registers
408 /// for export to other blocks need to be emitted before any terminator
409 /// instruction, but they have no other ordering requirements. We bunch them
410 /// up and the emit a single tokenfactor for them just before terminator
412 std::vector<SDOperand> PendingExports;
414 /// Case - A struct to record the Value for a switch case, and the
415 /// case's target basic block.
419 MachineBasicBlock* BB;
421 Case() : Low(0), High(0), BB(0) { }
422 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
423 Low(low), High(high), BB(bb) { }
424 uint64_t size() const {
425 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
426 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
427 return (rHigh - rLow + 1ULL);
433 MachineBasicBlock* BB;
436 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
437 Mask(mask), BB(bb), Bits(bits) { }
440 typedef std::vector<Case> CaseVector;
441 typedef std::vector<CaseBits> CaseBitsVector;
442 typedef CaseVector::iterator CaseItr;
443 typedef std::pair<CaseItr, CaseItr> CaseRange;
445 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
446 /// of conditional branches.
448 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
449 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
451 /// CaseBB - The MBB in which to emit the compare and branch
452 MachineBasicBlock *CaseBB;
453 /// LT, GE - If nonzero, we know the current case value must be less-than or
454 /// greater-than-or-equal-to these Constants.
457 /// Range - A pair of iterators representing the range of case values to be
458 /// processed at this point in the binary search tree.
462 typedef std::vector<CaseRec> CaseRecVector;
464 /// The comparison function for sorting the switch case values in the vector.
465 /// WARNING: Case ranges should be disjoint!
467 bool operator () (const Case& C1, const Case& C2) {
468 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
469 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
470 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
471 return CI1->getValue().slt(CI2->getValue());
476 bool operator () (const CaseBits& C1, const CaseBits& C2) {
477 return C1.Bits > C2.Bits;
481 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
484 // TLI - This is information that describes the available target features we
485 // need for lowering. This indicates when operations are unavailable,
486 // implemented with a libcall, etc.
489 const TargetData *TD;
492 /// SwitchCases - Vector of CaseBlock structures used to communicate
493 /// SwitchInst code generation information.
494 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
495 /// JTCases - Vector of JumpTable structures used to communicate
496 /// SwitchInst code generation information.
497 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
498 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
500 /// FuncInfo - Information about the function as a whole.
502 FunctionLoweringInfo &FuncInfo;
504 /// GCI - Garbage collection metadata for the function.
505 CollectorMetadata *GCI;
507 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
509 FunctionLoweringInfo &funcinfo,
510 CollectorMetadata *gci)
511 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
512 FuncInfo(funcinfo), GCI(gci) {
515 /// getRoot - Return the current virtual root of the Selection DAG,
516 /// flushing any PendingLoad items. This must be done before emitting
517 /// a store or any other node that may need to be ordered after any
518 /// prior load instructions.
520 SDOperand getRoot() {
521 if (PendingLoads.empty())
522 return DAG.getRoot();
524 if (PendingLoads.size() == 1) {
525 SDOperand Root = PendingLoads[0];
527 PendingLoads.clear();
531 // Otherwise, we have to make a token factor node.
532 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
533 &PendingLoads[0], PendingLoads.size());
534 PendingLoads.clear();
539 /// getControlRoot - Similar to getRoot, but instead of flushing all the
540 /// PendingLoad items, flush all the PendingExports items. It is necessary
541 /// to do this before emitting a terminator instruction.
543 SDOperand getControlRoot() {
544 SDOperand Root = DAG.getRoot();
546 if (PendingExports.empty())
549 // Turn all of the CopyToReg chains into one factored node.
550 if (Root.getOpcode() != ISD::EntryToken) {
551 unsigned i = 0, e = PendingExports.size();
552 for (; i != e; ++i) {
553 assert(PendingExports[i].Val->getNumOperands() > 1);
554 if (PendingExports[i].Val->getOperand(0) == Root)
555 break; // Don't add the root if we already indirectly depend on it.
559 PendingExports.push_back(Root);
562 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
564 PendingExports.size());
565 PendingExports.clear();
570 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
572 void visit(Instruction &I) { visit(I.getOpcode(), I); }
574 void visit(unsigned Opcode, User &I) {
575 // Note: this doesn't use InstVisitor, because it has to work with
576 // ConstantExpr's in addition to instructions.
578 default: assert(0 && "Unknown instruction type encountered!");
580 // Build the switch statement using the Instruction.def file.
581 #define HANDLE_INST(NUM, OPCODE, CLASS) \
582 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
583 #include "llvm/Instruction.def"
587 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
589 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
590 const Value *SV, SDOperand Root,
591 bool isVolatile, unsigned Alignment);
593 SDOperand getValue(const Value *V);
595 void setValue(const Value *V, SDOperand NewN) {
596 SDOperand &N = NodeMap[V];
597 assert(N.Val == 0 && "Already set a value for this node!");
601 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
602 std::set<unsigned> &OutputRegs,
603 std::set<unsigned> &InputRegs);
605 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
606 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
608 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
609 void ExportFromCurrentBlock(Value *V);
610 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
611 MachineBasicBlock *LandingPad = NULL);
613 // Terminator instructions.
614 void visitRet(ReturnInst &I);
615 void visitBr(BranchInst &I);
616 void visitSwitch(SwitchInst &I);
617 void visitUnreachable(UnreachableInst &I) { /* noop */ }
619 // Helpers for visitSwitch
620 bool handleSmallSwitchRange(CaseRec& CR,
621 CaseRecVector& WorkList,
623 MachineBasicBlock* Default);
624 bool handleJTSwitchCase(CaseRec& CR,
625 CaseRecVector& WorkList,
627 MachineBasicBlock* Default);
628 bool handleBTSplitSwitchCase(CaseRec& CR,
629 CaseRecVector& WorkList,
631 MachineBasicBlock* Default);
632 bool handleBitTestsSwitchCase(CaseRec& CR,
633 CaseRecVector& WorkList,
635 MachineBasicBlock* Default);
636 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
637 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
638 void visitBitTestCase(MachineBasicBlock* NextMBB,
640 SelectionDAGISel::BitTestCase &B);
641 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
642 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
643 SelectionDAGISel::JumpTableHeader &JTH);
645 // These all get lowered before this pass.
646 void visitInvoke(InvokeInst &I);
647 void visitUnwind(UnwindInst &I);
649 void visitBinary(User &I, unsigned OpCode);
650 void visitShift(User &I, unsigned Opcode);
651 void visitAdd(User &I) {
652 if (I.getType()->isFPOrFPVector())
653 visitBinary(I, ISD::FADD);
655 visitBinary(I, ISD::ADD);
657 void visitSub(User &I);
658 void visitMul(User &I) {
659 if (I.getType()->isFPOrFPVector())
660 visitBinary(I, ISD::FMUL);
662 visitBinary(I, ISD::MUL);
664 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
665 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
666 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
667 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
668 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
669 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
670 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
671 void visitOr (User &I) { visitBinary(I, ISD::OR); }
672 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
673 void visitShl (User &I) { visitShift(I, ISD::SHL); }
674 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
675 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
676 void visitICmp(User &I);
677 void visitFCmp(User &I);
678 // Visit the conversion instructions
679 void visitTrunc(User &I);
680 void visitZExt(User &I);
681 void visitSExt(User &I);
682 void visitFPTrunc(User &I);
683 void visitFPExt(User &I);
684 void visitFPToUI(User &I);
685 void visitFPToSI(User &I);
686 void visitUIToFP(User &I);
687 void visitSIToFP(User &I);
688 void visitPtrToInt(User &I);
689 void visitIntToPtr(User &I);
690 void visitBitCast(User &I);
692 void visitExtractElement(User &I);
693 void visitInsertElement(User &I);
694 void visitShuffleVector(User &I);
696 void visitGetElementPtr(User &I);
697 void visitSelect(User &I);
699 void visitMalloc(MallocInst &I);
700 void visitFree(FreeInst &I);
701 void visitAlloca(AllocaInst &I);
702 void visitLoad(LoadInst &I);
703 void visitStore(StoreInst &I);
704 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
705 void visitCall(CallInst &I);
706 void visitInlineAsm(CallSite CS);
707 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
708 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
710 void visitVAStart(CallInst &I);
711 void visitVAArg(VAArgInst &I);
712 void visitVAEnd(CallInst &I);
713 void visitVACopy(CallInst &I);
715 void visitGetResult(GetResultInst &I);
717 void visitUserOp1(Instruction &I) {
718 assert(0 && "UserOp1 should not exist at instruction selection time!");
721 void visitUserOp2(Instruction &I) {
722 assert(0 && "UserOp2 should not exist at instruction selection time!");
726 } // end namespace llvm
729 /// getCopyFromParts - Create a value that contains the specified legal parts
730 /// combined into the value they represent. If the parts combine to a type
731 /// larger then ValueVT then AssertOp can be used to specify whether the extra
732 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
733 /// (ISD::AssertSext).
734 static SDOperand getCopyFromParts(SelectionDAG &DAG,
735 const SDOperand *Parts,
737 MVT::ValueType PartVT,
738 MVT::ValueType ValueVT,
739 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
740 assert(NumParts > 0 && "No parts to assemble!");
741 TargetLowering &TLI = DAG.getTargetLoweringInfo();
742 SDOperand Val = Parts[0];
745 // Assemble the value from multiple parts.
746 if (!MVT::isVector(ValueVT)) {
747 unsigned PartBits = MVT::getSizeInBits(PartVT);
748 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
750 // Assemble the power of 2 part.
751 unsigned RoundParts = NumParts & (NumParts - 1) ?
752 1 << Log2_32(NumParts) : NumParts;
753 unsigned RoundBits = PartBits * RoundParts;
754 MVT::ValueType RoundVT = RoundBits == ValueBits ?
755 ValueVT : MVT::getIntegerType(RoundBits);
758 if (RoundParts > 2) {
759 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
760 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
761 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
767 if (TLI.isBigEndian())
769 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
771 if (RoundParts < NumParts) {
772 // Assemble the trailing non-power-of-2 part.
773 unsigned OddParts = NumParts - RoundParts;
774 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
775 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
777 // Combine the round and odd parts.
779 if (TLI.isBigEndian())
781 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
782 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
783 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
784 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
785 TLI.getShiftAmountTy()));
786 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
787 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
790 // Handle a multi-element vector.
791 MVT::ValueType IntermediateVT, RegisterVT;
792 unsigned NumIntermediates;
794 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
797 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
798 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
799 assert(RegisterVT == Parts[0].getValueType() &&
800 "Part type doesn't match part!");
802 // Assemble the parts into intermediate operands.
803 SmallVector<SDOperand, 8> Ops(NumIntermediates);
804 if (NumIntermediates == NumParts) {
805 // If the register was not expanded, truncate or copy the value,
807 for (unsigned i = 0; i != NumParts; ++i)
808 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
809 PartVT, IntermediateVT);
810 } else if (NumParts > 0) {
811 // If the intermediate type was expanded, build the intermediate operands
813 assert(NumParts % NumIntermediates == 0 &&
814 "Must expand into a divisible number of parts!");
815 unsigned Factor = NumParts / NumIntermediates;
816 for (unsigned i = 0; i != NumIntermediates; ++i)
817 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
818 PartVT, IntermediateVT);
821 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
823 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
824 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
825 ValueVT, &Ops[0], NumIntermediates);
829 // There is now one part, held in Val. Correct it to match ValueVT.
830 PartVT = Val.getValueType();
832 if (PartVT == ValueVT)
835 if (MVT::isVector(PartVT)) {
836 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
837 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
840 if (MVT::isVector(ValueVT)) {
841 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
842 MVT::getVectorNumElements(ValueVT) == 1 &&
843 "Only trivial scalar-to-vector conversions should get here!");
844 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
847 if (MVT::isInteger(PartVT) &&
848 MVT::isInteger(ValueVT)) {
849 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
850 // For a truncate, see if we have any information to
851 // indicate whether the truncated bits will always be
852 // zero or sign-extension.
853 if (AssertOp != ISD::DELETED_NODE)
854 Val = DAG.getNode(AssertOp, PartVT, Val,
855 DAG.getValueType(ValueVT));
856 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
858 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
862 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
863 if (ValueVT < Val.getValueType())
864 // FP_ROUND's are always exact here.
865 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
866 DAG.getIntPtrConstant(1));
867 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
870 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
871 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
873 assert(0 && "Unknown mismatch!");
877 /// getCopyToParts - Create a series of nodes that contain the specified value
878 /// split into legal parts. If the parts contain more bits than Val, then, for
879 /// integers, ExtendKind can be used to specify how to generate the extra bits.
880 static void getCopyToParts(SelectionDAG &DAG,
884 MVT::ValueType PartVT,
885 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
886 TargetLowering &TLI = DAG.getTargetLoweringInfo();
887 MVT::ValueType PtrVT = TLI.getPointerTy();
888 MVT::ValueType ValueVT = Val.getValueType();
889 unsigned PartBits = MVT::getSizeInBits(PartVT);
890 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
895 if (!MVT::isVector(ValueVT)) {
896 if (PartVT == ValueVT) {
897 assert(NumParts == 1 && "No-op copy with multiple parts!");
902 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
903 // If the parts cover more bits than the value has, promote the value.
904 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
905 assert(NumParts == 1 && "Do not know what to promote to!");
906 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
907 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
908 ValueVT = MVT::getIntegerType(NumParts * PartBits);
909 Val = DAG.getNode(ExtendKind, ValueVT, Val);
911 assert(0 && "Unknown mismatch!");
913 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
914 // Different types of the same size.
915 assert(NumParts == 1 && PartVT != ValueVT);
916 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
917 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
918 // If the parts cover less bits than value has, truncate the value.
919 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
920 ValueVT = MVT::getIntegerType(NumParts * PartBits);
921 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
923 assert(0 && "Unknown mismatch!");
927 // The value may have changed - recompute ValueVT.
928 ValueVT = Val.getValueType();
929 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
930 "Failed to tile the value with PartVT!");
933 assert(PartVT == ValueVT && "Type conversion failed!");
938 // Expand the value into multiple parts.
939 if (NumParts & (NumParts - 1)) {
940 // The number of parts is not a power of 2. Split off and copy the tail.
941 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
942 "Do not know what to expand to!");
943 unsigned RoundParts = 1 << Log2_32(NumParts);
944 unsigned RoundBits = RoundParts * PartBits;
945 unsigned OddParts = NumParts - RoundParts;
946 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
947 DAG.getConstant(RoundBits,
948 TLI.getShiftAmountTy()));
949 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
950 if (TLI.isBigEndian())
951 // The odd parts were reversed by getCopyToParts - unreverse them.
952 std::reverse(Parts + RoundParts, Parts + NumParts);
953 NumParts = RoundParts;
954 ValueVT = MVT::getIntegerType(NumParts * PartBits);
955 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
958 // The number of parts is a power of 2. Repeatedly bisect the value using
960 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
961 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
963 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
964 for (unsigned i = 0; i < NumParts; i += StepSize) {
965 unsigned ThisBits = StepSize * PartBits / 2;
966 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
967 SDOperand &Part0 = Parts[i];
968 SDOperand &Part1 = Parts[i+StepSize/2];
970 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
971 DAG.getConstant(1, PtrVT));
972 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
973 DAG.getConstant(0, PtrVT));
975 if (ThisBits == PartBits && ThisVT != PartVT) {
976 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
977 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
982 if (TLI.isBigEndian())
983 std::reverse(Parts, Parts + NumParts);
990 if (PartVT != ValueVT) {
991 if (MVT::isVector(PartVT)) {
992 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
994 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
995 MVT::getVectorNumElements(ValueVT) == 1 &&
996 "Only trivial vector-to-scalar conversions should get here!");
997 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
998 DAG.getConstant(0, PtrVT));
1006 // Handle a multi-element vector.
1007 MVT::ValueType IntermediateVT, RegisterVT;
1008 unsigned NumIntermediates;
1010 DAG.getTargetLoweringInfo()
1011 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1013 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1015 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1016 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1018 // Split the vector into intermediate operands.
1019 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1020 for (unsigned i = 0; i != NumIntermediates; ++i)
1021 if (MVT::isVector(IntermediateVT))
1022 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1023 IntermediateVT, Val,
1024 DAG.getConstant(i * (NumElements / NumIntermediates),
1027 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1028 IntermediateVT, Val,
1029 DAG.getConstant(i, PtrVT));
1031 // Split the intermediate operands into legal parts.
1032 if (NumParts == NumIntermediates) {
1033 // If the register was not expanded, promote or copy the value,
1035 for (unsigned i = 0; i != NumParts; ++i)
1036 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1037 } else if (NumParts > 0) {
1038 // If the intermediate type was expanded, split each the value into
1040 assert(NumParts % NumIntermediates == 0 &&
1041 "Must expand into a divisible number of parts!");
1042 unsigned Factor = NumParts / NumIntermediates;
1043 for (unsigned i = 0; i != NumIntermediates; ++i)
1044 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1049 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1050 SDOperand &N = NodeMap[V];
1051 if (N.Val) return N;
1053 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1054 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
1056 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1057 return N = DAG.getConstant(CI->getValue(), VT);
1059 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1060 return N = DAG.getGlobalAddress(GV, VT);
1062 if (isa<ConstantPointerNull>(C))
1063 return N = DAG.getConstant(0, TLI.getPointerTy());
1065 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1066 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1068 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1069 return N = DAG.getNode(ISD::UNDEF, VT);
1071 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1072 visit(CE->getOpcode(), *CE);
1073 SDOperand N1 = NodeMap[V];
1074 assert(N1.Val && "visit didn't populate the ValueMap!");
1078 const VectorType *VecTy = cast<VectorType>(V->getType());
1079 unsigned NumElements = VecTy->getNumElements();
1081 // Now that we know the number and type of the elements, get that number of
1082 // elements into the Ops array based on what kind of constant it is.
1083 SmallVector<SDOperand, 16> Ops;
1084 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1085 for (unsigned i = 0; i != NumElements; ++i)
1086 Ops.push_back(getValue(CP->getOperand(i)));
1088 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1089 "Unknown vector constant!");
1090 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1093 if (isa<UndefValue>(C))
1094 Op = DAG.getNode(ISD::UNDEF, EltVT);
1095 else if (MVT::isFloatingPoint(EltVT))
1096 Op = DAG.getConstantFP(0, EltVT);
1098 Op = DAG.getConstant(0, EltVT);
1099 Ops.assign(NumElements, Op);
1102 // Create a BUILD_VECTOR node.
1103 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1106 // If this is a static alloca, generate it as the frameindex instead of
1108 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1109 std::map<const AllocaInst*, int>::iterator SI =
1110 FuncInfo.StaticAllocaMap.find(AI);
1111 if (SI != FuncInfo.StaticAllocaMap.end())
1112 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1115 unsigned InReg = FuncInfo.ValueMap[V];
1116 assert(InReg && "Value not in map!");
1118 RegsForValue RFV(TLI, InReg, V->getType());
1119 SDOperand Chain = DAG.getEntryNode();
1120 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1124 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1125 if (I.getNumOperands() == 0) {
1126 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1130 SmallVector<SDOperand, 8> NewValues;
1131 NewValues.push_back(getControlRoot());
1132 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1133 SDOperand RetOp = getValue(I.getOperand(i));
1134 MVT::ValueType VT = RetOp.getValueType();
1136 // FIXME: C calling convention requires the return type to be promoted to
1137 // at least 32-bit. But this is not necessary for non-C calling conventions.
1138 if (MVT::isInteger(VT)) {
1139 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1140 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1144 unsigned NumParts = TLI.getNumRegisters(VT);
1145 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1146 SmallVector<SDOperand, 4> Parts(NumParts);
1147 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1149 const Function *F = I.getParent()->getParent();
1150 if (F->paramHasAttr(0, ParamAttr::SExt))
1151 ExtendKind = ISD::SIGN_EXTEND;
1152 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1153 ExtendKind = ISD::ZERO_EXTEND;
1155 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1157 for (unsigned i = 0; i < NumParts; ++i) {
1158 NewValues.push_back(Parts[i]);
1159 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1162 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1163 &NewValues[0], NewValues.size()));
1166 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1167 /// the current basic block, add it to ValueMap now so that we'll get a
1169 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1170 // No need to export constants.
1171 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1173 // Already exported?
1174 if (FuncInfo.isExportedInst(V)) return;
1176 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1177 CopyValueToVirtualRegister(V, Reg);
1180 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1181 const BasicBlock *FromBB) {
1182 // The operands of the setcc have to be in this block. We don't know
1183 // how to export them from some other block.
1184 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1185 // Can export from current BB.
1186 if (VI->getParent() == FromBB)
1189 // Is already exported, noop.
1190 return FuncInfo.isExportedInst(V);
1193 // If this is an argument, we can export it if the BB is the entry block or
1194 // if it is already exported.
1195 if (isa<Argument>(V)) {
1196 if (FromBB == &FromBB->getParent()->getEntryBlock())
1199 // Otherwise, can only export this if it is already exported.
1200 return FuncInfo.isExportedInst(V);
1203 // Otherwise, constants can always be exported.
1207 static bool InBlock(const Value *V, const BasicBlock *BB) {
1208 if (const Instruction *I = dyn_cast<Instruction>(V))
1209 return I->getParent() == BB;
1213 /// FindMergedConditions - If Cond is an expression like
1214 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1215 MachineBasicBlock *TBB,
1216 MachineBasicBlock *FBB,
1217 MachineBasicBlock *CurBB,
1219 // If this node is not part of the or/and tree, emit it as a branch.
1220 Instruction *BOp = dyn_cast<Instruction>(Cond);
1222 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1223 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1224 BOp->getParent() != CurBB->getBasicBlock() ||
1225 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1226 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1227 const BasicBlock *BB = CurBB->getBasicBlock();
1229 // If the leaf of the tree is a comparison, merge the condition into
1231 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1232 // The operands of the cmp have to be in this block. We don't know
1233 // how to export them from some other block. If this is the first block
1234 // of the sequence, no exporting is needed.
1236 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1237 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1238 BOp = cast<Instruction>(Cond);
1239 ISD::CondCode Condition;
1240 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1241 switch (IC->getPredicate()) {
1242 default: assert(0 && "Unknown icmp predicate opcode!");
1243 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1244 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1245 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1246 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1247 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1248 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1249 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1250 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1251 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1252 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1254 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1255 ISD::CondCode FPC, FOC;
1256 switch (FC->getPredicate()) {
1257 default: assert(0 && "Unknown fcmp predicate opcode!");
1258 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1259 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1260 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1261 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1262 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1263 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1264 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1265 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1266 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1267 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1268 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1269 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1270 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1271 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1272 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1273 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1275 if (FiniteOnlyFPMath())
1280 Condition = ISD::SETEQ; // silence warning.
1281 assert(0 && "Unknown compare instruction");
1284 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1285 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1286 SwitchCases.push_back(CB);
1290 // Create a CaseBlock record representing this branch.
1291 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1292 NULL, TBB, FBB, CurBB);
1293 SwitchCases.push_back(CB);
1298 // Create TmpBB after CurBB.
1299 MachineFunction::iterator BBI = CurBB;
1300 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1301 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1303 if (Opc == Instruction::Or) {
1304 // Codegen X | Y as:
1312 // Emit the LHS condition.
1313 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1315 // Emit the RHS condition into TmpBB.
1316 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1318 assert(Opc == Instruction::And && "Unknown merge op!");
1319 // Codegen X & Y as:
1326 // This requires creation of TmpBB after CurBB.
1328 // Emit the LHS condition.
1329 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1331 // Emit the RHS condition into TmpBB.
1332 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1336 /// If the set of cases should be emitted as a series of branches, return true.
1337 /// If we should emit this as a bunch of and/or'd together conditions, return
1340 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1341 if (Cases.size() != 2) return true;
1343 // If this is two comparisons of the same values or'd or and'd together, they
1344 // will get folded into a single comparison, so don't emit two blocks.
1345 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1346 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1347 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1348 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1355 void SelectionDAGLowering::visitBr(BranchInst &I) {
1356 // Update machine-CFG edges.
1357 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1359 // Figure out which block is immediately after the current one.
1360 MachineBasicBlock *NextBlock = 0;
1361 MachineFunction::iterator BBI = CurMBB;
1362 if (++BBI != CurMBB->getParent()->end())
1365 if (I.isUnconditional()) {
1366 // If this is not a fall-through branch, emit the branch.
1367 if (Succ0MBB != NextBlock)
1368 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1369 DAG.getBasicBlock(Succ0MBB)));
1371 // Update machine-CFG edges.
1372 CurMBB->addSuccessor(Succ0MBB);
1376 // If this condition is one of the special cases we handle, do special stuff
1378 Value *CondVal = I.getCondition();
1379 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1381 // If this is a series of conditions that are or'd or and'd together, emit
1382 // this as a sequence of branches instead of setcc's with and/or operations.
1383 // For example, instead of something like:
1396 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1397 if (BOp->hasOneUse() &&
1398 (BOp->getOpcode() == Instruction::And ||
1399 BOp->getOpcode() == Instruction::Or)) {
1400 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1401 // If the compares in later blocks need to use values not currently
1402 // exported from this block, export them now. This block should always
1403 // be the first entry.
1404 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1406 // Allow some cases to be rejected.
1407 if (ShouldEmitAsBranches(SwitchCases)) {
1408 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1409 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1410 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1413 // Emit the branch for this block.
1414 visitSwitchCase(SwitchCases[0]);
1415 SwitchCases.erase(SwitchCases.begin());
1419 // Okay, we decided not to do this, remove any inserted MBB's and clear
1421 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1422 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1424 SwitchCases.clear();
1428 // Create a CaseBlock record representing this branch.
1429 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1430 NULL, Succ0MBB, Succ1MBB, CurMBB);
1431 // Use visitSwitchCase to actually insert the fast branch sequence for this
1433 visitSwitchCase(CB);
1436 /// visitSwitchCase - Emits the necessary code to represent a single node in
1437 /// the binary search tree resulting from lowering a switch instruction.
1438 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1440 SDOperand CondLHS = getValue(CB.CmpLHS);
1442 // Build the setcc now.
1443 if (CB.CmpMHS == NULL) {
1444 // Fold "(X == true)" to X and "(X == false)" to !X to
1445 // handle common cases produced by branch lowering.
1446 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1448 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1449 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1450 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1452 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1454 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1456 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1457 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1459 SDOperand CmpOp = getValue(CB.CmpMHS);
1460 MVT::ValueType VT = CmpOp.getValueType();
1462 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1463 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1465 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1466 Cond = DAG.getSetCC(MVT::i1, SUB,
1467 DAG.getConstant(High-Low, VT), ISD::SETULE);
1472 // Set NextBlock to be the MBB immediately after the current one, if any.
1473 // This is used to avoid emitting unnecessary branches to the next block.
1474 MachineBasicBlock *NextBlock = 0;
1475 MachineFunction::iterator BBI = CurMBB;
1476 if (++BBI != CurMBB->getParent()->end())
1479 // If the lhs block is the next block, invert the condition so that we can
1480 // fall through to the lhs instead of the rhs block.
1481 if (CB.TrueBB == NextBlock) {
1482 std::swap(CB.TrueBB, CB.FalseBB);
1483 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1484 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1486 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1487 DAG.getBasicBlock(CB.TrueBB));
1488 if (CB.FalseBB == NextBlock)
1489 DAG.setRoot(BrCond);
1491 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1492 DAG.getBasicBlock(CB.FalseBB)));
1493 // Update successor info
1494 CurMBB->addSuccessor(CB.TrueBB);
1495 CurMBB->addSuccessor(CB.FalseBB);
1498 /// visitJumpTable - Emit JumpTable node in the current MBB
1499 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1500 // Emit the code for the jump table
1501 assert(JT.Reg != -1U && "Should lower JT Header first!");
1502 MVT::ValueType PTy = TLI.getPointerTy();
1503 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1504 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1505 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1510 /// visitJumpTableHeader - This function emits necessary code to produce index
1511 /// in the JumpTable from switch case.
1512 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1513 SelectionDAGISel::JumpTableHeader &JTH) {
1514 // Subtract the lowest switch case value from the value being switched on
1515 // and conditional branch to default mbb if the result is greater than the
1516 // difference between smallest and largest cases.
1517 SDOperand SwitchOp = getValue(JTH.SValue);
1518 MVT::ValueType VT = SwitchOp.getValueType();
1519 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1520 DAG.getConstant(JTH.First, VT));
1522 // The SDNode we just created, which holds the value being switched on
1523 // minus the the smallest case value, needs to be copied to a virtual
1524 // register so it can be used as an index into the jump table in a
1525 // subsequent basic block. This value may be smaller or larger than the
1526 // target's pointer type, and therefore require extension or truncating.
1527 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1528 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1530 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1532 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1533 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1534 JT.Reg = JumpTableReg;
1536 // Emit the range check for the jump table, and branch to the default
1537 // block for the switch statement if the value being switched on exceeds
1538 // the largest case in the switch.
1539 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1540 DAG.getConstant(JTH.Last-JTH.First,VT),
1543 // Set NextBlock to be the MBB immediately after the current one, if any.
1544 // This is used to avoid emitting unnecessary branches to the next block.
1545 MachineBasicBlock *NextBlock = 0;
1546 MachineFunction::iterator BBI = CurMBB;
1547 if (++BBI != CurMBB->getParent()->end())
1550 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1551 DAG.getBasicBlock(JT.Default));
1553 if (JT.MBB == NextBlock)
1554 DAG.setRoot(BrCond);
1556 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1557 DAG.getBasicBlock(JT.MBB)));
1562 /// visitBitTestHeader - This function emits necessary code to produce value
1563 /// suitable for "bit tests"
1564 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1565 // Subtract the minimum value
1566 SDOperand SwitchOp = getValue(B.SValue);
1567 MVT::ValueType VT = SwitchOp.getValueType();
1568 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1569 DAG.getConstant(B.First, VT));
1572 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1573 DAG.getConstant(B.Range, VT),
1577 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1578 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1580 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1582 // Make desired shift
1583 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1584 DAG.getConstant(1, TLI.getPointerTy()),
1587 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1588 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1591 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1592 DAG.getBasicBlock(B.Default));
1594 // Set NextBlock to be the MBB immediately after the current one, if any.
1595 // This is used to avoid emitting unnecessary branches to the next block.
1596 MachineBasicBlock *NextBlock = 0;
1597 MachineFunction::iterator BBI = CurMBB;
1598 if (++BBI != CurMBB->getParent()->end())
1601 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1602 if (MBB == NextBlock)
1603 DAG.setRoot(BrRange);
1605 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1606 DAG.getBasicBlock(MBB)));
1608 CurMBB->addSuccessor(B.Default);
1609 CurMBB->addSuccessor(MBB);
1614 /// visitBitTestCase - this function produces one "bit test"
1615 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1617 SelectionDAGISel::BitTestCase &B) {
1618 // Emit bit tests and jumps
1619 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1621 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1623 DAG.getConstant(B.Mask,
1624 TLI.getPointerTy()));
1625 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1626 DAG.getConstant(0, TLI.getPointerTy()),
1628 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1629 AndCmp, DAG.getBasicBlock(B.TargetBB));
1631 // Set NextBlock to be the MBB immediately after the current one, if any.
1632 // This is used to avoid emitting unnecessary branches to the next block.
1633 MachineBasicBlock *NextBlock = 0;
1634 MachineFunction::iterator BBI = CurMBB;
1635 if (++BBI != CurMBB->getParent()->end())
1638 if (NextMBB == NextBlock)
1641 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1642 DAG.getBasicBlock(NextMBB)));
1644 CurMBB->addSuccessor(B.TargetBB);
1645 CurMBB->addSuccessor(NextMBB);
1650 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1651 // Retrieve successors.
1652 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1653 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1655 if (isa<InlineAsm>(I.getCalledValue()))
1658 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1660 // If the value of the invoke is used outside of its defining block, make it
1661 // available as a virtual register.
1662 if (!I.use_empty()) {
1663 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1664 if (VMI != FuncInfo.ValueMap.end())
1665 CopyValueToVirtualRegister(&I, VMI->second);
1668 // Drop into normal successor.
1669 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1670 DAG.getBasicBlock(Return)));
1672 // Update successor info
1673 CurMBB->addSuccessor(Return);
1674 CurMBB->addSuccessor(LandingPad);
1677 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1680 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1681 /// small case ranges).
1682 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1683 CaseRecVector& WorkList,
1685 MachineBasicBlock* Default) {
1686 Case& BackCase = *(CR.Range.second-1);
1688 // Size is the number of Cases represented by this range.
1689 unsigned Size = CR.Range.second - CR.Range.first;
1693 // Get the MachineFunction which holds the current MBB. This is used when
1694 // inserting any additional MBBs necessary to represent the switch.
1695 MachineFunction *CurMF = CurMBB->getParent();
1697 // Figure out which block is immediately after the current one.
1698 MachineBasicBlock *NextBlock = 0;
1699 MachineFunction::iterator BBI = CR.CaseBB;
1701 if (++BBI != CurMBB->getParent()->end())
1704 // TODO: If any two of the cases has the same destination, and if one value
1705 // is the same as the other, but has one bit unset that the other has set,
1706 // use bit manipulation to do two compares at once. For example:
1707 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1709 // Rearrange the case blocks so that the last one falls through if possible.
1710 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1711 // The last case block won't fall through into 'NextBlock' if we emit the
1712 // branches in this order. See if rearranging a case value would help.
1713 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1714 if (I->BB == NextBlock) {
1715 std::swap(*I, BackCase);
1721 // Create a CaseBlock record representing a conditional branch to
1722 // the Case's target mbb if the value being switched on SV is equal
1724 MachineBasicBlock *CurBlock = CR.CaseBB;
1725 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1726 MachineBasicBlock *FallThrough;
1728 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1729 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1731 // If the last case doesn't match, go to the default block.
1732 FallThrough = Default;
1735 Value *RHS, *LHS, *MHS;
1737 if (I->High == I->Low) {
1738 // This is just small small case range :) containing exactly 1 case
1740 LHS = SV; RHS = I->High; MHS = NULL;
1743 LHS = I->Low; MHS = SV; RHS = I->High;
1745 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1746 I->BB, FallThrough, CurBlock);
1748 // If emitting the first comparison, just call visitSwitchCase to emit the
1749 // code into the current block. Otherwise, push the CaseBlock onto the
1750 // vector to be later processed by SDISel, and insert the node's MBB
1751 // before the next MBB.
1752 if (CurBlock == CurMBB)
1753 visitSwitchCase(CB);
1755 SwitchCases.push_back(CB);
1757 CurBlock = FallThrough;
1763 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1764 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1765 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1768 /// handleJTSwitchCase - Emit jumptable for current switch case range
1769 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1770 CaseRecVector& WorkList,
1772 MachineBasicBlock* Default) {
1773 Case& FrontCase = *CR.Range.first;
1774 Case& BackCase = *(CR.Range.second-1);
1776 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1777 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1780 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1784 if (!areJTsAllowed(TLI) || TSize <= 3)
1787 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1791 DOUT << "Lowering jump table\n"
1792 << "First entry: " << First << ". Last entry: " << Last << "\n"
1793 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1795 // Get the MachineFunction which holds the current MBB. This is used when
1796 // inserting any additional MBBs necessary to represent the switch.
1797 MachineFunction *CurMF = CurMBB->getParent();
1799 // Figure out which block is immediately after the current one.
1800 MachineBasicBlock *NextBlock = 0;
1801 MachineFunction::iterator BBI = CR.CaseBB;
1803 if (++BBI != CurMBB->getParent()->end())
1806 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1808 // Create a new basic block to hold the code for loading the address
1809 // of the jump table, and jumping to it. Update successor information;
1810 // we will either branch to the default case for the switch, or the jump
1812 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1813 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1814 CR.CaseBB->addSuccessor(Default);
1815 CR.CaseBB->addSuccessor(JumpTableBB);
1817 // Build a vector of destination BBs, corresponding to each target
1818 // of the jump table. If the value of the jump table slot corresponds to
1819 // a case statement, push the case's BB onto the vector, otherwise, push
1821 std::vector<MachineBasicBlock*> DestBBs;
1822 int64_t TEI = First;
1823 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1824 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1825 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1827 if ((Low <= TEI) && (TEI <= High)) {
1828 DestBBs.push_back(I->BB);
1832 DestBBs.push_back(Default);
1836 // Update successor info. Add one edge to each unique successor.
1837 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1838 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1839 E = DestBBs.end(); I != E; ++I) {
1840 if (!SuccsHandled[(*I)->getNumber()]) {
1841 SuccsHandled[(*I)->getNumber()] = true;
1842 JumpTableBB->addSuccessor(*I);
1846 // Create a jump table index for this jump table, or return an existing
1848 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1850 // Set the jump table information so that we can codegen it as a second
1851 // MachineBasicBlock
1852 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1853 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1854 (CR.CaseBB == CurMBB));
1855 if (CR.CaseBB == CurMBB)
1856 visitJumpTableHeader(JT, JTH);
1858 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1863 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1865 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1866 CaseRecVector& WorkList,
1868 MachineBasicBlock* Default) {
1869 // Get the MachineFunction which holds the current MBB. This is used when
1870 // inserting any additional MBBs necessary to represent the switch.
1871 MachineFunction *CurMF = CurMBB->getParent();
1873 // Figure out which block is immediately after the current one.
1874 MachineBasicBlock *NextBlock = 0;
1875 MachineFunction::iterator BBI = CR.CaseBB;
1877 if (++BBI != CurMBB->getParent()->end())
1880 Case& FrontCase = *CR.Range.first;
1881 Case& BackCase = *(CR.Range.second-1);
1882 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1884 // Size is the number of Cases represented by this range.
1885 unsigned Size = CR.Range.second - CR.Range.first;
1887 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1888 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1890 CaseItr Pivot = CR.Range.first + Size/2;
1892 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1893 // (heuristically) allow us to emit JumpTable's later.
1895 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1899 uint64_t LSize = FrontCase.size();
1900 uint64_t RSize = TSize-LSize;
1901 DOUT << "Selecting best pivot: \n"
1902 << "First: " << First << ", Last: " << Last <<"\n"
1903 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1904 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1906 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1907 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1908 assert((RBegin-LEnd>=1) && "Invalid case distance");
1909 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1910 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1911 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1912 // Should always split in some non-trivial place
1914 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1915 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1916 << "Metric: " << Metric << "\n";
1917 if (FMetric < Metric) {
1920 DOUT << "Current metric set to: " << FMetric << "\n";
1926 if (areJTsAllowed(TLI)) {
1927 // If our case is dense we *really* should handle it earlier!
1928 assert((FMetric > 0) && "Should handle dense range earlier!");
1930 Pivot = CR.Range.first + Size/2;
1933 CaseRange LHSR(CR.Range.first, Pivot);
1934 CaseRange RHSR(Pivot, CR.Range.second);
1935 Constant *C = Pivot->Low;
1936 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1938 // We know that we branch to the LHS if the Value being switched on is
1939 // less than the Pivot value, C. We use this to optimize our binary
1940 // tree a bit, by recognizing that if SV is greater than or equal to the
1941 // LHS's Case Value, and that Case Value is exactly one less than the
1942 // Pivot's Value, then we can branch directly to the LHS's Target,
1943 // rather than creating a leaf node for it.
1944 if ((LHSR.second - LHSR.first) == 1 &&
1945 LHSR.first->High == CR.GE &&
1946 cast<ConstantInt>(C)->getSExtValue() ==
1947 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1948 TrueBB = LHSR.first->BB;
1950 TrueBB = new MachineBasicBlock(LLVMBB);
1951 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1952 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1955 // Similar to the optimization above, if the Value being switched on is
1956 // known to be less than the Constant CR.LT, and the current Case Value
1957 // is CR.LT - 1, then we can branch directly to the target block for
1958 // the current Case Value, rather than emitting a RHS leaf node for it.
1959 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1960 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1961 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1962 FalseBB = RHSR.first->BB;
1964 FalseBB = new MachineBasicBlock(LLVMBB);
1965 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1966 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1969 // Create a CaseBlock record representing a conditional branch to
1970 // the LHS node if the value being switched on SV is less than C.
1971 // Otherwise, branch to LHS.
1972 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1973 TrueBB, FalseBB, CR.CaseBB);
1975 if (CR.CaseBB == CurMBB)
1976 visitSwitchCase(CB);
1978 SwitchCases.push_back(CB);
1983 /// handleBitTestsSwitchCase - if current case range has few destination and
1984 /// range span less, than machine word bitwidth, encode case range into series
1985 /// of masks and emit bit tests with these masks.
1986 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1987 CaseRecVector& WorkList,
1989 MachineBasicBlock* Default){
1990 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1992 Case& FrontCase = *CR.Range.first;
1993 Case& BackCase = *(CR.Range.second-1);
1995 // Get the MachineFunction which holds the current MBB. This is used when
1996 // inserting any additional MBBs necessary to represent the switch.
1997 MachineFunction *CurMF = CurMBB->getParent();
1999 unsigned numCmps = 0;
2000 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2002 // Single case counts one, case range - two.
2003 if (I->Low == I->High)
2009 // Count unique destinations
2010 SmallSet<MachineBasicBlock*, 4> Dests;
2011 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2012 Dests.insert(I->BB);
2013 if (Dests.size() > 3)
2014 // Don't bother the code below, if there are too much unique destinations
2017 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2018 << "Total number of comparisons: " << numCmps << "\n";
2020 // Compute span of values.
2021 Constant* minValue = FrontCase.Low;
2022 Constant* maxValue = BackCase.High;
2023 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2024 cast<ConstantInt>(minValue)->getSExtValue();
2025 DOUT << "Compare range: " << range << "\n"
2026 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2027 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2029 if (range>=IntPtrBits ||
2030 (!(Dests.size() == 1 && numCmps >= 3) &&
2031 !(Dests.size() == 2 && numCmps >= 5) &&
2032 !(Dests.size() >= 3 && numCmps >= 6)))
2035 DOUT << "Emitting bit tests\n";
2036 int64_t lowBound = 0;
2038 // Optimize the case where all the case values fit in a
2039 // word without having to subtract minValue. In this case,
2040 // we can optimize away the subtraction.
2041 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2042 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2043 range = cast<ConstantInt>(maxValue)->getSExtValue();
2045 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2048 CaseBitsVector CasesBits;
2049 unsigned i, count = 0;
2051 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2052 MachineBasicBlock* Dest = I->BB;
2053 for (i = 0; i < count; ++i)
2054 if (Dest == CasesBits[i].BB)
2058 assert((count < 3) && "Too much destinations to test!");
2059 CasesBits.push_back(CaseBits(0, Dest, 0));
2063 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2064 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2066 for (uint64_t j = lo; j <= hi; j++) {
2067 CasesBits[i].Mask |= 1ULL << j;
2068 CasesBits[i].Bits++;
2072 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2074 SelectionDAGISel::BitTestInfo BTC;
2076 // Figure out which block is immediately after the current one.
2077 MachineFunction::iterator BBI = CR.CaseBB;
2080 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2083 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2084 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2085 << ", BB: " << CasesBits[i].BB << "\n";
2087 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2088 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2089 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2094 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2095 -1U, (CR.CaseBB == CurMBB),
2096 CR.CaseBB, Default, BTC);
2098 if (CR.CaseBB == CurMBB)
2099 visitBitTestHeader(BTB);
2101 BitTestCases.push_back(BTB);
2107 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2108 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2109 const SwitchInst& SI) {
2110 unsigned numCmps = 0;
2112 // Start with "simple" cases
2113 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2114 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2115 Cases.push_back(Case(SI.getSuccessorValue(i),
2116 SI.getSuccessorValue(i),
2119 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2121 // Merge case into clusters
2122 if (Cases.size()>=2)
2123 // Must recompute end() each iteration because it may be
2124 // invalidated by erase if we hold on to it
2125 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2126 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2127 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2128 MachineBasicBlock* nextBB = J->BB;
2129 MachineBasicBlock* currentBB = I->BB;
2131 // If the two neighboring cases go to the same destination, merge them
2132 // into a single case.
2133 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2141 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2142 if (I->Low != I->High)
2143 // A range counts double, since it requires two compares.
2150 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2151 // Figure out which block is immediately after the current one.
2152 MachineBasicBlock *NextBlock = 0;
2153 MachineFunction::iterator BBI = CurMBB;
2155 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2157 // If there is only the default destination, branch to it if it is not the
2158 // next basic block. Otherwise, just fall through.
2159 if (SI.getNumOperands() == 2) {
2160 // Update machine-CFG edges.
2162 // If this is not a fall-through branch, emit the branch.
2163 if (Default != NextBlock)
2164 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2165 DAG.getBasicBlock(Default)));
2167 CurMBB->addSuccessor(Default);
2171 // If there are any non-default case statements, create a vector of Cases
2172 // representing each one, and sort the vector so that we can efficiently
2173 // create a binary search tree from them.
2175 unsigned numCmps = Clusterify(Cases, SI);
2176 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2177 << ". Total compares: " << numCmps << "\n";
2179 // Get the Value to be switched on and default basic blocks, which will be
2180 // inserted into CaseBlock records, representing basic blocks in the binary
2182 Value *SV = SI.getOperand(0);
2184 // Push the initial CaseRec onto the worklist
2185 CaseRecVector WorkList;
2186 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2188 while (!WorkList.empty()) {
2189 // Grab a record representing a case range to process off the worklist
2190 CaseRec CR = WorkList.back();
2191 WorkList.pop_back();
2193 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2196 // If the range has few cases (two or less) emit a series of specific
2198 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2201 // If the switch has more than 5 blocks, and at least 40% dense, and the
2202 // target supports indirect branches, then emit a jump table rather than
2203 // lowering the switch to a binary tree of conditional branches.
2204 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2207 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2208 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2209 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2214 void SelectionDAGLowering::visitSub(User &I) {
2215 // -0.0 - X --> fneg
2216 const Type *Ty = I.getType();
2217 if (isa<VectorType>(Ty)) {
2218 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2219 const VectorType *DestTy = cast<VectorType>(I.getType());
2220 const Type *ElTy = DestTy->getElementType();
2221 if (ElTy->isFloatingPoint()) {
2222 unsigned VL = DestTy->getNumElements();
2223 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2224 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2226 SDOperand Op2 = getValue(I.getOperand(1));
2227 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2233 if (Ty->isFloatingPoint()) {
2234 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2235 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2236 SDOperand Op2 = getValue(I.getOperand(1));
2237 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2242 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2245 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2246 SDOperand Op1 = getValue(I.getOperand(0));
2247 SDOperand Op2 = getValue(I.getOperand(1));
2249 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2252 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2253 SDOperand Op1 = getValue(I.getOperand(0));
2254 SDOperand Op2 = getValue(I.getOperand(1));
2256 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2257 MVT::getSizeInBits(Op2.getValueType()))
2258 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2259 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2260 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2262 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2265 void SelectionDAGLowering::visitICmp(User &I) {
2266 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2267 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2268 predicate = IC->getPredicate();
2269 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2270 predicate = ICmpInst::Predicate(IC->getPredicate());
2271 SDOperand Op1 = getValue(I.getOperand(0));
2272 SDOperand Op2 = getValue(I.getOperand(1));
2273 ISD::CondCode Opcode;
2274 switch (predicate) {
2275 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2276 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2277 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2278 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2279 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2280 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2281 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2282 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2283 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2284 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2286 assert(!"Invalid ICmp predicate value");
2287 Opcode = ISD::SETEQ;
2290 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2293 void SelectionDAGLowering::visitFCmp(User &I) {
2294 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2295 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2296 predicate = FC->getPredicate();
2297 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2298 predicate = FCmpInst::Predicate(FC->getPredicate());
2299 SDOperand Op1 = getValue(I.getOperand(0));
2300 SDOperand Op2 = getValue(I.getOperand(1));
2301 ISD::CondCode Condition, FOC, FPC;
2302 switch (predicate) {
2303 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2304 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2305 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2306 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2307 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2308 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2309 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2310 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2311 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2312 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2313 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2314 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2315 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2316 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2317 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2318 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2320 assert(!"Invalid FCmp predicate value");
2321 FOC = FPC = ISD::SETFALSE;
2324 if (FiniteOnlyFPMath())
2328 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2331 void SelectionDAGLowering::visitSelect(User &I) {
2332 SDOperand Cond = getValue(I.getOperand(0));
2333 SDOperand TrueVal = getValue(I.getOperand(1));
2334 SDOperand FalseVal = getValue(I.getOperand(2));
2335 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2336 TrueVal, FalseVal));
2340 void SelectionDAGLowering::visitTrunc(User &I) {
2341 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2342 SDOperand N = getValue(I.getOperand(0));
2343 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2344 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2347 void SelectionDAGLowering::visitZExt(User &I) {
2348 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2349 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2350 SDOperand N = getValue(I.getOperand(0));
2351 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2352 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2355 void SelectionDAGLowering::visitSExt(User &I) {
2356 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2357 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2358 SDOperand N = getValue(I.getOperand(0));
2359 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2360 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2363 void SelectionDAGLowering::visitFPTrunc(User &I) {
2364 // FPTrunc is never a no-op cast, no need to check
2365 SDOperand N = getValue(I.getOperand(0));
2366 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2367 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2370 void SelectionDAGLowering::visitFPExt(User &I){
2371 // FPTrunc is never a no-op cast, no need to check
2372 SDOperand N = getValue(I.getOperand(0));
2373 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2374 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2377 void SelectionDAGLowering::visitFPToUI(User &I) {
2378 // FPToUI is never a no-op cast, no need to check
2379 SDOperand N = getValue(I.getOperand(0));
2380 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2381 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2384 void SelectionDAGLowering::visitFPToSI(User &I) {
2385 // FPToSI is never a no-op cast, no need to check
2386 SDOperand N = getValue(I.getOperand(0));
2387 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2388 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2391 void SelectionDAGLowering::visitUIToFP(User &I) {
2392 // UIToFP is never a no-op cast, no need to check
2393 SDOperand N = getValue(I.getOperand(0));
2394 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2395 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2398 void SelectionDAGLowering::visitSIToFP(User &I){
2399 // UIToFP is never a no-op cast, no need to check
2400 SDOperand N = getValue(I.getOperand(0));
2401 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2402 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2405 void SelectionDAGLowering::visitPtrToInt(User &I) {
2406 // What to do depends on the size of the integer and the size of the pointer.
2407 // We can either truncate, zero extend, or no-op, accordingly.
2408 SDOperand N = getValue(I.getOperand(0));
2409 MVT::ValueType SrcVT = N.getValueType();
2410 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2412 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2413 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2415 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2416 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2417 setValue(&I, Result);
2420 void SelectionDAGLowering::visitIntToPtr(User &I) {
2421 // What to do depends on the size of the integer and the size of the pointer.
2422 // We can either truncate, zero extend, or no-op, accordingly.
2423 SDOperand N = getValue(I.getOperand(0));
2424 MVT::ValueType SrcVT = N.getValueType();
2425 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2426 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2427 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2429 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2430 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2433 void SelectionDAGLowering::visitBitCast(User &I) {
2434 SDOperand N = getValue(I.getOperand(0));
2435 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2437 // BitCast assures us that source and destination are the same size so this
2438 // is either a BIT_CONVERT or a no-op.
2439 if (DestVT != N.getValueType())
2440 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2442 setValue(&I, N); // noop cast.
2445 void SelectionDAGLowering::visitInsertElement(User &I) {
2446 SDOperand InVec = getValue(I.getOperand(0));
2447 SDOperand InVal = getValue(I.getOperand(1));
2448 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2449 getValue(I.getOperand(2)));
2451 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2452 TLI.getValueType(I.getType()),
2453 InVec, InVal, InIdx));
2456 void SelectionDAGLowering::visitExtractElement(User &I) {
2457 SDOperand InVec = getValue(I.getOperand(0));
2458 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2459 getValue(I.getOperand(1)));
2460 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2461 TLI.getValueType(I.getType()), InVec, InIdx));
2464 void SelectionDAGLowering::visitShuffleVector(User &I) {
2465 SDOperand V1 = getValue(I.getOperand(0));
2466 SDOperand V2 = getValue(I.getOperand(1));
2467 SDOperand Mask = getValue(I.getOperand(2));
2469 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2470 TLI.getValueType(I.getType()),
2475 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2476 SDOperand N = getValue(I.getOperand(0));
2477 const Type *Ty = I.getOperand(0)->getType();
2479 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2482 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2483 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2486 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2487 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2488 DAG.getIntPtrConstant(Offset));
2490 Ty = StTy->getElementType(Field);
2492 Ty = cast<SequentialType>(Ty)->getElementType();
2494 // If this is a constant subscript, handle it quickly.
2495 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2496 if (CI->getZExtValue() == 0) continue;
2498 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2499 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2500 DAG.getIntPtrConstant(Offs));
2504 // N = N + Idx * ElementSize;
2505 uint64_t ElementSize = TD->getABITypeSize(Ty);
2506 SDOperand IdxN = getValue(Idx);
2508 // If the index is smaller or larger than intptr_t, truncate or extend
2510 if (IdxN.getValueType() < N.getValueType()) {
2511 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2512 } else if (IdxN.getValueType() > N.getValueType())
2513 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2515 // If this is a multiply by a power of two, turn it into a shl
2516 // immediately. This is a very common case.
2517 if (isPowerOf2_64(ElementSize)) {
2518 unsigned Amt = Log2_64(ElementSize);
2519 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2520 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2521 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2525 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2526 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2527 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2533 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2534 // If this is a fixed sized alloca in the entry block of the function,
2535 // allocate it statically on the stack.
2536 if (FuncInfo.StaticAllocaMap.count(&I))
2537 return; // getValue will auto-populate this.
2539 const Type *Ty = I.getAllocatedType();
2540 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2542 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2545 SDOperand AllocSize = getValue(I.getArraySize());
2546 MVT::ValueType IntPtr = TLI.getPointerTy();
2547 if (IntPtr < AllocSize.getValueType())
2548 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2549 else if (IntPtr > AllocSize.getValueType())
2550 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2552 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2553 DAG.getIntPtrConstant(TySize));
2555 // Handle alignment. If the requested alignment is less than or equal to
2556 // the stack alignment, ignore it. If the size is greater than or equal to
2557 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2558 unsigned StackAlign =
2559 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2560 if (Align <= StackAlign)
2563 // Round the size of the allocation up to the stack alignment size
2564 // by add SA-1 to the size.
2565 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2566 DAG.getIntPtrConstant(StackAlign-1));
2567 // Mask out the low bits for alignment purposes.
2568 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2569 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2571 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2572 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2574 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2576 DAG.setRoot(DSA.getValue(1));
2578 // Inform the Frame Information that we have just allocated a variable-sized
2580 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2583 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2584 SDOperand Ptr = getValue(I.getOperand(0));
2590 // Do not serialize non-volatile loads against each other.
2591 Root = DAG.getRoot();
2594 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2595 Root, I.isVolatile(), I.getAlignment()));
2598 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2599 const Value *SV, SDOperand Root,
2601 unsigned Alignment) {
2603 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2604 isVolatile, Alignment);
2607 DAG.setRoot(L.getValue(1));
2609 PendingLoads.push_back(L.getValue(1));
2615 void SelectionDAGLowering::visitStore(StoreInst &I) {
2616 Value *SrcV = I.getOperand(0);
2617 SDOperand Src = getValue(SrcV);
2618 SDOperand Ptr = getValue(I.getOperand(1));
2619 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2620 I.isVolatile(), I.getAlignment()));
2623 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2625 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2626 unsigned Intrinsic) {
2627 bool HasChain = !I.doesNotAccessMemory();
2628 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2630 // Build the operand list.
2631 SmallVector<SDOperand, 8> Ops;
2632 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2634 // We don't need to serialize loads against other loads.
2635 Ops.push_back(DAG.getRoot());
2637 Ops.push_back(getRoot());
2641 // Add the intrinsic ID as an integer operand.
2642 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2644 // Add all operands of the call to the operand list.
2645 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2646 SDOperand Op = getValue(I.getOperand(i));
2647 assert(TLI.isTypeLegal(Op.getValueType()) &&
2648 "Intrinsic uses a non-legal type?");
2652 std::vector<MVT::ValueType> VTs;
2653 if (I.getType() != Type::VoidTy) {
2654 MVT::ValueType VT = TLI.getValueType(I.getType());
2655 if (MVT::isVector(VT)) {
2656 const VectorType *DestTy = cast<VectorType>(I.getType());
2657 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2659 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2660 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2663 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2667 VTs.push_back(MVT::Other);
2669 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2674 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2675 &Ops[0], Ops.size());
2676 else if (I.getType() != Type::VoidTy)
2677 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2678 &Ops[0], Ops.size());
2680 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2681 &Ops[0], Ops.size());
2684 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2686 PendingLoads.push_back(Chain);
2690 if (I.getType() != Type::VoidTy) {
2691 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2692 MVT::ValueType VT = TLI.getValueType(PTy);
2693 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2695 setValue(&I, Result);
2699 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2700 static GlobalVariable *ExtractTypeInfo (Value *V) {
2701 V = IntrinsicInst::StripPointerCasts(V);
2702 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2703 assert ((GV || isa<ConstantPointerNull>(V)) &&
2704 "TypeInfo must be a global variable or NULL");
2708 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2709 /// call, and add them to the specified machine basic block.
2710 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2711 MachineBasicBlock *MBB) {
2712 // Inform the MachineModuleInfo of the personality for this landing pad.
2713 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2714 assert(CE->getOpcode() == Instruction::BitCast &&
2715 isa<Function>(CE->getOperand(0)) &&
2716 "Personality should be a function");
2717 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2719 // Gather all the type infos for this landing pad and pass them along to
2720 // MachineModuleInfo.
2721 std::vector<GlobalVariable *> TyInfo;
2722 unsigned N = I.getNumOperands();
2724 for (unsigned i = N - 1; i > 2; --i) {
2725 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2726 unsigned FilterLength = CI->getZExtValue();
2727 unsigned FirstCatch = i + FilterLength + !FilterLength;
2728 assert (FirstCatch <= N && "Invalid filter length");
2730 if (FirstCatch < N) {
2731 TyInfo.reserve(N - FirstCatch);
2732 for (unsigned j = FirstCatch; j < N; ++j)
2733 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2734 MMI->addCatchTypeInfo(MBB, TyInfo);
2738 if (!FilterLength) {
2740 MMI->addCleanup(MBB);
2743 TyInfo.reserve(FilterLength - 1);
2744 for (unsigned j = i + 1; j < FirstCatch; ++j)
2745 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2746 MMI->addFilterTypeInfo(MBB, TyInfo);
2755 TyInfo.reserve(N - 3);
2756 for (unsigned j = 3; j < N; ++j)
2757 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2758 MMI->addCatchTypeInfo(MBB, TyInfo);
2762 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2763 /// we want to emit this as a call to a named external function, return the name
2764 /// otherwise lower it and return null.
2766 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2767 switch (Intrinsic) {
2769 // By default, turn this into a target intrinsic node.
2770 visitTargetIntrinsic(I, Intrinsic);
2772 case Intrinsic::vastart: visitVAStart(I); return 0;
2773 case Intrinsic::vaend: visitVAEnd(I); return 0;
2774 case Intrinsic::vacopy: visitVACopy(I); return 0;
2775 case Intrinsic::returnaddress:
2776 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2777 getValue(I.getOperand(1))));
2779 case Intrinsic::frameaddress:
2780 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2781 getValue(I.getOperand(1))));
2783 case Intrinsic::setjmp:
2784 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2786 case Intrinsic::longjmp:
2787 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2789 case Intrinsic::memcpy_i32:
2790 case Intrinsic::memcpy_i64: {
2791 SDOperand Op1 = getValue(I.getOperand(1));
2792 SDOperand Op2 = getValue(I.getOperand(2));
2793 SDOperand Op3 = getValue(I.getOperand(3));
2794 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2795 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2796 I.getOperand(1), 0, I.getOperand(2), 0));
2799 case Intrinsic::memset_i32:
2800 case Intrinsic::memset_i64: {
2801 SDOperand Op1 = getValue(I.getOperand(1));
2802 SDOperand Op2 = getValue(I.getOperand(2));
2803 SDOperand Op3 = getValue(I.getOperand(3));
2804 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2805 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2806 I.getOperand(1), 0));
2809 case Intrinsic::memmove_i32:
2810 case Intrinsic::memmove_i64: {
2811 SDOperand Op1 = getValue(I.getOperand(1));
2812 SDOperand Op2 = getValue(I.getOperand(2));
2813 SDOperand Op3 = getValue(I.getOperand(3));
2814 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2816 // If the source and destination are known to not be aliases, we can
2817 // lower memmove as memcpy.
2818 uint64_t Size = -1ULL;
2819 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2820 Size = C->getValue();
2821 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2822 AliasAnalysis::NoAlias) {
2823 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2824 I.getOperand(1), 0, I.getOperand(2), 0));
2828 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2829 I.getOperand(1), 0, I.getOperand(2), 0));
2832 case Intrinsic::dbg_stoppoint: {
2833 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2834 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2835 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2839 Ops[1] = getValue(SPI.getLineValue());
2840 Ops[2] = getValue(SPI.getColumnValue());
2842 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2843 assert(DD && "Not a debug information descriptor");
2844 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2846 Ops[3] = DAG.getString(CompileUnit->getFileName());
2847 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2849 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2854 case Intrinsic::dbg_region_start: {
2855 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2856 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2857 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2858 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2859 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2860 DAG.getConstant(LabelID, MVT::i32),
2861 DAG.getConstant(0, MVT::i32)));
2866 case Intrinsic::dbg_region_end: {
2867 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2868 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2869 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2870 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2871 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2872 DAG.getConstant(LabelID, MVT::i32),
2873 DAG.getConstant(0, MVT::i32)));
2878 case Intrinsic::dbg_func_start: {
2879 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2881 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2882 Value *SP = FSI.getSubprogram();
2883 if (SP && MMI->Verify(SP)) {
2884 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2885 // what (most?) gdb expects.
2886 DebugInfoDesc *DD = MMI->getDescFor(SP);
2887 assert(DD && "Not a debug information descriptor");
2888 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2889 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2890 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2891 CompileUnit->getFileName());
2892 // Record the source line but does create a label. It will be emitted
2893 // at asm emission time.
2894 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2899 case Intrinsic::dbg_declare: {
2900 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2901 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2902 Value *Variable = DI.getVariable();
2903 if (MMI && Variable && MMI->Verify(Variable))
2904 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2905 getValue(DI.getAddress()), getValue(Variable)));
2909 case Intrinsic::eh_exception: {
2910 if (!CurMBB->isLandingPad()) {
2911 // FIXME: Mark exception register as live in. Hack for PR1508.
2912 unsigned Reg = TLI.getExceptionAddressRegister();
2913 if (Reg) CurMBB->addLiveIn(Reg);
2915 // Insert the EXCEPTIONADDR instruction.
2916 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2918 Ops[0] = DAG.getRoot();
2919 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2921 DAG.setRoot(Op.getValue(1));
2925 case Intrinsic::eh_selector_i32:
2926 case Intrinsic::eh_selector_i64: {
2927 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2928 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2929 MVT::i32 : MVT::i64);
2932 if (CurMBB->isLandingPad())
2933 addCatchInfo(I, MMI, CurMBB);
2936 FuncInfo.CatchInfoLost.insert(&I);
2938 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2939 unsigned Reg = TLI.getExceptionSelectorRegister();
2940 if (Reg) CurMBB->addLiveIn(Reg);
2943 // Insert the EHSELECTION instruction.
2944 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2946 Ops[0] = getValue(I.getOperand(1));
2948 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2950 DAG.setRoot(Op.getValue(1));
2952 setValue(&I, DAG.getConstant(0, VT));
2958 case Intrinsic::eh_typeid_for_i32:
2959 case Intrinsic::eh_typeid_for_i64: {
2960 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2961 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2962 MVT::i32 : MVT::i64);
2965 // Find the type id for the given typeinfo.
2966 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2968 unsigned TypeID = MMI->getTypeIDFor(GV);
2969 setValue(&I, DAG.getConstant(TypeID, VT));
2971 // Return something different to eh_selector.
2972 setValue(&I, DAG.getConstant(1, VT));
2978 case Intrinsic::eh_return: {
2979 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2982 MMI->setCallsEHReturn(true);
2983 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2986 getValue(I.getOperand(1)),
2987 getValue(I.getOperand(2))));
2989 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2995 case Intrinsic::eh_unwind_init: {
2996 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2997 MMI->setCallsUnwindInit(true);
3003 case Intrinsic::eh_dwarf_cfa: {
3004 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3006 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3007 CfaArg = DAG.getNode(ISD::TRUNCATE,
3008 TLI.getPointerTy(), getValue(I.getOperand(1)));
3010 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3011 TLI.getPointerTy(), getValue(I.getOperand(1)));
3013 SDOperand Offset = DAG.getNode(ISD::ADD,
3015 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3016 TLI.getPointerTy()),
3018 setValue(&I, DAG.getNode(ISD::ADD,
3020 DAG.getNode(ISD::FRAMEADDR,
3023 TLI.getPointerTy())),
3028 case Intrinsic::sqrt:
3029 setValue(&I, DAG.getNode(ISD::FSQRT,
3030 getValue(I.getOperand(1)).getValueType(),
3031 getValue(I.getOperand(1))));
3033 case Intrinsic::powi:
3034 setValue(&I, DAG.getNode(ISD::FPOWI,
3035 getValue(I.getOperand(1)).getValueType(),
3036 getValue(I.getOperand(1)),
3037 getValue(I.getOperand(2))));
3039 case Intrinsic::sin:
3040 setValue(&I, DAG.getNode(ISD::FSIN,
3041 getValue(I.getOperand(1)).getValueType(),
3042 getValue(I.getOperand(1))));
3044 case Intrinsic::cos:
3045 setValue(&I, DAG.getNode(ISD::FCOS,
3046 getValue(I.getOperand(1)).getValueType(),
3047 getValue(I.getOperand(1))));
3049 case Intrinsic::pow:
3050 setValue(&I, DAG.getNode(ISD::FPOW,
3051 getValue(I.getOperand(1)).getValueType(),
3052 getValue(I.getOperand(1)),
3053 getValue(I.getOperand(2))));
3055 case Intrinsic::pcmarker: {
3056 SDOperand Tmp = getValue(I.getOperand(1));
3057 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3060 case Intrinsic::readcyclecounter: {
3061 SDOperand Op = getRoot();
3062 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3063 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3066 DAG.setRoot(Tmp.getValue(1));
3069 case Intrinsic::part_select: {
3070 // Currently not implemented: just abort
3071 assert(0 && "part_select intrinsic not implemented");
3074 case Intrinsic::part_set: {
3075 // Currently not implemented: just abort
3076 assert(0 && "part_set intrinsic not implemented");
3079 case Intrinsic::bswap:
3080 setValue(&I, DAG.getNode(ISD::BSWAP,
3081 getValue(I.getOperand(1)).getValueType(),
3082 getValue(I.getOperand(1))));
3084 case Intrinsic::cttz: {
3085 SDOperand Arg = getValue(I.getOperand(1));
3086 MVT::ValueType Ty = Arg.getValueType();
3087 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3088 setValue(&I, result);
3091 case Intrinsic::ctlz: {
3092 SDOperand Arg = getValue(I.getOperand(1));
3093 MVT::ValueType Ty = Arg.getValueType();
3094 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3095 setValue(&I, result);
3098 case Intrinsic::ctpop: {
3099 SDOperand Arg = getValue(I.getOperand(1));
3100 MVT::ValueType Ty = Arg.getValueType();
3101 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3102 setValue(&I, result);
3105 case Intrinsic::stacksave: {
3106 SDOperand Op = getRoot();
3107 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3108 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3110 DAG.setRoot(Tmp.getValue(1));
3113 case Intrinsic::stackrestore: {
3114 SDOperand Tmp = getValue(I.getOperand(1));
3115 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3118 case Intrinsic::var_annotation:
3119 // Discard annotate attributes
3122 case Intrinsic::init_trampoline: {
3124 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3128 Ops[1] = getValue(I.getOperand(1));
3129 Ops[2] = getValue(I.getOperand(2));
3130 Ops[3] = getValue(I.getOperand(3));
3131 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3132 Ops[5] = DAG.getSrcValue(F);
3134 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3135 DAG.getNodeValueTypes(TLI.getPointerTy(),
3140 DAG.setRoot(Tmp.getValue(1));
3144 case Intrinsic::gcroot:
3146 Value *Alloca = I.getOperand(1);
3147 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3149 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3150 GCI->addStackRoot(FI->getIndex(), TypeMap);
3154 case Intrinsic::gcread:
3155 case Intrinsic::gcwrite:
3156 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3159 case Intrinsic::flt_rounds: {
3160 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3164 case Intrinsic::trap: {
3165 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3168 case Intrinsic::prefetch: {
3171 Ops[1] = getValue(I.getOperand(1));
3172 Ops[2] = getValue(I.getOperand(2));
3173 Ops[3] = getValue(I.getOperand(3));
3174 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3178 case Intrinsic::memory_barrier: {
3181 for (int x = 1; x < 6; ++x)
3182 Ops[x] = getValue(I.getOperand(x));
3184 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3187 case Intrinsic::atomic_lcs: {
3188 SDOperand Root = getRoot();
3189 SDOperand O3 = getValue(I.getOperand(3));
3190 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3191 getValue(I.getOperand(1)),
3192 getValue(I.getOperand(2)),
3193 O3, O3.getValueType());
3195 DAG.setRoot(L.getValue(1));
3198 case Intrinsic::atomic_las: {
3199 SDOperand Root = getRoot();
3200 SDOperand O2 = getValue(I.getOperand(2));
3201 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3202 getValue(I.getOperand(1)),
3203 O2, O2.getValueType());
3205 DAG.setRoot(L.getValue(1));
3208 case Intrinsic::atomic_swap: {
3209 SDOperand Root = getRoot();
3210 SDOperand O2 = getValue(I.getOperand(2));
3211 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3212 getValue(I.getOperand(1)),
3213 O2, O2.getValueType());
3215 DAG.setRoot(L.getValue(1));
3223 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3225 MachineBasicBlock *LandingPad) {
3226 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3227 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3228 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3229 unsigned BeginLabel = 0, EndLabel = 0;
3231 TargetLowering::ArgListTy Args;
3232 TargetLowering::ArgListEntry Entry;
3233 Args.reserve(CS.arg_size());
3234 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3236 SDOperand ArgNode = getValue(*i);
3237 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3239 unsigned attrInd = i - CS.arg_begin() + 1;
3240 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3241 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3242 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3243 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3244 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3245 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3246 Entry.Alignment = CS.getParamAlignment(attrInd);
3247 Args.push_back(Entry);
3250 if (LandingPad && MMI) {
3251 // Insert a label before the invoke call to mark the try range. This can be
3252 // used to detect deletion of the invoke via the MachineModuleInfo.
3253 BeginLabel = MMI->NextLabelID();
3254 // Both PendingLoads and PendingExports must be flushed here;
3255 // this call might not return.
3257 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3258 DAG.getConstant(BeginLabel, MVT::i32),
3259 DAG.getConstant(1, MVT::i32)));
3262 std::pair<SDOperand,SDOperand> Result =
3263 TLI.LowerCallTo(getRoot(), CS.getType(),
3264 CS.paramHasAttr(0, ParamAttr::SExt),
3265 CS.paramHasAttr(0, ParamAttr::ZExt),
3266 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3268 if (CS.getType() != Type::VoidTy)
3269 setValue(CS.getInstruction(), Result.first);
3270 DAG.setRoot(Result.second);
3272 if (LandingPad && MMI) {
3273 // Insert a label at the end of the invoke call to mark the try range. This
3274 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3275 EndLabel = MMI->NextLabelID();
3276 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3277 DAG.getConstant(EndLabel, MVT::i32),
3278 DAG.getConstant(1, MVT::i32)));
3280 // Inform MachineModuleInfo of range.
3281 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3286 void SelectionDAGLowering::visitCall(CallInst &I) {
3287 const char *RenameFn = 0;
3288 if (Function *F = I.getCalledFunction()) {
3289 if (F->isDeclaration()) {
3290 if (unsigned IID = F->getIntrinsicID()) {
3291 RenameFn = visitIntrinsicCall(I, IID);
3297 // Check for well-known libc/libm calls. If the function is internal, it
3298 // can't be a library call.
3299 unsigned NameLen = F->getNameLen();
3300 if (!F->hasInternalLinkage() && NameLen) {
3301 const char *NameStr = F->getNameStart();
3302 if (NameStr[0] == 'c' &&
3303 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3304 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3305 if (I.getNumOperands() == 3 && // Basic sanity checks.
3306 I.getOperand(1)->getType()->isFloatingPoint() &&
3307 I.getType() == I.getOperand(1)->getType() &&
3308 I.getType() == I.getOperand(2)->getType()) {
3309 SDOperand LHS = getValue(I.getOperand(1));
3310 SDOperand RHS = getValue(I.getOperand(2));
3311 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3315 } else if (NameStr[0] == 'f' &&
3316 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3317 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3318 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3319 if (I.getNumOperands() == 2 && // Basic sanity checks.
3320 I.getOperand(1)->getType()->isFloatingPoint() &&
3321 I.getType() == I.getOperand(1)->getType()) {
3322 SDOperand Tmp = getValue(I.getOperand(1));
3323 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3326 } else if (NameStr[0] == 's' &&
3327 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3328 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3329 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3330 if (I.getNumOperands() == 2 && // Basic sanity checks.
3331 I.getOperand(1)->getType()->isFloatingPoint() &&
3332 I.getType() == I.getOperand(1)->getType()) {
3333 SDOperand Tmp = getValue(I.getOperand(1));
3334 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3337 } else if (NameStr[0] == 'c' &&
3338 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3339 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3340 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3341 if (I.getNumOperands() == 2 && // Basic sanity checks.
3342 I.getOperand(1)->getType()->isFloatingPoint() &&
3343 I.getType() == I.getOperand(1)->getType()) {
3344 SDOperand Tmp = getValue(I.getOperand(1));
3345 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3350 } else if (isa<InlineAsm>(I.getOperand(0))) {
3357 Callee = getValue(I.getOperand(0));
3359 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3361 LowerCallTo(&I, Callee, I.isTailCall());
3365 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3366 if (isa<UndefValue>(I.getOperand(0))) {
3367 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3368 setValue(&I, Undef);
3372 // To add support for individual return values with aggregate types,
3373 // we'd need a way to take a getresult index and determine which
3374 // values of the Call SDNode are associated with it.
3375 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3376 "Individual return values must not be aggregates!");
3378 SDOperand Call = getValue(I.getOperand(0));
3379 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3383 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3384 /// this value and returns the result as a ValueVT value. This uses
3385 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3386 /// If the Flag pointer is NULL, no flag is used.
3387 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3389 SDOperand *Flag) const {
3390 // Assemble the legal parts into the final values.
3391 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3392 SmallVector<SDOperand, 8> Parts;
3393 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3394 // Copy the legal parts from the registers.
3395 MVT::ValueType ValueVT = ValueVTs[Value];
3396 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3397 MVT::ValueType RegisterVT = RegVTs[Value];
3399 Parts.resize(NumRegs);
3400 for (unsigned i = 0; i != NumRegs; ++i) {
3403 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3405 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3406 *Flag = P.getValue(2);
3408 Chain = P.getValue(1);
3412 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3417 if (ValueVTs.size() == 1)
3420 return DAG.getNode(ISD::MERGE_VALUES,
3421 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3422 &Values[0], ValueVTs.size());
3425 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3426 /// specified value into the registers specified by this object. This uses
3427 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3428 /// If the Flag pointer is NULL, no flag is used.
3429 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3430 SDOperand &Chain, SDOperand *Flag) const {
3431 // Get the list of the values's legal parts.
3432 unsigned NumRegs = Regs.size();
3433 SmallVector<SDOperand, 8> Parts(NumRegs);
3434 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3435 MVT::ValueType ValueVT = ValueVTs[Value];
3436 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3437 MVT::ValueType RegisterVT = RegVTs[Value];
3439 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3440 &Parts[Part], NumParts, RegisterVT);
3444 // Copy the parts into the registers.
3445 SmallVector<SDOperand, 8> Chains(NumRegs);
3446 for (unsigned i = 0; i != NumRegs; ++i) {
3449 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3451 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3452 *Flag = Part.getValue(1);
3454 Chains[i] = Part.getValue(0);
3460 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3463 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3464 /// operand list. This adds the code marker and includes the number of
3465 /// values added into it.
3466 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3467 std::vector<SDOperand> &Ops) const {
3468 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3469 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3470 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3471 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3472 MVT::ValueType RegisterVT = RegVTs[Value];
3473 for (unsigned i = 0; i != NumRegs; ++i)
3474 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3478 /// isAllocatableRegister - If the specified register is safe to allocate,
3479 /// i.e. it isn't a stack pointer or some other special register, return the
3480 /// register class for the register. Otherwise, return null.
3481 static const TargetRegisterClass *
3482 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3483 const TargetLowering &TLI,
3484 const TargetRegisterInfo *TRI) {
3485 MVT::ValueType FoundVT = MVT::Other;
3486 const TargetRegisterClass *FoundRC = 0;
3487 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3488 E = TRI->regclass_end(); RCI != E; ++RCI) {
3489 MVT::ValueType ThisVT = MVT::Other;
3491 const TargetRegisterClass *RC = *RCI;
3492 // If none of the the value types for this register class are valid, we
3493 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3494 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3496 if (TLI.isTypeLegal(*I)) {
3497 // If we have already found this register in a different register class,
3498 // choose the one with the largest VT specified. For example, on
3499 // PowerPC, we favor f64 register classes over f32.
3500 if (FoundVT == MVT::Other ||
3501 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3508 if (ThisVT == MVT::Other) continue;
3510 // NOTE: This isn't ideal. In particular, this might allocate the
3511 // frame pointer in functions that need it (due to them not being taken
3512 // out of allocation, because a variable sized allocation hasn't been seen
3513 // yet). This is a slight code pessimization, but should still work.
3514 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3515 E = RC->allocation_order_end(MF); I != E; ++I)
3517 // We found a matching register class. Keep looking at others in case
3518 // we find one with larger registers that this physreg is also in.
3529 /// AsmOperandInfo - This contains information for each constraint that we are
3531 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3532 /// CallOperand - If this is the result output operand or a clobber
3533 /// this is null, otherwise it is the incoming operand to the CallInst.
3534 /// This gets modified as the asm is processed.
3535 SDOperand CallOperand;
3537 /// AssignedRegs - If this is a register or register class operand, this
3538 /// contains the set of register corresponding to the operand.
3539 RegsForValue AssignedRegs;
3541 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3542 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3545 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3546 /// busy in OutputRegs/InputRegs.
3547 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3548 std::set<unsigned> &OutputRegs,
3549 std::set<unsigned> &InputRegs,
3550 const TargetRegisterInfo &TRI) const {
3552 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3553 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3556 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3557 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3562 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3564 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3565 const TargetRegisterInfo &TRI) {
3566 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3568 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3569 for (; *Aliases; ++Aliases)
3570 Regs.insert(*Aliases);
3573 } // end anon namespace.
3576 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3577 /// specified operand. We prefer to assign virtual registers, to allow the
3578 /// register allocator handle the assignment process. However, if the asm uses
3579 /// features that we can't model on machineinstrs, we have SDISel do the
3580 /// allocation. This produces generally horrible, but correct, code.
3582 /// OpInfo describes the operand.
3583 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3584 /// or any explicitly clobbered registers.
3585 /// Input and OutputRegs are the set of already allocated physical registers.
3587 void SelectionDAGLowering::
3588 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3589 std::set<unsigned> &OutputRegs,
3590 std::set<unsigned> &InputRegs) {
3591 // Compute whether this value requires an input register, an output register,
3593 bool isOutReg = false;
3594 bool isInReg = false;
3595 switch (OpInfo.Type) {
3596 case InlineAsm::isOutput:
3599 // If this is an early-clobber output, or if there is an input
3600 // constraint that matches this, we need to reserve the input register
3601 // so no other inputs allocate to it.
3602 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3604 case InlineAsm::isInput:
3608 case InlineAsm::isClobber:
3615 MachineFunction &MF = DAG.getMachineFunction();
3616 SmallVector<unsigned, 4> Regs;
3618 // If this is a constraint for a single physreg, or a constraint for a
3619 // register class, find it.
3620 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3621 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3622 OpInfo.ConstraintVT);
3624 unsigned NumRegs = 1;
3625 if (OpInfo.ConstraintVT != MVT::Other)
3626 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3627 MVT::ValueType RegVT;
3628 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3631 // If this is a constraint for a specific physical register, like {r17},
3633 if (PhysReg.first) {
3634 if (OpInfo.ConstraintVT == MVT::Other)
3635 ValueVT = *PhysReg.second->vt_begin();
3637 // Get the actual register value type. This is important, because the user
3638 // may have asked for (e.g.) the AX register in i32 type. We need to
3639 // remember that AX is actually i16 to get the right extension.
3640 RegVT = *PhysReg.second->vt_begin();
3642 // This is a explicit reference to a physical register.
3643 Regs.push_back(PhysReg.first);
3645 // If this is an expanded reference, add the rest of the regs to Regs.
3647 TargetRegisterClass::iterator I = PhysReg.second->begin();
3648 TargetRegisterClass::iterator E = PhysReg.second->end();
3649 for (; *I != PhysReg.first; ++I)
3650 assert(I != E && "Didn't find reg!");
3652 // Already added the first reg.
3654 for (; NumRegs; --NumRegs, ++I) {
3655 assert(I != E && "Ran out of registers to allocate!");
3659 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3660 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3661 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3665 // Otherwise, if this was a reference to an LLVM register class, create vregs
3666 // for this reference.
3667 std::vector<unsigned> RegClassRegs;
3668 const TargetRegisterClass *RC = PhysReg.second;
3670 // If this is an early clobber or tied register, our regalloc doesn't know
3671 // how to maintain the constraint. If it isn't, go ahead and create vreg
3672 // and let the regalloc do the right thing.
3673 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3674 // If there is some other early clobber and this is an input register,
3675 // then we are forced to pre-allocate the input reg so it doesn't
3676 // conflict with the earlyclobber.
3677 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3678 RegVT = *PhysReg.second->vt_begin();
3680 if (OpInfo.ConstraintVT == MVT::Other)
3683 // Create the appropriate number of virtual registers.
3684 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3685 for (; NumRegs; --NumRegs)
3686 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3688 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3692 // Otherwise, we can't allocate it. Let the code below figure out how to
3693 // maintain these constraints.
3694 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3697 // This is a reference to a register class that doesn't directly correspond
3698 // to an LLVM register class. Allocate NumRegs consecutive, available,
3699 // registers from the class.
3700 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3701 OpInfo.ConstraintVT);
3704 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3705 unsigned NumAllocated = 0;
3706 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3707 unsigned Reg = RegClassRegs[i];
3708 // See if this register is available.
3709 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3710 (isInReg && InputRegs.count(Reg))) { // Already used.
3711 // Make sure we find consecutive registers.
3716 // Check to see if this register is allocatable (i.e. don't give out the
3719 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3720 if (!RC) { // Couldn't allocate this register.
3721 // Reset NumAllocated to make sure we return consecutive registers.
3727 // Okay, this register is good, we can use it.
3730 // If we allocated enough consecutive registers, succeed.
3731 if (NumAllocated == NumRegs) {
3732 unsigned RegStart = (i-NumAllocated)+1;
3733 unsigned RegEnd = i+1;
3734 // Mark all of the allocated registers used.
3735 for (unsigned i = RegStart; i != RegEnd; ++i)
3736 Regs.push_back(RegClassRegs[i]);
3738 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
3739 OpInfo.ConstraintVT);
3740 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3745 // Otherwise, we couldn't allocate enough registers for this.
3750 /// visitInlineAsm - Handle a call to an InlineAsm object.
3752 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3753 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3755 /// ConstraintOperands - Information about all of the constraints.
3756 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3758 SDOperand Chain = getRoot();
3761 std::set<unsigned> OutputRegs, InputRegs;
3763 // Do a prepass over the constraints, canonicalizing them, and building up the
3764 // ConstraintOperands list.
3765 std::vector<InlineAsm::ConstraintInfo>
3766 ConstraintInfos = IA->ParseConstraints();
3768 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3769 // constraint. If so, we can't let the register allocator allocate any input
3770 // registers, because it will not know to avoid the earlyclobbered output reg.
3771 bool SawEarlyClobber = false;
3773 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3774 unsigned ResNo = 0; // ResNo - The result number of the next output.
3775 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3776 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3777 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3779 MVT::ValueType OpVT = MVT::Other;
3781 // Compute the value type for each operand.
3782 switch (OpInfo.Type) {
3783 case InlineAsm::isOutput:
3784 // Indirect outputs just consume an argument.
3785 if (OpInfo.isIndirect) {
3786 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3789 // The return value of the call is this value. As such, there is no
3790 // corresponding argument.
3791 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3792 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3793 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3795 assert(ResNo == 0 && "Asm only has one result!");
3796 OpVT = TLI.getValueType(CS.getType());
3800 case InlineAsm::isInput:
3801 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3803 case InlineAsm::isClobber:
3808 // If this is an input or an indirect output, process the call argument.
3809 // BasicBlocks are labels, currently appearing only in asm's.
3810 if (OpInfo.CallOperandVal) {
3811 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3812 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3814 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3815 const Type *OpTy = OpInfo.CallOperandVal->getType();
3816 // If this is an indirect operand, the operand is a pointer to the
3818 if (OpInfo.isIndirect)
3819 OpTy = cast<PointerType>(OpTy)->getElementType();
3821 // If OpTy is not a first-class value, it may be a struct/union that we
3822 // can tile with integers.
3823 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3824 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3832 OpTy = IntegerType::get(BitSize);
3837 OpVT = TLI.getValueType(OpTy, true);
3841 OpInfo.ConstraintVT = OpVT;
3843 // Compute the constraint code and ConstraintType to use.
3844 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
3846 // Keep track of whether we see an earlyclobber.
3847 SawEarlyClobber |= OpInfo.isEarlyClobber;
3849 // If we see a clobber of a register, it is an early clobber.
3850 if (!SawEarlyClobber &&
3851 OpInfo.Type == InlineAsm::isClobber &&
3852 OpInfo.ConstraintType == TargetLowering::C_Register) {
3853 // Note that we want to ignore things that we don't trick here, like
3854 // dirflag, fpsr, flags, etc.
3855 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3856 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3857 OpInfo.ConstraintVT);
3858 if (PhysReg.first || PhysReg.second) {
3859 // This is a register we know of.
3860 SawEarlyClobber = true;
3864 // If this is a memory input, and if the operand is not indirect, do what we
3865 // need to to provide an address for the memory input.
3866 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3867 !OpInfo.isIndirect) {
3868 assert(OpInfo.Type == InlineAsm::isInput &&
3869 "Can only indirectify direct input operands!");
3871 // Memory operands really want the address of the value. If we don't have
3872 // an indirect input, put it in the constpool if we can, otherwise spill
3873 // it to a stack slot.
3875 // If the operand is a float, integer, or vector constant, spill to a
3876 // constant pool entry to get its address.
3877 Value *OpVal = OpInfo.CallOperandVal;
3878 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3879 isa<ConstantVector>(OpVal)) {
3880 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3881 TLI.getPointerTy());
3883 // Otherwise, create a stack slot and emit a store to it before the
3885 const Type *Ty = OpVal->getType();
3886 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3887 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3888 MachineFunction &MF = DAG.getMachineFunction();
3889 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3890 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3891 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3892 OpInfo.CallOperand = StackSlot;
3895 // There is no longer a Value* corresponding to this operand.
3896 OpInfo.CallOperandVal = 0;
3897 // It is now an indirect operand.
3898 OpInfo.isIndirect = true;
3901 // If this constraint is for a specific register, allocate it before
3903 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3904 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3906 ConstraintInfos.clear();
3909 // Second pass - Loop over all of the operands, assigning virtual or physregs
3910 // to registerclass operands.
3911 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3912 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3914 // C_Register operands have already been allocated, Other/Memory don't need
3916 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3917 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3920 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3921 std::vector<SDOperand> AsmNodeOperands;
3922 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3923 AsmNodeOperands.push_back(
3924 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3927 // Loop over all of the inputs, copying the operand values into the
3928 // appropriate registers and processing the output regs.
3929 RegsForValue RetValRegs;
3931 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3932 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3934 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3935 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3937 switch (OpInfo.Type) {
3938 case InlineAsm::isOutput: {
3939 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3940 OpInfo.ConstraintType != TargetLowering::C_Register) {
3941 // Memory output, or 'other' output (e.g. 'X' constraint).
3942 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3944 // Add information to the INLINEASM node to know about this output.
3945 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3946 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3947 TLI.getPointerTy()));
3948 AsmNodeOperands.push_back(OpInfo.CallOperand);
3952 // Otherwise, this is a register or register class output.
3954 // Copy the output from the appropriate register. Find a register that
3956 if (OpInfo.AssignedRegs.Regs.empty()) {
3957 cerr << "Couldn't allocate output reg for contraint '"
3958 << OpInfo.ConstraintCode << "'!\n";
3962 if (!OpInfo.isIndirect) {
3963 // This is the result value of the call.
3964 assert(RetValRegs.Regs.empty() &&
3965 "Cannot have multiple output constraints yet!");
3966 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3967 RetValRegs = OpInfo.AssignedRegs;
3969 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3970 OpInfo.CallOperandVal));
3973 // Add information to the INLINEASM node to know that this register is
3975 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3979 case InlineAsm::isInput: {
3980 SDOperand InOperandVal = OpInfo.CallOperand;
3982 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3983 // If this is required to match an output register we have already set,
3984 // just use its register.
3985 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3987 // Scan until we find the definition we already emitted of this operand.
3988 // When we find it, create a RegsForValue operand.
3989 unsigned CurOp = 2; // The first operand.
3990 for (; OperandNo; --OperandNo) {
3991 // Advance to the next operand.
3993 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3994 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3995 (NumOps & 7) == 4 /*MEM*/) &&
3996 "Skipped past definitions?");
3997 CurOp += (NumOps>>3)+1;
4001 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4002 if ((NumOps & 7) == 2 /*REGDEF*/) {
4003 // Add NumOps>>3 registers to MatchedRegs.
4004 RegsForValue MatchedRegs;
4005 MatchedRegs.TLI = &TLI;
4006 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
4007 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
4008 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4010 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4011 MatchedRegs.Regs.push_back(Reg);
4014 // Use the produced MatchedRegs object to
4015 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4016 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4019 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4020 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4021 // Add information to the INLINEASM node to know about this input.
4022 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4023 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4024 TLI.getPointerTy()));
4025 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4030 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4031 assert(!OpInfo.isIndirect &&
4032 "Don't know how to handle indirect other inputs yet!");
4034 std::vector<SDOperand> Ops;
4035 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4038 cerr << "Invalid operand for inline asm constraint '"
4039 << OpInfo.ConstraintCode << "'!\n";
4043 // Add information to the INLINEASM node to know about this input.
4044 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4045 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4046 TLI.getPointerTy()));
4047 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4049 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4050 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4051 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4052 "Memory operands expect pointer values");
4054 // Add information to the INLINEASM node to know about this input.
4055 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4056 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4057 TLI.getPointerTy()));
4058 AsmNodeOperands.push_back(InOperandVal);
4062 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4063 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4064 "Unknown constraint type!");
4065 assert(!OpInfo.isIndirect &&
4066 "Don't know how to handle indirect register inputs yet!");
4068 // Copy the input into the appropriate registers.
4069 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4070 "Couldn't allocate input reg!");
4072 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4074 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4078 case InlineAsm::isClobber: {
4079 // Add the clobbered value to the operand list, so that the register
4080 // allocator is aware that the physreg got clobbered.
4081 if (!OpInfo.AssignedRegs.Regs.empty())
4082 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4089 // Finish up input operands.
4090 AsmNodeOperands[0] = Chain;
4091 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4093 Chain = DAG.getNode(ISD::INLINEASM,
4094 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4095 &AsmNodeOperands[0], AsmNodeOperands.size());
4096 Flag = Chain.getValue(1);
4098 // If this asm returns a register value, copy the result from that register
4099 // and set it as the value of the call.
4100 if (!RetValRegs.Regs.empty()) {
4101 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4103 // If the result of the inline asm is a vector, it may have the wrong
4104 // width/num elts. Make sure to convert it to the right type with
4106 if (MVT::isVector(Val.getValueType())) {
4107 const VectorType *VTy = cast<VectorType>(CS.getType());
4108 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
4110 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
4113 setValue(CS.getInstruction(), Val);
4116 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4118 // Process indirect outputs, first output all of the flagged copies out of
4120 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4121 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4122 Value *Ptr = IndirectStoresToEmit[i].second;
4123 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4124 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4127 // Emit the non-flagged stores from the physregs.
4128 SmallVector<SDOperand, 8> OutChains;
4129 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4130 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4131 getValue(StoresToEmit[i].second),
4132 StoresToEmit[i].second, 0));
4133 if (!OutChains.empty())
4134 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4135 &OutChains[0], OutChains.size());
4140 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4141 SDOperand Src = getValue(I.getOperand(0));
4143 MVT::ValueType IntPtr = TLI.getPointerTy();
4145 if (IntPtr < Src.getValueType())
4146 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4147 else if (IntPtr > Src.getValueType())
4148 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4150 // Scale the source by the type size.
4151 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4152 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4153 Src, DAG.getIntPtrConstant(ElementSize));
4155 TargetLowering::ArgListTy Args;
4156 TargetLowering::ArgListEntry Entry;
4158 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4159 Args.push_back(Entry);
4161 std::pair<SDOperand,SDOperand> Result =
4162 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4163 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4164 setValue(&I, Result.first); // Pointers always fit in registers
4165 DAG.setRoot(Result.second);
4168 void SelectionDAGLowering::visitFree(FreeInst &I) {
4169 TargetLowering::ArgListTy Args;
4170 TargetLowering::ArgListEntry Entry;
4171 Entry.Node = getValue(I.getOperand(0));
4172 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4173 Args.push_back(Entry);
4174 MVT::ValueType IntPtr = TLI.getPointerTy();
4175 std::pair<SDOperand,SDOperand> Result =
4176 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4177 CallingConv::C, true,
4178 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4179 DAG.setRoot(Result.second);
4182 // EmitInstrWithCustomInserter - This method should be implemented by targets
4183 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4184 // instructions are special in various ways, which require special support to
4185 // insert. The specified MachineInstr is created but not inserted into any
4186 // basic blocks, and the scheduler passes ownership of it to this method.
4187 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4188 MachineBasicBlock *MBB) {
4189 cerr << "If a target marks an instruction with "
4190 << "'usesCustomDAGSchedInserter', it must implement "
4191 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4196 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4197 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4198 getValue(I.getOperand(1)),
4199 DAG.getSrcValue(I.getOperand(1))));
4202 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4203 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4204 getValue(I.getOperand(0)),
4205 DAG.getSrcValue(I.getOperand(0)));
4207 DAG.setRoot(V.getValue(1));
4210 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4211 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4212 getValue(I.getOperand(1)),
4213 DAG.getSrcValue(I.getOperand(1))));
4216 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4217 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4218 getValue(I.getOperand(1)),
4219 getValue(I.getOperand(2)),
4220 DAG.getSrcValue(I.getOperand(1)),
4221 DAG.getSrcValue(I.getOperand(2))));
4224 /// TargetLowering::LowerArguments - This is the default LowerArguments
4225 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4226 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4227 /// integrated into SDISel.
4228 std::vector<SDOperand>
4229 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4230 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4231 std::vector<SDOperand> Ops;
4232 Ops.push_back(DAG.getRoot());
4233 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4234 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4236 // Add one result value for each formal argument.
4237 std::vector<MVT::ValueType> RetVals;
4239 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4241 MVT::ValueType VT = getValueType(I->getType());
4242 ISD::ArgFlagsTy Flags;
4243 unsigned OriginalAlignment =
4244 getTargetData()->getABITypeAlignment(I->getType());
4246 if (F.paramHasAttr(j, ParamAttr::ZExt))
4248 if (F.paramHasAttr(j, ParamAttr::SExt))
4250 if (F.paramHasAttr(j, ParamAttr::InReg))
4252 if (F.paramHasAttr(j, ParamAttr::StructRet))
4254 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4256 const PointerType *Ty = cast<PointerType>(I->getType());
4257 const Type *ElementTy = Ty->getElementType();
4258 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4259 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4260 // For ByVal, alignment should be passed from FE. BE will guess if
4261 // this info is not there but there are cases it cannot get right.
4262 if (F.getParamAlignment(j))
4263 FrameAlign = F.getParamAlignment(j);
4264 Flags.setByValAlign(FrameAlign);
4265 Flags.setByValSize(FrameSize);
4267 if (F.paramHasAttr(j, ParamAttr::Nest))
4269 Flags.setOrigAlign(OriginalAlignment);
4271 MVT::ValueType RegisterVT = getRegisterType(VT);
4272 unsigned NumRegs = getNumRegisters(VT);
4273 for (unsigned i = 0; i != NumRegs; ++i) {
4274 RetVals.push_back(RegisterVT);
4275 ISD::ArgFlagsTy MyFlags = Flags;
4276 if (NumRegs > 1 && i == 0)
4278 // if it isn't first piece, alignment must be 1
4280 MyFlags.setOrigAlign(1);
4281 Ops.push_back(DAG.getArgFlags(MyFlags));
4285 RetVals.push_back(MVT::Other);
4288 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4289 DAG.getVTList(&RetVals[0], RetVals.size()),
4290 &Ops[0], Ops.size()).Val;
4292 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4293 // allows exposing the loads that may be part of the argument access to the
4294 // first DAGCombiner pass.
4295 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4297 // The number of results should match up, except that the lowered one may have
4298 // an extra flag result.
4299 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4300 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4301 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4302 && "Lowering produced unexpected number of results!");
4303 Result = TmpRes.Val;
4305 unsigned NumArgRegs = Result->getNumValues() - 1;
4306 DAG.setRoot(SDOperand(Result, NumArgRegs));
4308 // Set up the return result vector.
4312 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4314 MVT::ValueType VT = getValueType(I->getType());
4315 MVT::ValueType PartVT = getRegisterType(VT);
4317 unsigned NumParts = getNumRegisters(VT);
4318 SmallVector<SDOperand, 4> Parts(NumParts);
4319 for (unsigned j = 0; j != NumParts; ++j)
4320 Parts[j] = SDOperand(Result, i++);
4322 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4323 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4324 AssertOp = ISD::AssertSext;
4325 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4326 AssertOp = ISD::AssertZext;
4328 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4331 assert(i == NumArgRegs && "Argument register count mismatch!");
4336 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4337 /// implementation, which just inserts an ISD::CALL node, which is later custom
4338 /// lowered by the target to something concrete. FIXME: When all targets are
4339 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4340 std::pair<SDOperand, SDOperand>
4341 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4342 bool RetSExt, bool RetZExt, bool isVarArg,
4343 unsigned CallingConv, bool isTailCall,
4345 ArgListTy &Args, SelectionDAG &DAG) {
4346 SmallVector<SDOperand, 32> Ops;
4347 Ops.push_back(Chain); // Op#0 - Chain
4348 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4349 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4350 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4351 Ops.push_back(Callee);
4353 // Handle all of the outgoing arguments.
4354 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4355 MVT::ValueType VT = getValueType(Args[i].Ty);
4356 SDOperand Op = Args[i].Node;
4357 ISD::ArgFlagsTy Flags;
4358 unsigned OriginalAlignment =
4359 getTargetData()->getABITypeAlignment(Args[i].Ty);
4365 if (Args[i].isInReg)
4369 if (Args[i].isByVal) {
4371 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4372 const Type *ElementTy = Ty->getElementType();
4373 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4374 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4375 // For ByVal, alignment should come from FE. BE will guess if this
4376 // info is not there but there are cases it cannot get right.
4377 if (Args[i].Alignment)
4378 FrameAlign = Args[i].Alignment;
4379 Flags.setByValAlign(FrameAlign);
4380 Flags.setByValSize(FrameSize);
4384 Flags.setOrigAlign(OriginalAlignment);
4386 MVT::ValueType PartVT = getRegisterType(VT);
4387 unsigned NumParts = getNumRegisters(VT);
4388 SmallVector<SDOperand, 4> Parts(NumParts);
4389 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4392 ExtendKind = ISD::SIGN_EXTEND;
4393 else if (Args[i].isZExt)
4394 ExtendKind = ISD::ZERO_EXTEND;
4396 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4398 for (unsigned i = 0; i != NumParts; ++i) {
4399 // if it isn't first piece, alignment must be 1
4400 ISD::ArgFlagsTy MyFlags = Flags;
4401 if (NumParts > 1 && i == 0)
4404 MyFlags.setOrigAlign(1);
4406 Ops.push_back(Parts[i]);
4407 Ops.push_back(DAG.getArgFlags(MyFlags));
4411 // Figure out the result value types. We start by making a list of
4412 // the potentially illegal return value types.
4413 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4414 SmallVector<MVT::ValueType, 4> RetTys;
4415 ComputeValueVTs(*this, RetTy, RetTys);
4417 // Then we translate that to a list of legal types.
4418 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4419 MVT::ValueType VT = RetTys[I];
4420 MVT::ValueType RegisterVT = getRegisterType(VT);
4421 unsigned NumRegs = getNumRegisters(VT);
4422 for (unsigned i = 0; i != NumRegs; ++i)
4423 LoweredRetTys.push_back(RegisterVT);
4426 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4428 // Create the CALL node.
4429 SDOperand Res = DAG.getNode(ISD::CALL,
4430 DAG.getVTList(&LoweredRetTys[0],
4431 LoweredRetTys.size()),
4432 &Ops[0], Ops.size());
4433 Chain = Res.getValue(LoweredRetTys.size() - 1);
4435 // Gather up the call result into a single value.
4436 if (RetTy != Type::VoidTy) {
4437 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4440 AssertOp = ISD::AssertSext;
4442 AssertOp = ISD::AssertZext;
4444 SmallVector<SDOperand, 4> ReturnValues;
4446 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4447 MVT::ValueType VT = RetTys[I];
4448 MVT::ValueType RegisterVT = getRegisterType(VT);
4449 unsigned NumRegs = getNumRegisters(VT);
4450 unsigned RegNoEnd = NumRegs + RegNo;
4451 SmallVector<SDOperand, 4> Results;
4452 for (; RegNo != RegNoEnd; ++RegNo)
4453 Results.push_back(Res.getValue(RegNo));
4454 SDOperand ReturnValue =
4455 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4457 ReturnValues.push_back(ReturnValue);
4459 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4460 DAG.getNode(ISD::MERGE_VALUES,
4461 DAG.getVTList(&RetTys[0], RetTys.size()),
4462 &ReturnValues[0], ReturnValues.size());
4465 return std::make_pair(Res, Chain);
4468 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4469 assert(0 && "LowerOperation not implemented for this target!");
4474 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4475 SelectionDAG &DAG) {
4476 assert(0 && "CustomPromoteOperation not implemented for this target!");
4481 //===----------------------------------------------------------------------===//
4482 // SelectionDAGISel code
4483 //===----------------------------------------------------------------------===//
4485 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4486 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4489 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4490 AU.addRequired<AliasAnalysis>();
4491 AU.addRequired<CollectorModuleMetadata>();
4492 AU.setPreservesAll();
4497 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4498 // Get alias analysis for load/store combining.
4499 AA = &getAnalysis<AliasAnalysis>();
4501 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4502 if (MF.getFunction()->hasCollector())
4503 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4506 RegInfo = &MF.getRegInfo();
4507 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4509 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4511 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4512 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4513 // Mark landing pad.
4514 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4516 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4517 SelectBasicBlock(I, MF, FuncInfo);
4519 // Add function live-ins to entry block live-in set.
4520 BasicBlock *EntryBB = &Fn.getEntryBlock();
4521 BB = FuncInfo.MBBMap[EntryBB];
4522 if (!RegInfo->livein_empty())
4523 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4524 E = RegInfo->livein_end(); I != E; ++I)
4525 BB->addLiveIn(I->first);
4528 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4529 "Not all catch info was assigned to a landing pad!");
4535 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4536 SDOperand Op = getValue(V);
4537 assert((Op.getOpcode() != ISD::CopyFromReg ||
4538 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4539 "Copy from a reg to the same reg!");
4540 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4542 RegsForValue RFV(TLI, Reg, V->getType());
4543 SDOperand Chain = DAG.getEntryNode();
4544 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4545 PendingExports.push_back(Chain);
4548 void SelectionDAGISel::
4549 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4550 // If this is the entry block, emit arguments.
4551 Function &F = *LLVMBB->getParent();
4552 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4553 SDOperand OldRoot = SDL.DAG.getRoot();
4554 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4557 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4559 if (!AI->use_empty()) {
4560 SDL.setValue(AI, Args[a]);
4562 // If this argument is live outside of the entry block, insert a copy from
4563 // whereever we got it to the vreg that other BB's will reference it as.
4564 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4565 if (VMI != FuncInfo.ValueMap.end()) {
4566 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4570 // Finally, if the target has anything special to do, allow it to do so.
4571 // FIXME: this should insert code into the DAG!
4572 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4575 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4576 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4577 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4578 if (isSelector(I)) {
4579 // Apply the catch info to DestBB.
4580 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4582 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4583 FLI.CatchInfoFound.insert(I);
4588 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4589 /// DAG and fixes their tailcall attribute operand.
4590 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4591 TargetLowering& TLI) {
4592 SDNode * Ret = NULL;
4593 SDOperand Terminator = DAG.getRoot();
4596 if (Terminator.getOpcode() == ISD::RET) {
4597 Ret = Terminator.Val;
4600 // Fix tail call attribute of CALL nodes.
4601 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4602 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4603 if (BI->getOpcode() == ISD::CALL) {
4604 SDOperand OpRet(Ret, 0);
4605 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4606 bool isMarkedTailCall =
4607 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4608 // If CALL node has tail call attribute set to true and the call is not
4609 // eligible (no RET or the target rejects) the attribute is fixed to
4610 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4611 // must correctly identify tail call optimizable calls.
4612 if (isMarkedTailCall &&
4614 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4615 SmallVector<SDOperand, 32> Ops;
4617 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4618 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4622 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4624 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4630 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4631 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4632 FunctionLoweringInfo &FuncInfo) {
4633 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
4635 // Lower any arguments needed in this block if this is the entry block.
4636 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4637 LowerArguments(LLVMBB, SDL);
4639 BB = FuncInfo.MBBMap[LLVMBB];
4640 SDL.setCurrentBasicBlock(BB);
4642 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4644 if (MMI && BB->isLandingPad()) {
4645 // Add a label to mark the beginning of the landing pad. Deletion of the
4646 // landing pad can thus be detected via the MachineModuleInfo.
4647 unsigned LabelID = MMI->addLandingPad(BB);
4648 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4649 DAG.getConstant(LabelID, MVT::i32),
4650 DAG.getConstant(1, MVT::i32)));
4652 // Mark exception register as live in.
4653 unsigned Reg = TLI.getExceptionAddressRegister();
4654 if (Reg) BB->addLiveIn(Reg);
4656 // Mark exception selector register as live in.
4657 Reg = TLI.getExceptionSelectorRegister();
4658 if (Reg) BB->addLiveIn(Reg);
4660 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4661 // function and list of typeids logically belong to the invoke (or, if you
4662 // like, the basic block containing the invoke), and need to be associated
4663 // with it in the dwarf exception handling tables. Currently however the
4664 // information is provided by an intrinsic (eh.selector) that can be moved
4665 // to unexpected places by the optimizers: if the unwind edge is critical,
4666 // then breaking it can result in the intrinsics being in the successor of
4667 // the landing pad, not the landing pad itself. This results in exceptions
4668 // not being caught because no typeids are associated with the invoke.
4669 // This may not be the only way things can go wrong, but it is the only way
4670 // we try to work around for the moment.
4671 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4673 if (Br && Br->isUnconditional()) { // Critical edge?
4674 BasicBlock::iterator I, E;
4675 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4680 // No catch info found - try to extract some from the successor.
4681 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4685 // Lower all of the non-terminator instructions.
4686 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4690 // Ensure that all instructions which are used outside of their defining
4691 // blocks are available as virtual registers. Invoke is handled elsewhere.
4692 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4693 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4694 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4695 if (VMI != FuncInfo.ValueMap.end())
4696 SDL.CopyValueToVirtualRegister(I, VMI->second);
4699 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4700 // ensure constants are generated when needed. Remember the virtual registers
4701 // that need to be added to the Machine PHI nodes as input. We cannot just
4702 // directly add them, because expansion might result in multiple MBB's for one
4703 // BB. As such, the start of the BB might correspond to a different MBB than
4706 TerminatorInst *TI = LLVMBB->getTerminator();
4708 // Emit constants only once even if used by multiple PHI nodes.
4709 std::map<Constant*, unsigned> ConstantsOut;
4711 // Vector bool would be better, but vector<bool> is really slow.
4712 std::vector<unsigned char> SuccsHandled;
4713 if (TI->getNumSuccessors())
4714 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4716 // Check successor nodes' PHI nodes that expect a constant to be available
4718 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4719 BasicBlock *SuccBB = TI->getSuccessor(succ);
4720 if (!isa<PHINode>(SuccBB->begin())) continue;
4721 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4723 // If this terminator has multiple identical successors (common for
4724 // switches), only handle each succ once.
4725 unsigned SuccMBBNo = SuccMBB->getNumber();
4726 if (SuccsHandled[SuccMBBNo]) continue;
4727 SuccsHandled[SuccMBBNo] = true;
4729 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4732 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4733 // nodes and Machine PHI nodes, but the incoming operands have not been
4735 for (BasicBlock::iterator I = SuccBB->begin();
4736 (PN = dyn_cast<PHINode>(I)); ++I) {
4737 // Ignore dead phi's.
4738 if (PN->use_empty()) continue;
4741 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4743 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4744 unsigned &RegOut = ConstantsOut[C];
4746 RegOut = FuncInfo.CreateRegForValue(C);
4747 SDL.CopyValueToVirtualRegister(C, RegOut);
4751 Reg = FuncInfo.ValueMap[PHIOp];
4753 assert(isa<AllocaInst>(PHIOp) &&
4754 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4755 "Didn't codegen value into a register!??");
4756 Reg = FuncInfo.CreateRegForValue(PHIOp);
4757 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
4761 // Remember that this register needs to added to the machine PHI node as
4762 // the input for this MBB.
4763 MVT::ValueType VT = TLI.getValueType(PN->getType());
4764 unsigned NumRegisters = TLI.getNumRegisters(VT);
4765 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4766 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4769 ConstantsOut.clear();
4771 // Lower the terminator after the copies are emitted.
4772 SDL.visit(*LLVMBB->getTerminator());
4774 // Copy over any CaseBlock records that may now exist due to SwitchInst
4775 // lowering, as well as any jump table information.
4776 SwitchCases.clear();
4777 SwitchCases = SDL.SwitchCases;
4779 JTCases = SDL.JTCases;
4780 BitTestCases.clear();
4781 BitTestCases = SDL.BitTestCases;
4783 // Make sure the root of the DAG is up-to-date.
4784 DAG.setRoot(SDL.getControlRoot());
4786 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4787 // with correct tailcall attribute so that the target can rely on the tailcall
4788 // attribute indicating whether the call is really eligible for tail call
4790 CheckDAGForTailCallsAndFixThem(DAG, TLI);
4793 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4794 DOUT << "Lowered selection DAG:\n";
4797 // Run the DAG combiner in pre-legalize mode.
4798 DAG.Combine(false, *AA);
4800 DOUT << "Optimized lowered selection DAG:\n";
4803 // Second step, hack on the DAG until it only uses operations and types that
4804 // the target supports.
4805 #if 0 // Enable this some day.
4806 DAG.LegalizeTypes();
4807 // Someday even later, enable a dag combine pass here.
4811 DOUT << "Legalized selection DAG:\n";
4814 // Run the DAG combiner in post-legalize mode.
4815 DAG.Combine(true, *AA);
4817 DOUT << "Optimized legalized selection DAG:\n";
4820 if (ViewISelDAGs) DAG.viewGraph();
4822 // Third, instruction select all of the operations to machine code, adding the
4823 // code to the MachineBasicBlock.
4824 InstructionSelectBasicBlock(DAG);
4826 DOUT << "Selected machine code:\n";
4830 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4831 FunctionLoweringInfo &FuncInfo) {
4832 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4834 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4837 // First step, lower LLVM code to some DAG. This DAG may use operations and
4838 // types that are not supported by the target.
4839 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4841 // Second step, emit the lowered DAG as machine code.
4842 CodeGenAndEmitDAG(DAG);
4845 DOUT << "Total amount of phi nodes to update: "
4846 << PHINodesToUpdate.size() << "\n";
4847 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4848 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4849 << ", " << PHINodesToUpdate[i].second << ")\n";);
4851 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4852 // PHI nodes in successors.
4853 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4854 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4855 MachineInstr *PHI = PHINodesToUpdate[i].first;
4856 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4857 "This is not a machine PHI node that we are updating!");
4858 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4860 PHI->addOperand(MachineOperand::CreateMBB(BB));
4865 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4866 // Lower header first, if it wasn't already lowered
4867 if (!BitTestCases[i].Emitted) {
4868 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4870 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4871 // Set the current basic block to the mbb we wish to insert the code into
4872 BB = BitTestCases[i].Parent;
4873 HSDL.setCurrentBasicBlock(BB);
4875 HSDL.visitBitTestHeader(BitTestCases[i]);
4876 HSDAG.setRoot(HSDL.getRoot());
4877 CodeGenAndEmitDAG(HSDAG);
4880 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4881 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4883 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
4884 // Set the current basic block to the mbb we wish to insert the code into
4885 BB = BitTestCases[i].Cases[j].ThisBB;
4886 BSDL.setCurrentBasicBlock(BB);
4889 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4890 BitTestCases[i].Reg,
4891 BitTestCases[i].Cases[j]);
4893 BSDL.visitBitTestCase(BitTestCases[i].Default,
4894 BitTestCases[i].Reg,
4895 BitTestCases[i].Cases[j]);
4898 BSDAG.setRoot(BSDL.getRoot());
4899 CodeGenAndEmitDAG(BSDAG);
4903 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4904 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4905 MachineBasicBlock *PHIBB = PHI->getParent();
4906 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4907 "This is not a machine PHI node that we are updating!");
4908 // This is "default" BB. We have two jumps to it. From "header" BB and
4909 // from last "case" BB.
4910 if (PHIBB == BitTestCases[i].Default) {
4911 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4913 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4914 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4916 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4919 // One of "cases" BB.
4920 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4921 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4922 if (cBB->succ_end() !=
4923 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4924 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4926 PHI->addOperand(MachineOperand::CreateMBB(cBB));
4932 // If the JumpTable record is filled in, then we need to emit a jump table.
4933 // Updating the PHI nodes is tricky in this case, since we need to determine
4934 // whether the PHI is a successor of the range check MBB or the jump table MBB
4935 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4936 // Lower header first, if it wasn't already lowered
4937 if (!JTCases[i].first.Emitted) {
4938 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4940 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4941 // Set the current basic block to the mbb we wish to insert the code into
4942 BB = JTCases[i].first.HeaderBB;
4943 HSDL.setCurrentBasicBlock(BB);
4945 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4946 HSDAG.setRoot(HSDL.getRoot());
4947 CodeGenAndEmitDAG(HSDAG);
4950 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4952 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
4953 // Set the current basic block to the mbb we wish to insert the code into
4954 BB = JTCases[i].second.MBB;
4955 JSDL.setCurrentBasicBlock(BB);
4957 JSDL.visitJumpTable(JTCases[i].second);
4958 JSDAG.setRoot(JSDL.getRoot());
4959 CodeGenAndEmitDAG(JSDAG);
4962 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4963 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4964 MachineBasicBlock *PHIBB = PHI->getParent();
4965 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4966 "This is not a machine PHI node that we are updating!");
4967 // "default" BB. We can go there only from header BB.
4968 if (PHIBB == JTCases[i].second.Default) {
4969 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4971 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
4973 // JT BB. Just iterate over successors here
4974 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4975 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4977 PHI->addOperand(MachineOperand::CreateMBB(BB));
4982 // If the switch block involved a branch to one of the actual successors, we
4983 // need to update PHI nodes in that block.
4984 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4985 MachineInstr *PHI = PHINodesToUpdate[i].first;
4986 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4987 "This is not a machine PHI node that we are updating!");
4988 if (BB->isSuccessor(PHI->getParent())) {
4989 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4991 PHI->addOperand(MachineOperand::CreateMBB(BB));
4995 // If we generated any switch lowering information, build and codegen any
4996 // additional DAGs necessary.
4997 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4998 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5000 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5002 // Set the current basic block to the mbb we wish to insert the code into
5003 BB = SwitchCases[i].ThisBB;
5004 SDL.setCurrentBasicBlock(BB);
5007 SDL.visitSwitchCase(SwitchCases[i]);
5008 SDAG.setRoot(SDL.getRoot());
5009 CodeGenAndEmitDAG(SDAG);
5011 // Handle any PHI nodes in successors of this chunk, as if we were coming
5012 // from the original BB before switch expansion. Note that PHI nodes can
5013 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5014 // handle them the right number of times.
5015 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5016 for (MachineBasicBlock::iterator Phi = BB->begin();
5017 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5018 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5019 for (unsigned pn = 0; ; ++pn) {
5020 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5021 if (PHINodesToUpdate[pn].first == Phi) {
5022 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5024 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5030 // Don't process RHS if same block as LHS.
5031 if (BB == SwitchCases[i].FalseBB)
5032 SwitchCases[i].FalseBB = 0;
5034 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5035 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5036 SwitchCases[i].FalseBB = 0;
5038 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5043 //===----------------------------------------------------------------------===//
5044 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5045 /// target node in the graph.
5046 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5047 if (ViewSchedDAGs) DAG.viewGraph();
5049 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5053 RegisterScheduler::setDefault(Ctor);
5056 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5059 if (ViewSUnitDAGs) SL->viewGraph();
5065 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5066 return new HazardRecognizer();
5069 //===----------------------------------------------------------------------===//
5070 // Helper functions used by the generated instruction selector.
5071 //===----------------------------------------------------------------------===//
5072 // Calls to these methods are generated by tblgen.
5074 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5075 /// the dag combiner simplified the 255, we still want to match. RHS is the
5076 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5077 /// specified in the .td file (e.g. 255).
5078 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5079 int64_t DesiredMaskS) const {
5080 const APInt &ActualMask = RHS->getAPIntValue();
5081 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5083 // If the actual mask exactly matches, success!
5084 if (ActualMask == DesiredMask)
5087 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5088 if (ActualMask.intersects(~DesiredMask))
5091 // Otherwise, the DAG Combiner may have proven that the value coming in is
5092 // either already zero or is not demanded. Check for known zero input bits.
5093 APInt NeededMask = DesiredMask & ~ActualMask;
5094 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5097 // TODO: check to see if missing bits are just not demanded.
5099 // Otherwise, this pattern doesn't match.
5103 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5104 /// the dag combiner simplified the 255, we still want to match. RHS is the
5105 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5106 /// specified in the .td file (e.g. 255).
5107 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5108 int64_t DesiredMaskS) const {
5109 const APInt &ActualMask = RHS->getAPIntValue();
5110 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5112 // If the actual mask exactly matches, success!
5113 if (ActualMask == DesiredMask)
5116 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5117 if (ActualMask.intersects(~DesiredMask))
5120 // Otherwise, the DAG Combiner may have proven that the value coming in is
5121 // either already zero or is not demanded. Check for known zero input bits.
5122 APInt NeededMask = DesiredMask & ~ActualMask;
5124 APInt KnownZero, KnownOne;
5125 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5127 // If all the missing bits in the or are already known to be set, match!
5128 if ((NeededMask & KnownOne) == NeededMask)
5131 // TODO: check to see if missing bits are just not demanded.
5133 // Otherwise, this pattern doesn't match.
5138 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5139 /// by tblgen. Others should not call it.
5140 void SelectionDAGISel::
5141 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5142 std::vector<SDOperand> InOps;
5143 std::swap(InOps, Ops);
5145 Ops.push_back(InOps[0]); // input chain.
5146 Ops.push_back(InOps[1]); // input asm string.
5148 unsigned i = 2, e = InOps.size();
5149 if (InOps[e-1].getValueType() == MVT::Flag)
5150 --e; // Don't process a flag operand if it is here.
5153 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5154 if ((Flags & 7) != 4 /*MEM*/) {
5155 // Just skip over this operand, copying the operands verbatim.
5156 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5157 i += (Flags >> 3) + 1;
5159 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5160 // Otherwise, this is a memory operand. Ask the target to select it.
5161 std::vector<SDOperand> SelOps;
5162 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5163 cerr << "Could not match memory address. Inline asm failure!\n";
5167 // Add this to the output node.
5168 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5169 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5171 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5176 // Add the flag input back if present.
5177 if (e != InOps.size())
5178 Ops.push_back(InOps.back());
5181 char SelectionDAGISel::ID = 0;