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 const SmallVector<unsigned, 4> ®s,
157 MVT::ValueType regvt, MVT::ValueType valuevt)
158 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
159 RegsForValue(const TargetLowering &tli,
160 const SmallVector<unsigned, 4> ®s,
161 const SmallVector<MVT::ValueType, 4> ®vts,
162 const SmallVector<MVT::ValueType, 4> &valuevts)
163 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
164 RegsForValue(const TargetLowering &tli,
165 unsigned Reg, const Type *Ty) : TLI(&tli) {
166 ComputeValueVTs(tli, Ty, ValueVTs);
168 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
169 MVT::ValueType ValueVT = ValueVTs[Value];
170 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
171 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
172 for (unsigned i = 0; i != NumRegs; ++i)
173 Regs.push_back(Reg + i);
174 RegVTs.push_back(RegisterVT);
179 /// append - Add the specified values to this one.
180 void append(const RegsForValue &RHS) {
182 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
183 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
184 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
188 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
189 /// this value and returns the result as a ValueVTs value. This uses
190 /// Chain/Flag as the input and updates them for the output Chain/Flag.
191 /// If the Flag pointer is NULL, no flag is used.
192 SDOperand getCopyFromRegs(SelectionDAG &DAG,
193 SDOperand &Chain, SDOperand *Flag) const;
195 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
196 /// specified value into the registers specified by this object. This uses
197 /// Chain/Flag as the input and updates them for the output Chain/Flag.
198 /// If the Flag pointer is NULL, no flag is used.
199 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
200 SDOperand &Chain, SDOperand *Flag) const;
202 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
203 /// operand list. This adds the code marker and includes the number of
204 /// values added into it.
205 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
206 std::vector<SDOperand> &Ops) const;
211 //===--------------------------------------------------------------------===//
212 /// createDefaultScheduler - This creates an instruction scheduler appropriate
214 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
216 MachineBasicBlock *BB) {
217 TargetLowering &TLI = IS->getTargetLowering();
219 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
220 return createTDListDAGScheduler(IS, DAG, BB);
222 assert(TLI.getSchedulingPreference() ==
223 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
224 return createBURRListDAGScheduler(IS, DAG, BB);
229 //===--------------------------------------------------------------------===//
230 /// FunctionLoweringInfo - This contains information that is global to a
231 /// function that is used when lowering a region of the function.
232 class FunctionLoweringInfo {
237 MachineRegisterInfo &RegInfo;
239 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
241 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
242 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
244 /// ValueMap - Since we emit code for the function a basic block at a time,
245 /// we must remember which virtual registers hold the values for
246 /// cross-basic-block values.
247 DenseMap<const Value*, unsigned> ValueMap;
249 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
250 /// the entry block. This allows the allocas to be efficiently referenced
251 /// anywhere in the function.
252 std::map<const AllocaInst*, int> StaticAllocaMap;
255 SmallSet<Instruction*, 8> CatchInfoLost;
256 SmallSet<Instruction*, 8> CatchInfoFound;
259 unsigned MakeReg(MVT::ValueType VT) {
260 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
263 /// isExportedInst - Return true if the specified value is an instruction
264 /// exported from its block.
265 bool isExportedInst(const Value *V) {
266 return ValueMap.count(V);
269 unsigned CreateRegForValue(const Value *V);
271 unsigned InitializeRegForValue(const Value *V) {
272 unsigned &R = ValueMap[V];
273 assert(R == 0 && "Already initialized this value register!");
274 return R = CreateRegForValue(V);
279 /// isSelector - Return true if this instruction is a call to the
280 /// eh.selector intrinsic.
281 static bool isSelector(Instruction *I) {
282 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
283 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
284 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
288 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
289 /// PHI nodes or outside of the basic block that defines it, or used by a
290 /// switch or atomic instruction, which may expand to multiple basic blocks.
291 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
292 if (isa<PHINode>(I)) return true;
293 BasicBlock *BB = I->getParent();
294 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
295 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
296 // FIXME: Remove switchinst special case.
297 isa<SwitchInst>(*UI))
302 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
303 /// entry block, return true. This includes arguments used by switches, since
304 /// the switch may expand into multiple basic blocks.
305 static bool isOnlyUsedInEntryBlock(Argument *A) {
306 BasicBlock *Entry = A->getParent()->begin();
307 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
308 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
309 return false; // Use not in entry block.
313 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
314 Function &fn, MachineFunction &mf)
315 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
317 // Create a vreg for each argument register that is not dead and is used
318 // outside of the entry block for the function.
319 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
321 if (!isOnlyUsedInEntryBlock(AI))
322 InitializeRegForValue(AI);
324 // Initialize the mapping of values to registers. This is only set up for
325 // instruction values that are used outside of the block that defines
327 Function::iterator BB = Fn.begin(), EB = Fn.end();
328 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
329 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
330 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
331 const Type *Ty = AI->getAllocatedType();
332 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
334 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
337 TySize *= CUI->getZExtValue(); // Get total allocated size.
338 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
339 StaticAllocaMap[AI] =
340 MF.getFrameInfo()->CreateStackObject(TySize, Align);
343 for (; BB != EB; ++BB)
344 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
345 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
346 if (!isa<AllocaInst>(I) ||
347 !StaticAllocaMap.count(cast<AllocaInst>(I)))
348 InitializeRegForValue(I);
350 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
351 // also creates the initial PHI MachineInstrs, though none of the input
352 // operands are populated.
353 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
354 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
356 MF.getBasicBlockList().push_back(MBB);
358 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
361 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
362 if (PN->use_empty()) continue;
364 MVT::ValueType VT = TLI.getValueType(PN->getType());
365 unsigned NumRegisters = TLI.getNumRegisters(VT);
366 unsigned PHIReg = ValueMap[PN];
367 assert(PHIReg && "PHI node does not have an assigned virtual register!");
368 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
369 for (unsigned i = 0; i != NumRegisters; ++i)
370 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
375 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
376 /// the correctly promoted or expanded types. Assign these registers
377 /// consecutive vreg numbers and return the first assigned number.
379 /// In the case that the given value has struct or array type, this function
380 /// will assign registers for each member or element.
382 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
383 SmallVector<MVT::ValueType, 4> ValueVTs;
384 ComputeValueVTs(TLI, V->getType(), ValueVTs);
386 unsigned FirstReg = 0;
387 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
388 MVT::ValueType ValueVT = ValueVTs[Value];
389 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
391 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
392 for (unsigned i = 0; i != NumRegs; ++i) {
393 unsigned R = MakeReg(RegisterVT);
394 if (!FirstReg) FirstReg = R;
400 //===----------------------------------------------------------------------===//
401 /// SelectionDAGLowering - This is the common target-independent lowering
402 /// implementation that is parameterized by a TargetLowering object.
403 /// Also, targets can overload any lowering method.
406 class SelectionDAGLowering {
407 MachineBasicBlock *CurMBB;
409 DenseMap<const Value*, SDOperand> NodeMap;
411 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
412 /// them up and then emit token factor nodes when possible. This allows us to
413 /// get simple disambiguation between loads without worrying about alias
415 std::vector<SDOperand> PendingLoads;
417 /// PendingExports - CopyToReg nodes that copy values to virtual registers
418 /// for export to other blocks need to be emitted before any terminator
419 /// instruction, but they have no other ordering requirements. We bunch them
420 /// up and the emit a single tokenfactor for them just before terminator
422 std::vector<SDOperand> PendingExports;
424 /// Case - A struct to record the Value for a switch case, and the
425 /// case's target basic block.
429 MachineBasicBlock* BB;
431 Case() : Low(0), High(0), BB(0) { }
432 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
433 Low(low), High(high), BB(bb) { }
434 uint64_t size() const {
435 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
436 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
437 return (rHigh - rLow + 1ULL);
443 MachineBasicBlock* BB;
446 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
447 Mask(mask), BB(bb), Bits(bits) { }
450 typedef std::vector<Case> CaseVector;
451 typedef std::vector<CaseBits> CaseBitsVector;
452 typedef CaseVector::iterator CaseItr;
453 typedef std::pair<CaseItr, CaseItr> CaseRange;
455 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
456 /// of conditional branches.
458 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
459 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
461 /// CaseBB - The MBB in which to emit the compare and branch
462 MachineBasicBlock *CaseBB;
463 /// LT, GE - If nonzero, we know the current case value must be less-than or
464 /// greater-than-or-equal-to these Constants.
467 /// Range - A pair of iterators representing the range of case values to be
468 /// processed at this point in the binary search tree.
472 typedef std::vector<CaseRec> CaseRecVector;
474 /// The comparison function for sorting the switch case values in the vector.
475 /// WARNING: Case ranges should be disjoint!
477 bool operator () (const Case& C1, const Case& C2) {
478 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
479 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
480 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
481 return CI1->getValue().slt(CI2->getValue());
486 bool operator () (const CaseBits& C1, const CaseBits& C2) {
487 return C1.Bits > C2.Bits;
491 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
494 // TLI - This is information that describes the available target features we
495 // need for lowering. This indicates when operations are unavailable,
496 // implemented with a libcall, etc.
499 const TargetData *TD;
502 /// SwitchCases - Vector of CaseBlock structures used to communicate
503 /// SwitchInst code generation information.
504 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
505 /// JTCases - Vector of JumpTable structures used to communicate
506 /// SwitchInst code generation information.
507 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
508 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
510 /// FuncInfo - Information about the function as a whole.
512 FunctionLoweringInfo &FuncInfo;
514 /// GCI - Garbage collection metadata for the function.
515 CollectorMetadata *GCI;
517 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
519 FunctionLoweringInfo &funcinfo,
520 CollectorMetadata *gci)
521 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
522 FuncInfo(funcinfo), GCI(gci) {
525 /// getRoot - Return the current virtual root of the Selection DAG,
526 /// flushing any PendingLoad items. This must be done before emitting
527 /// a store or any other node that may need to be ordered after any
528 /// prior load instructions.
530 SDOperand getRoot() {
531 if (PendingLoads.empty())
532 return DAG.getRoot();
534 if (PendingLoads.size() == 1) {
535 SDOperand Root = PendingLoads[0];
537 PendingLoads.clear();
541 // Otherwise, we have to make a token factor node.
542 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
543 &PendingLoads[0], PendingLoads.size());
544 PendingLoads.clear();
549 /// getControlRoot - Similar to getRoot, but instead of flushing all the
550 /// PendingLoad items, flush all the PendingExports items. It is necessary
551 /// to do this before emitting a terminator instruction.
553 SDOperand getControlRoot() {
554 SDOperand Root = DAG.getRoot();
556 if (PendingExports.empty())
559 // Turn all of the CopyToReg chains into one factored node.
560 if (Root.getOpcode() != ISD::EntryToken) {
561 unsigned i = 0, e = PendingExports.size();
562 for (; i != e; ++i) {
563 assert(PendingExports[i].Val->getNumOperands() > 1);
564 if (PendingExports[i].Val->getOperand(0) == Root)
565 break; // Don't add the root if we already indirectly depend on it.
569 PendingExports.push_back(Root);
572 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
574 PendingExports.size());
575 PendingExports.clear();
580 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
582 void visit(Instruction &I) { visit(I.getOpcode(), I); }
584 void visit(unsigned Opcode, User &I) {
585 // Note: this doesn't use InstVisitor, because it has to work with
586 // ConstantExpr's in addition to instructions.
588 default: assert(0 && "Unknown instruction type encountered!");
590 // Build the switch statement using the Instruction.def file.
591 #define HANDLE_INST(NUM, OPCODE, CLASS) \
592 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
593 #include "llvm/Instruction.def"
597 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
599 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
600 const Value *SV, SDOperand Root,
601 bool isVolatile, unsigned Alignment);
603 SDOperand getValue(const Value *V);
605 void setValue(const Value *V, SDOperand NewN) {
606 SDOperand &N = NodeMap[V];
607 assert(N.Val == 0 && "Already set a value for this node!");
611 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
612 std::set<unsigned> &OutputRegs,
613 std::set<unsigned> &InputRegs);
615 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
616 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
618 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
619 void ExportFromCurrentBlock(Value *V);
620 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
621 MachineBasicBlock *LandingPad = NULL);
623 // Terminator instructions.
624 void visitRet(ReturnInst &I);
625 void visitBr(BranchInst &I);
626 void visitSwitch(SwitchInst &I);
627 void visitUnreachable(UnreachableInst &I) { /* noop */ }
629 // Helpers for visitSwitch
630 bool handleSmallSwitchRange(CaseRec& CR,
631 CaseRecVector& WorkList,
633 MachineBasicBlock* Default);
634 bool handleJTSwitchCase(CaseRec& CR,
635 CaseRecVector& WorkList,
637 MachineBasicBlock* Default);
638 bool handleBTSplitSwitchCase(CaseRec& CR,
639 CaseRecVector& WorkList,
641 MachineBasicBlock* Default);
642 bool handleBitTestsSwitchCase(CaseRec& CR,
643 CaseRecVector& WorkList,
645 MachineBasicBlock* Default);
646 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
647 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
648 void visitBitTestCase(MachineBasicBlock* NextMBB,
650 SelectionDAGISel::BitTestCase &B);
651 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
652 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
653 SelectionDAGISel::JumpTableHeader &JTH);
655 // These all get lowered before this pass.
656 void visitInvoke(InvokeInst &I);
657 void visitUnwind(UnwindInst &I);
659 void visitBinary(User &I, unsigned OpCode);
660 void visitShift(User &I, unsigned Opcode);
661 void visitAdd(User &I) {
662 if (I.getType()->isFPOrFPVector())
663 visitBinary(I, ISD::FADD);
665 visitBinary(I, ISD::ADD);
667 void visitSub(User &I);
668 void visitMul(User &I) {
669 if (I.getType()->isFPOrFPVector())
670 visitBinary(I, ISD::FMUL);
672 visitBinary(I, ISD::MUL);
674 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
675 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
676 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
677 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
678 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
679 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
680 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
681 void visitOr (User &I) { visitBinary(I, ISD::OR); }
682 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
683 void visitShl (User &I) { visitShift(I, ISD::SHL); }
684 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
685 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
686 void visitICmp(User &I);
687 void visitFCmp(User &I);
688 // Visit the conversion instructions
689 void visitTrunc(User &I);
690 void visitZExt(User &I);
691 void visitSExt(User &I);
692 void visitFPTrunc(User &I);
693 void visitFPExt(User &I);
694 void visitFPToUI(User &I);
695 void visitFPToSI(User &I);
696 void visitUIToFP(User &I);
697 void visitSIToFP(User &I);
698 void visitPtrToInt(User &I);
699 void visitIntToPtr(User &I);
700 void visitBitCast(User &I);
702 void visitExtractElement(User &I);
703 void visitInsertElement(User &I);
704 void visitShuffleVector(User &I);
706 void visitGetElementPtr(User &I);
707 void visitSelect(User &I);
709 void visitMalloc(MallocInst &I);
710 void visitFree(FreeInst &I);
711 void visitAlloca(AllocaInst &I);
712 void visitLoad(LoadInst &I);
713 void visitStore(StoreInst &I);
714 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
715 void visitCall(CallInst &I);
716 void visitInlineAsm(CallSite CS);
717 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
718 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
720 void visitVAStart(CallInst &I);
721 void visitVAArg(VAArgInst &I);
722 void visitVAEnd(CallInst &I);
723 void visitVACopy(CallInst &I);
725 void visitGetResult(GetResultInst &I);
727 void visitUserOp1(Instruction &I) {
728 assert(0 && "UserOp1 should not exist at instruction selection time!");
731 void visitUserOp2(Instruction &I) {
732 assert(0 && "UserOp2 should not exist at instruction selection time!");
737 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
740 } // end namespace llvm
743 /// getCopyFromParts - Create a value that contains the specified legal parts
744 /// combined into the value they represent. If the parts combine to a type
745 /// larger then ValueVT then AssertOp can be used to specify whether the extra
746 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
747 /// (ISD::AssertSext).
748 static SDOperand getCopyFromParts(SelectionDAG &DAG,
749 const SDOperand *Parts,
751 MVT::ValueType PartVT,
752 MVT::ValueType ValueVT,
753 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
754 assert(NumParts > 0 && "No parts to assemble!");
755 TargetLowering &TLI = DAG.getTargetLoweringInfo();
756 SDOperand Val = Parts[0];
759 // Assemble the value from multiple parts.
760 if (!MVT::isVector(ValueVT)) {
761 unsigned PartBits = MVT::getSizeInBits(PartVT);
762 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
764 // Assemble the power of 2 part.
765 unsigned RoundParts = NumParts & (NumParts - 1) ?
766 1 << Log2_32(NumParts) : NumParts;
767 unsigned RoundBits = PartBits * RoundParts;
768 MVT::ValueType RoundVT = RoundBits == ValueBits ?
769 ValueVT : MVT::getIntegerType(RoundBits);
772 if (RoundParts > 2) {
773 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
774 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
775 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
781 if (TLI.isBigEndian())
783 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
785 if (RoundParts < NumParts) {
786 // Assemble the trailing non-power-of-2 part.
787 unsigned OddParts = NumParts - RoundParts;
788 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
789 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
791 // Combine the round and odd parts.
793 if (TLI.isBigEndian())
795 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
796 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
797 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
798 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
799 TLI.getShiftAmountTy()));
800 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
801 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
804 // Handle a multi-element vector.
805 MVT::ValueType IntermediateVT, RegisterVT;
806 unsigned NumIntermediates;
808 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
811 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
812 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
813 assert(RegisterVT == Parts[0].getValueType() &&
814 "Part type doesn't match part!");
816 // Assemble the parts into intermediate operands.
817 SmallVector<SDOperand, 8> Ops(NumIntermediates);
818 if (NumIntermediates == NumParts) {
819 // If the register was not expanded, truncate or copy the value,
821 for (unsigned i = 0; i != NumParts; ++i)
822 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
823 PartVT, IntermediateVT);
824 } else if (NumParts > 0) {
825 // If the intermediate type was expanded, build the intermediate operands
827 assert(NumParts % NumIntermediates == 0 &&
828 "Must expand into a divisible number of parts!");
829 unsigned Factor = NumParts / NumIntermediates;
830 for (unsigned i = 0; i != NumIntermediates; ++i)
831 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
832 PartVT, IntermediateVT);
835 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
837 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
838 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
839 ValueVT, &Ops[0], NumIntermediates);
843 // There is now one part, held in Val. Correct it to match ValueVT.
844 PartVT = Val.getValueType();
846 if (PartVT == ValueVT)
849 if (MVT::isVector(PartVT)) {
850 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
851 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
854 if (MVT::isVector(ValueVT)) {
855 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
856 MVT::getVectorNumElements(ValueVT) == 1 &&
857 "Only trivial scalar-to-vector conversions should get here!");
858 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
861 if (MVT::isInteger(PartVT) &&
862 MVT::isInteger(ValueVT)) {
863 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
864 // For a truncate, see if we have any information to
865 // indicate whether the truncated bits will always be
866 // zero or sign-extension.
867 if (AssertOp != ISD::DELETED_NODE)
868 Val = DAG.getNode(AssertOp, PartVT, Val,
869 DAG.getValueType(ValueVT));
870 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
872 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
876 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
877 if (ValueVT < Val.getValueType())
878 // FP_ROUND's are always exact here.
879 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
880 DAG.getIntPtrConstant(1));
881 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
884 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
885 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
887 assert(0 && "Unknown mismatch!");
891 /// getCopyToParts - Create a series of nodes that contain the specified value
892 /// split into legal parts. If the parts contain more bits than Val, then, for
893 /// integers, ExtendKind can be used to specify how to generate the extra bits.
894 static void getCopyToParts(SelectionDAG &DAG,
898 MVT::ValueType PartVT,
899 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
900 TargetLowering &TLI = DAG.getTargetLoweringInfo();
901 MVT::ValueType PtrVT = TLI.getPointerTy();
902 MVT::ValueType ValueVT = Val.getValueType();
903 unsigned PartBits = MVT::getSizeInBits(PartVT);
904 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
909 if (!MVT::isVector(ValueVT)) {
910 if (PartVT == ValueVT) {
911 assert(NumParts == 1 && "No-op copy with multiple parts!");
916 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
917 // If the parts cover more bits than the value has, promote the value.
918 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
919 assert(NumParts == 1 && "Do not know what to promote to!");
920 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
921 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
922 ValueVT = MVT::getIntegerType(NumParts * PartBits);
923 Val = DAG.getNode(ExtendKind, ValueVT, Val);
925 assert(0 && "Unknown mismatch!");
927 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
928 // Different types of the same size.
929 assert(NumParts == 1 && PartVT != ValueVT);
930 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
931 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
932 // If the parts cover less bits than value has, truncate the value.
933 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
934 ValueVT = MVT::getIntegerType(NumParts * PartBits);
935 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
937 assert(0 && "Unknown mismatch!");
941 // The value may have changed - recompute ValueVT.
942 ValueVT = Val.getValueType();
943 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
944 "Failed to tile the value with PartVT!");
947 assert(PartVT == ValueVT && "Type conversion failed!");
952 // Expand the value into multiple parts.
953 if (NumParts & (NumParts - 1)) {
954 // The number of parts is not a power of 2. Split off and copy the tail.
955 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
956 "Do not know what to expand to!");
957 unsigned RoundParts = 1 << Log2_32(NumParts);
958 unsigned RoundBits = RoundParts * PartBits;
959 unsigned OddParts = NumParts - RoundParts;
960 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
961 DAG.getConstant(RoundBits,
962 TLI.getShiftAmountTy()));
963 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
964 if (TLI.isBigEndian())
965 // The odd parts were reversed by getCopyToParts - unreverse them.
966 std::reverse(Parts + RoundParts, Parts + NumParts);
967 NumParts = RoundParts;
968 ValueVT = MVT::getIntegerType(NumParts * PartBits);
969 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
972 // The number of parts is a power of 2. Repeatedly bisect the value using
974 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
975 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
977 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
978 for (unsigned i = 0; i < NumParts; i += StepSize) {
979 unsigned ThisBits = StepSize * PartBits / 2;
980 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
981 SDOperand &Part0 = Parts[i];
982 SDOperand &Part1 = Parts[i+StepSize/2];
984 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
985 DAG.getConstant(1, PtrVT));
986 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
987 DAG.getConstant(0, PtrVT));
989 if (ThisBits == PartBits && ThisVT != PartVT) {
990 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
991 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
996 if (TLI.isBigEndian())
997 std::reverse(Parts, Parts + NumParts);
1003 if (NumParts == 1) {
1004 if (PartVT != ValueVT) {
1005 if (MVT::isVector(PartVT)) {
1006 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1008 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
1009 MVT::getVectorNumElements(ValueVT) == 1 &&
1010 "Only trivial vector-to-scalar conversions should get here!");
1011 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1012 DAG.getConstant(0, PtrVT));
1020 // Handle a multi-element vector.
1021 MVT::ValueType IntermediateVT, RegisterVT;
1022 unsigned NumIntermediates;
1024 DAG.getTargetLoweringInfo()
1025 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1027 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1029 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1030 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1032 // Split the vector into intermediate operands.
1033 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1034 for (unsigned i = 0; i != NumIntermediates; ++i)
1035 if (MVT::isVector(IntermediateVT))
1036 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1037 IntermediateVT, Val,
1038 DAG.getConstant(i * (NumElements / NumIntermediates),
1041 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1042 IntermediateVT, Val,
1043 DAG.getConstant(i, PtrVT));
1045 // Split the intermediate operands into legal parts.
1046 if (NumParts == NumIntermediates) {
1047 // If the register was not expanded, promote or copy the value,
1049 for (unsigned i = 0; i != NumParts; ++i)
1050 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1051 } else if (NumParts > 0) {
1052 // If the intermediate type was expanded, split each the value into
1054 assert(NumParts % NumIntermediates == 0 &&
1055 "Must expand into a divisible number of parts!");
1056 unsigned Factor = NumParts / NumIntermediates;
1057 for (unsigned i = 0; i != NumIntermediates; ++i)
1058 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1063 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1064 SDOperand &N = NodeMap[V];
1065 if (N.Val) return N;
1067 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1068 MVT::ValueType VT = TLI.getValueType(V->getType(), true);
1070 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1071 return N = DAG.getConstant(CI->getValue(), VT);
1073 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1074 return N = DAG.getGlobalAddress(GV, VT);
1076 if (isa<ConstantPointerNull>(C))
1077 return N = DAG.getConstant(0, TLI.getPointerTy());
1079 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1080 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1082 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1083 return N = DAG.getNode(ISD::UNDEF, VT);
1085 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1086 visit(CE->getOpcode(), *CE);
1087 SDOperand N1 = NodeMap[V];
1088 assert(N1.Val && "visit didn't populate the ValueMap!");
1092 const VectorType *VecTy = cast<VectorType>(V->getType());
1093 unsigned NumElements = VecTy->getNumElements();
1095 // Now that we know the number and type of the elements, get that number of
1096 // elements into the Ops array based on what kind of constant it is.
1097 SmallVector<SDOperand, 16> Ops;
1098 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1099 for (unsigned i = 0; i != NumElements; ++i)
1100 Ops.push_back(getValue(CP->getOperand(i)));
1102 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1103 "Unknown vector constant!");
1104 MVT::ValueType EltVT = TLI.getValueType(VecTy->getElementType());
1107 if (isa<UndefValue>(C))
1108 Op = DAG.getNode(ISD::UNDEF, EltVT);
1109 else if (MVT::isFloatingPoint(EltVT))
1110 Op = DAG.getConstantFP(0, EltVT);
1112 Op = DAG.getConstant(0, EltVT);
1113 Ops.assign(NumElements, Op);
1116 // Create a BUILD_VECTOR node.
1117 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1120 // If this is a static alloca, generate it as the frameindex instead of
1122 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1123 std::map<const AllocaInst*, int>::iterator SI =
1124 FuncInfo.StaticAllocaMap.find(AI);
1125 if (SI != FuncInfo.StaticAllocaMap.end())
1126 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1129 unsigned InReg = FuncInfo.ValueMap[V];
1130 assert(InReg && "Value not in map!");
1132 RegsForValue RFV(TLI, InReg, V->getType());
1133 SDOperand Chain = DAG.getEntryNode();
1134 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1138 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1139 if (I.getNumOperands() == 0) {
1140 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1144 SmallVector<SDOperand, 8> NewValues;
1145 NewValues.push_back(getControlRoot());
1146 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1147 SDOperand RetOp = getValue(I.getOperand(i));
1148 MVT::ValueType VT = RetOp.getValueType();
1150 // FIXME: C calling convention requires the return type to be promoted to
1151 // at least 32-bit. But this is not necessary for non-C calling conventions.
1152 if (MVT::isInteger(VT)) {
1153 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1154 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1158 unsigned NumParts = TLI.getNumRegisters(VT);
1159 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1160 SmallVector<SDOperand, 4> Parts(NumParts);
1161 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1163 const Function *F = I.getParent()->getParent();
1164 if (F->paramHasAttr(0, ParamAttr::SExt))
1165 ExtendKind = ISD::SIGN_EXTEND;
1166 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1167 ExtendKind = ISD::ZERO_EXTEND;
1169 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1171 for (unsigned i = 0; i < NumParts; ++i) {
1172 NewValues.push_back(Parts[i]);
1173 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1176 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1177 &NewValues[0], NewValues.size()));
1180 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1181 /// the current basic block, add it to ValueMap now so that we'll get a
1183 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1184 // No need to export constants.
1185 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1187 // Already exported?
1188 if (FuncInfo.isExportedInst(V)) return;
1190 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1191 CopyValueToVirtualRegister(V, Reg);
1194 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1195 const BasicBlock *FromBB) {
1196 // The operands of the setcc have to be in this block. We don't know
1197 // how to export them from some other block.
1198 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1199 // Can export from current BB.
1200 if (VI->getParent() == FromBB)
1203 // Is already exported, noop.
1204 return FuncInfo.isExportedInst(V);
1207 // If this is an argument, we can export it if the BB is the entry block or
1208 // if it is already exported.
1209 if (isa<Argument>(V)) {
1210 if (FromBB == &FromBB->getParent()->getEntryBlock())
1213 // Otherwise, can only export this if it is already exported.
1214 return FuncInfo.isExportedInst(V);
1217 // Otherwise, constants can always be exported.
1221 static bool InBlock(const Value *V, const BasicBlock *BB) {
1222 if (const Instruction *I = dyn_cast<Instruction>(V))
1223 return I->getParent() == BB;
1227 /// FindMergedConditions - If Cond is an expression like
1228 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1229 MachineBasicBlock *TBB,
1230 MachineBasicBlock *FBB,
1231 MachineBasicBlock *CurBB,
1233 // If this node is not part of the or/and tree, emit it as a branch.
1234 Instruction *BOp = dyn_cast<Instruction>(Cond);
1236 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1237 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1238 BOp->getParent() != CurBB->getBasicBlock() ||
1239 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1240 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1241 const BasicBlock *BB = CurBB->getBasicBlock();
1243 // If the leaf of the tree is a comparison, merge the condition into
1245 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1246 // The operands of the cmp have to be in this block. We don't know
1247 // how to export them from some other block. If this is the first block
1248 // of the sequence, no exporting is needed.
1250 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1251 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1252 BOp = cast<Instruction>(Cond);
1253 ISD::CondCode Condition;
1254 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1255 switch (IC->getPredicate()) {
1256 default: assert(0 && "Unknown icmp predicate opcode!");
1257 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1258 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1259 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1260 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1261 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1262 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1263 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1264 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1265 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1266 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1268 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1269 ISD::CondCode FPC, FOC;
1270 switch (FC->getPredicate()) {
1271 default: assert(0 && "Unknown fcmp predicate opcode!");
1272 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1273 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1274 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1275 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1276 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1277 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1278 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1279 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1280 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1281 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1282 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1283 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1284 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1285 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1286 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1287 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1289 if (FiniteOnlyFPMath())
1294 Condition = ISD::SETEQ; // silence warning.
1295 assert(0 && "Unknown compare instruction");
1298 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1299 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1300 SwitchCases.push_back(CB);
1304 // Create a CaseBlock record representing this branch.
1305 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1306 NULL, TBB, FBB, CurBB);
1307 SwitchCases.push_back(CB);
1312 // Create TmpBB after CurBB.
1313 MachineFunction::iterator BBI = CurBB;
1314 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1315 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1317 if (Opc == Instruction::Or) {
1318 // Codegen X | Y as:
1326 // Emit the LHS condition.
1327 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1329 // Emit the RHS condition into TmpBB.
1330 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1332 assert(Opc == Instruction::And && "Unknown merge op!");
1333 // Codegen X & Y as:
1340 // This requires creation of TmpBB after CurBB.
1342 // Emit the LHS condition.
1343 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1345 // Emit the RHS condition into TmpBB.
1346 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1350 /// If the set of cases should be emitted as a series of branches, return true.
1351 /// If we should emit this as a bunch of and/or'd together conditions, return
1354 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1355 if (Cases.size() != 2) return true;
1357 // If this is two comparisons of the same values or'd or and'd together, they
1358 // will get folded into a single comparison, so don't emit two blocks.
1359 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1360 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1361 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1362 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1369 void SelectionDAGLowering::visitBr(BranchInst &I) {
1370 // Update machine-CFG edges.
1371 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1373 // Figure out which block is immediately after the current one.
1374 MachineBasicBlock *NextBlock = 0;
1375 MachineFunction::iterator BBI = CurMBB;
1376 if (++BBI != CurMBB->getParent()->end())
1379 if (I.isUnconditional()) {
1380 // If this is not a fall-through branch, emit the branch.
1381 if (Succ0MBB != NextBlock)
1382 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1383 DAG.getBasicBlock(Succ0MBB)));
1385 // Update machine-CFG edges.
1386 CurMBB->addSuccessor(Succ0MBB);
1390 // If this condition is one of the special cases we handle, do special stuff
1392 Value *CondVal = I.getCondition();
1393 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1395 // If this is a series of conditions that are or'd or and'd together, emit
1396 // this as a sequence of branches instead of setcc's with and/or operations.
1397 // For example, instead of something like:
1410 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1411 if (BOp->hasOneUse() &&
1412 (BOp->getOpcode() == Instruction::And ||
1413 BOp->getOpcode() == Instruction::Or)) {
1414 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1415 // If the compares in later blocks need to use values not currently
1416 // exported from this block, export them now. This block should always
1417 // be the first entry.
1418 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1420 // Allow some cases to be rejected.
1421 if (ShouldEmitAsBranches(SwitchCases)) {
1422 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1423 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1424 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1427 // Emit the branch for this block.
1428 visitSwitchCase(SwitchCases[0]);
1429 SwitchCases.erase(SwitchCases.begin());
1433 // Okay, we decided not to do this, remove any inserted MBB's and clear
1435 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1436 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1438 SwitchCases.clear();
1442 // Create a CaseBlock record representing this branch.
1443 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1444 NULL, Succ0MBB, Succ1MBB, CurMBB);
1445 // Use visitSwitchCase to actually insert the fast branch sequence for this
1447 visitSwitchCase(CB);
1450 /// visitSwitchCase - Emits the necessary code to represent a single node in
1451 /// the binary search tree resulting from lowering a switch instruction.
1452 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1454 SDOperand CondLHS = getValue(CB.CmpLHS);
1456 // Build the setcc now.
1457 if (CB.CmpMHS == NULL) {
1458 // Fold "(X == true)" to X and "(X == false)" to !X to
1459 // handle common cases produced by branch lowering.
1460 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1462 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1463 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1464 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1466 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1468 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1470 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1471 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1473 SDOperand CmpOp = getValue(CB.CmpMHS);
1474 MVT::ValueType VT = CmpOp.getValueType();
1476 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1477 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1479 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1480 Cond = DAG.getSetCC(MVT::i1, SUB,
1481 DAG.getConstant(High-Low, VT), ISD::SETULE);
1486 // Set NextBlock to be the MBB immediately after the current one, if any.
1487 // This is used to avoid emitting unnecessary branches to the next block.
1488 MachineBasicBlock *NextBlock = 0;
1489 MachineFunction::iterator BBI = CurMBB;
1490 if (++BBI != CurMBB->getParent()->end())
1493 // If the lhs block is the next block, invert the condition so that we can
1494 // fall through to the lhs instead of the rhs block.
1495 if (CB.TrueBB == NextBlock) {
1496 std::swap(CB.TrueBB, CB.FalseBB);
1497 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1498 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1500 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1501 DAG.getBasicBlock(CB.TrueBB));
1502 if (CB.FalseBB == NextBlock)
1503 DAG.setRoot(BrCond);
1505 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1506 DAG.getBasicBlock(CB.FalseBB)));
1507 // Update successor info
1508 CurMBB->addSuccessor(CB.TrueBB);
1509 CurMBB->addSuccessor(CB.FalseBB);
1512 /// visitJumpTable - Emit JumpTable node in the current MBB
1513 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1514 // Emit the code for the jump table
1515 assert(JT.Reg != -1U && "Should lower JT Header first!");
1516 MVT::ValueType PTy = TLI.getPointerTy();
1517 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1518 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1519 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1524 /// visitJumpTableHeader - This function emits necessary code to produce index
1525 /// in the JumpTable from switch case.
1526 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1527 SelectionDAGISel::JumpTableHeader &JTH) {
1528 // Subtract the lowest switch case value from the value being switched on
1529 // and conditional branch to default mbb if the result is greater than the
1530 // difference between smallest and largest cases.
1531 SDOperand SwitchOp = getValue(JTH.SValue);
1532 MVT::ValueType VT = SwitchOp.getValueType();
1533 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1534 DAG.getConstant(JTH.First, VT));
1536 // The SDNode we just created, which holds the value being switched on
1537 // minus the the smallest case value, needs to be copied to a virtual
1538 // register so it can be used as an index into the jump table in a
1539 // subsequent basic block. This value may be smaller or larger than the
1540 // target's pointer type, and therefore require extension or truncating.
1541 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1542 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1544 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1546 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1547 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1548 JT.Reg = JumpTableReg;
1550 // Emit the range check for the jump table, and branch to the default
1551 // block for the switch statement if the value being switched on exceeds
1552 // the largest case in the switch.
1553 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1554 DAG.getConstant(JTH.Last-JTH.First,VT),
1557 // Set NextBlock to be the MBB immediately after the current one, if any.
1558 // This is used to avoid emitting unnecessary branches to the next block.
1559 MachineBasicBlock *NextBlock = 0;
1560 MachineFunction::iterator BBI = CurMBB;
1561 if (++BBI != CurMBB->getParent()->end())
1564 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1565 DAG.getBasicBlock(JT.Default));
1567 if (JT.MBB == NextBlock)
1568 DAG.setRoot(BrCond);
1570 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1571 DAG.getBasicBlock(JT.MBB)));
1576 /// visitBitTestHeader - This function emits necessary code to produce value
1577 /// suitable for "bit tests"
1578 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1579 // Subtract the minimum value
1580 SDOperand SwitchOp = getValue(B.SValue);
1581 MVT::ValueType VT = SwitchOp.getValueType();
1582 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1583 DAG.getConstant(B.First, VT));
1586 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1587 DAG.getConstant(B.Range, VT),
1591 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1592 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1594 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1596 // Make desired shift
1597 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1598 DAG.getConstant(1, TLI.getPointerTy()),
1601 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1602 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1605 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1606 DAG.getBasicBlock(B.Default));
1608 // Set NextBlock to be the MBB immediately after the current one, if any.
1609 // This is used to avoid emitting unnecessary branches to the next block.
1610 MachineBasicBlock *NextBlock = 0;
1611 MachineFunction::iterator BBI = CurMBB;
1612 if (++BBI != CurMBB->getParent()->end())
1615 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1616 if (MBB == NextBlock)
1617 DAG.setRoot(BrRange);
1619 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1620 DAG.getBasicBlock(MBB)));
1622 CurMBB->addSuccessor(B.Default);
1623 CurMBB->addSuccessor(MBB);
1628 /// visitBitTestCase - this function produces one "bit test"
1629 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1631 SelectionDAGISel::BitTestCase &B) {
1632 // Emit bit tests and jumps
1633 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1635 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1637 DAG.getConstant(B.Mask,
1638 TLI.getPointerTy()));
1639 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1640 DAG.getConstant(0, TLI.getPointerTy()),
1642 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1643 AndCmp, DAG.getBasicBlock(B.TargetBB));
1645 // Set NextBlock to be the MBB immediately after the current one, if any.
1646 // This is used to avoid emitting unnecessary branches to the next block.
1647 MachineBasicBlock *NextBlock = 0;
1648 MachineFunction::iterator BBI = CurMBB;
1649 if (++BBI != CurMBB->getParent()->end())
1652 if (NextMBB == NextBlock)
1655 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1656 DAG.getBasicBlock(NextMBB)));
1658 CurMBB->addSuccessor(B.TargetBB);
1659 CurMBB->addSuccessor(NextMBB);
1664 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1665 // Retrieve successors.
1666 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1667 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1669 if (isa<InlineAsm>(I.getCalledValue()))
1672 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1674 // If the value of the invoke is used outside of its defining block, make it
1675 // available as a virtual register.
1676 if (!I.use_empty()) {
1677 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1678 if (VMI != FuncInfo.ValueMap.end())
1679 CopyValueToVirtualRegister(&I, VMI->second);
1682 // Drop into normal successor.
1683 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1684 DAG.getBasicBlock(Return)));
1686 // Update successor info
1687 CurMBB->addSuccessor(Return);
1688 CurMBB->addSuccessor(LandingPad);
1691 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1694 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1695 /// small case ranges).
1696 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1697 CaseRecVector& WorkList,
1699 MachineBasicBlock* Default) {
1700 Case& BackCase = *(CR.Range.second-1);
1702 // Size is the number of Cases represented by this range.
1703 unsigned Size = CR.Range.second - CR.Range.first;
1707 // Get the MachineFunction which holds the current MBB. This is used when
1708 // inserting any additional MBBs necessary to represent the switch.
1709 MachineFunction *CurMF = CurMBB->getParent();
1711 // Figure out which block is immediately after the current one.
1712 MachineBasicBlock *NextBlock = 0;
1713 MachineFunction::iterator BBI = CR.CaseBB;
1715 if (++BBI != CurMBB->getParent()->end())
1718 // TODO: If any two of the cases has the same destination, and if one value
1719 // is the same as the other, but has one bit unset that the other has set,
1720 // use bit manipulation to do two compares at once. For example:
1721 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1723 // Rearrange the case blocks so that the last one falls through if possible.
1724 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1725 // The last case block won't fall through into 'NextBlock' if we emit the
1726 // branches in this order. See if rearranging a case value would help.
1727 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1728 if (I->BB == NextBlock) {
1729 std::swap(*I, BackCase);
1735 // Create a CaseBlock record representing a conditional branch to
1736 // the Case's target mbb if the value being switched on SV is equal
1738 MachineBasicBlock *CurBlock = CR.CaseBB;
1739 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1740 MachineBasicBlock *FallThrough;
1742 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1743 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1745 // If the last case doesn't match, go to the default block.
1746 FallThrough = Default;
1749 Value *RHS, *LHS, *MHS;
1751 if (I->High == I->Low) {
1752 // This is just small small case range :) containing exactly 1 case
1754 LHS = SV; RHS = I->High; MHS = NULL;
1757 LHS = I->Low; MHS = SV; RHS = I->High;
1759 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1760 I->BB, FallThrough, CurBlock);
1762 // If emitting the first comparison, just call visitSwitchCase to emit the
1763 // code into the current block. Otherwise, push the CaseBlock onto the
1764 // vector to be later processed by SDISel, and insert the node's MBB
1765 // before the next MBB.
1766 if (CurBlock == CurMBB)
1767 visitSwitchCase(CB);
1769 SwitchCases.push_back(CB);
1771 CurBlock = FallThrough;
1777 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1778 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1779 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1782 /// handleJTSwitchCase - Emit jumptable for current switch case range
1783 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1784 CaseRecVector& WorkList,
1786 MachineBasicBlock* Default) {
1787 Case& FrontCase = *CR.Range.first;
1788 Case& BackCase = *(CR.Range.second-1);
1790 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1791 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1794 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1798 if (!areJTsAllowed(TLI) || TSize <= 3)
1801 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1805 DOUT << "Lowering jump table\n"
1806 << "First entry: " << First << ". Last entry: " << Last << "\n"
1807 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1809 // Get the MachineFunction which holds the current MBB. This is used when
1810 // inserting any additional MBBs necessary to represent the switch.
1811 MachineFunction *CurMF = CurMBB->getParent();
1813 // Figure out which block is immediately after the current one.
1814 MachineBasicBlock *NextBlock = 0;
1815 MachineFunction::iterator BBI = CR.CaseBB;
1817 if (++BBI != CurMBB->getParent()->end())
1820 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1822 // Create a new basic block to hold the code for loading the address
1823 // of the jump table, and jumping to it. Update successor information;
1824 // we will either branch to the default case for the switch, or the jump
1826 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1827 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1828 CR.CaseBB->addSuccessor(Default);
1829 CR.CaseBB->addSuccessor(JumpTableBB);
1831 // Build a vector of destination BBs, corresponding to each target
1832 // of the jump table. If the value of the jump table slot corresponds to
1833 // a case statement, push the case's BB onto the vector, otherwise, push
1835 std::vector<MachineBasicBlock*> DestBBs;
1836 int64_t TEI = First;
1837 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1838 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1839 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1841 if ((Low <= TEI) && (TEI <= High)) {
1842 DestBBs.push_back(I->BB);
1846 DestBBs.push_back(Default);
1850 // Update successor info. Add one edge to each unique successor.
1851 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1852 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1853 E = DestBBs.end(); I != E; ++I) {
1854 if (!SuccsHandled[(*I)->getNumber()]) {
1855 SuccsHandled[(*I)->getNumber()] = true;
1856 JumpTableBB->addSuccessor(*I);
1860 // Create a jump table index for this jump table, or return an existing
1862 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1864 // Set the jump table information so that we can codegen it as a second
1865 // MachineBasicBlock
1866 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1867 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1868 (CR.CaseBB == CurMBB));
1869 if (CR.CaseBB == CurMBB)
1870 visitJumpTableHeader(JT, JTH);
1872 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1877 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1879 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1880 CaseRecVector& WorkList,
1882 MachineBasicBlock* Default) {
1883 // Get the MachineFunction which holds the current MBB. This is used when
1884 // inserting any additional MBBs necessary to represent the switch.
1885 MachineFunction *CurMF = CurMBB->getParent();
1887 // Figure out which block is immediately after the current one.
1888 MachineBasicBlock *NextBlock = 0;
1889 MachineFunction::iterator BBI = CR.CaseBB;
1891 if (++BBI != CurMBB->getParent()->end())
1894 Case& FrontCase = *CR.Range.first;
1895 Case& BackCase = *(CR.Range.second-1);
1896 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1898 // Size is the number of Cases represented by this range.
1899 unsigned Size = CR.Range.second - CR.Range.first;
1901 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1902 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1904 CaseItr Pivot = CR.Range.first + Size/2;
1906 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1907 // (heuristically) allow us to emit JumpTable's later.
1909 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1913 uint64_t LSize = FrontCase.size();
1914 uint64_t RSize = TSize-LSize;
1915 DOUT << "Selecting best pivot: \n"
1916 << "First: " << First << ", Last: " << Last <<"\n"
1917 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1918 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1920 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1921 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1922 assert((RBegin-LEnd>=1) && "Invalid case distance");
1923 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1924 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1925 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1926 // Should always split in some non-trivial place
1928 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1929 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1930 << "Metric: " << Metric << "\n";
1931 if (FMetric < Metric) {
1934 DOUT << "Current metric set to: " << FMetric << "\n";
1940 if (areJTsAllowed(TLI)) {
1941 // If our case is dense we *really* should handle it earlier!
1942 assert((FMetric > 0) && "Should handle dense range earlier!");
1944 Pivot = CR.Range.first + Size/2;
1947 CaseRange LHSR(CR.Range.first, Pivot);
1948 CaseRange RHSR(Pivot, CR.Range.second);
1949 Constant *C = Pivot->Low;
1950 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1952 // We know that we branch to the LHS if the Value being switched on is
1953 // less than the Pivot value, C. We use this to optimize our binary
1954 // tree a bit, by recognizing that if SV is greater than or equal to the
1955 // LHS's Case Value, and that Case Value is exactly one less than the
1956 // Pivot's Value, then we can branch directly to the LHS's Target,
1957 // rather than creating a leaf node for it.
1958 if ((LHSR.second - LHSR.first) == 1 &&
1959 LHSR.first->High == CR.GE &&
1960 cast<ConstantInt>(C)->getSExtValue() ==
1961 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1962 TrueBB = LHSR.first->BB;
1964 TrueBB = new MachineBasicBlock(LLVMBB);
1965 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1966 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1969 // Similar to the optimization above, if the Value being switched on is
1970 // known to be less than the Constant CR.LT, and the current Case Value
1971 // is CR.LT - 1, then we can branch directly to the target block for
1972 // the current Case Value, rather than emitting a RHS leaf node for it.
1973 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1974 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1975 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1976 FalseBB = RHSR.first->BB;
1978 FalseBB = new MachineBasicBlock(LLVMBB);
1979 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1980 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1983 // Create a CaseBlock record representing a conditional branch to
1984 // the LHS node if the value being switched on SV is less than C.
1985 // Otherwise, branch to LHS.
1986 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1987 TrueBB, FalseBB, CR.CaseBB);
1989 if (CR.CaseBB == CurMBB)
1990 visitSwitchCase(CB);
1992 SwitchCases.push_back(CB);
1997 /// handleBitTestsSwitchCase - if current case range has few destination and
1998 /// range span less, than machine word bitwidth, encode case range into series
1999 /// of masks and emit bit tests with these masks.
2000 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2001 CaseRecVector& WorkList,
2003 MachineBasicBlock* Default){
2004 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
2006 Case& FrontCase = *CR.Range.first;
2007 Case& BackCase = *(CR.Range.second-1);
2009 // Get the MachineFunction which holds the current MBB. This is used when
2010 // inserting any additional MBBs necessary to represent the switch.
2011 MachineFunction *CurMF = CurMBB->getParent();
2013 unsigned numCmps = 0;
2014 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2016 // Single case counts one, case range - two.
2017 if (I->Low == I->High)
2023 // Count unique destinations
2024 SmallSet<MachineBasicBlock*, 4> Dests;
2025 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2026 Dests.insert(I->BB);
2027 if (Dests.size() > 3)
2028 // Don't bother the code below, if there are too much unique destinations
2031 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2032 << "Total number of comparisons: " << numCmps << "\n";
2034 // Compute span of values.
2035 Constant* minValue = FrontCase.Low;
2036 Constant* maxValue = BackCase.High;
2037 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2038 cast<ConstantInt>(minValue)->getSExtValue();
2039 DOUT << "Compare range: " << range << "\n"
2040 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2041 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2043 if (range>=IntPtrBits ||
2044 (!(Dests.size() == 1 && numCmps >= 3) &&
2045 !(Dests.size() == 2 && numCmps >= 5) &&
2046 !(Dests.size() >= 3 && numCmps >= 6)))
2049 DOUT << "Emitting bit tests\n";
2050 int64_t lowBound = 0;
2052 // Optimize the case where all the case values fit in a
2053 // word without having to subtract minValue. In this case,
2054 // we can optimize away the subtraction.
2055 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2056 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2057 range = cast<ConstantInt>(maxValue)->getSExtValue();
2059 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2062 CaseBitsVector CasesBits;
2063 unsigned i, count = 0;
2065 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2066 MachineBasicBlock* Dest = I->BB;
2067 for (i = 0; i < count; ++i)
2068 if (Dest == CasesBits[i].BB)
2072 assert((count < 3) && "Too much destinations to test!");
2073 CasesBits.push_back(CaseBits(0, Dest, 0));
2077 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2078 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2080 for (uint64_t j = lo; j <= hi; j++) {
2081 CasesBits[i].Mask |= 1ULL << j;
2082 CasesBits[i].Bits++;
2086 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2088 SelectionDAGISel::BitTestInfo BTC;
2090 // Figure out which block is immediately after the current one.
2091 MachineFunction::iterator BBI = CR.CaseBB;
2094 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2097 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2098 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2099 << ", BB: " << CasesBits[i].BB << "\n";
2101 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2102 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2103 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2108 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2109 -1U, (CR.CaseBB == CurMBB),
2110 CR.CaseBB, Default, BTC);
2112 if (CR.CaseBB == CurMBB)
2113 visitBitTestHeader(BTB);
2115 BitTestCases.push_back(BTB);
2121 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2122 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2123 const SwitchInst& SI) {
2124 unsigned numCmps = 0;
2126 // Start with "simple" cases
2127 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2128 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2129 Cases.push_back(Case(SI.getSuccessorValue(i),
2130 SI.getSuccessorValue(i),
2133 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2135 // Merge case into clusters
2136 if (Cases.size()>=2)
2137 // Must recompute end() each iteration because it may be
2138 // invalidated by erase if we hold on to it
2139 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2140 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2141 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2142 MachineBasicBlock* nextBB = J->BB;
2143 MachineBasicBlock* currentBB = I->BB;
2145 // If the two neighboring cases go to the same destination, merge them
2146 // into a single case.
2147 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2155 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2156 if (I->Low != I->High)
2157 // A range counts double, since it requires two compares.
2164 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2165 // Figure out which block is immediately after the current one.
2166 MachineBasicBlock *NextBlock = 0;
2167 MachineFunction::iterator BBI = CurMBB;
2169 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2171 // If there is only the default destination, branch to it if it is not the
2172 // next basic block. Otherwise, just fall through.
2173 if (SI.getNumOperands() == 2) {
2174 // Update machine-CFG edges.
2176 // If this is not a fall-through branch, emit the branch.
2177 if (Default != NextBlock)
2178 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2179 DAG.getBasicBlock(Default)));
2181 CurMBB->addSuccessor(Default);
2185 // If there are any non-default case statements, create a vector of Cases
2186 // representing each one, and sort the vector so that we can efficiently
2187 // create a binary search tree from them.
2189 unsigned numCmps = Clusterify(Cases, SI);
2190 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2191 << ". Total compares: " << numCmps << "\n";
2193 // Get the Value to be switched on and default basic blocks, which will be
2194 // inserted into CaseBlock records, representing basic blocks in the binary
2196 Value *SV = SI.getOperand(0);
2198 // Push the initial CaseRec onto the worklist
2199 CaseRecVector WorkList;
2200 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2202 while (!WorkList.empty()) {
2203 // Grab a record representing a case range to process off the worklist
2204 CaseRec CR = WorkList.back();
2205 WorkList.pop_back();
2207 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2210 // If the range has few cases (two or less) emit a series of specific
2212 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2215 // If the switch has more than 5 blocks, and at least 40% dense, and the
2216 // target supports indirect branches, then emit a jump table rather than
2217 // lowering the switch to a binary tree of conditional branches.
2218 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2221 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2222 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2223 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2228 void SelectionDAGLowering::visitSub(User &I) {
2229 // -0.0 - X --> fneg
2230 const Type *Ty = I.getType();
2231 if (isa<VectorType>(Ty)) {
2232 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2233 const VectorType *DestTy = cast<VectorType>(I.getType());
2234 const Type *ElTy = DestTy->getElementType();
2235 if (ElTy->isFloatingPoint()) {
2236 unsigned VL = DestTy->getNumElements();
2237 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2238 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2240 SDOperand Op2 = getValue(I.getOperand(1));
2241 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2247 if (Ty->isFloatingPoint()) {
2248 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2249 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2250 SDOperand Op2 = getValue(I.getOperand(1));
2251 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2256 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2259 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2260 SDOperand Op1 = getValue(I.getOperand(0));
2261 SDOperand Op2 = getValue(I.getOperand(1));
2263 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2266 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2267 SDOperand Op1 = getValue(I.getOperand(0));
2268 SDOperand Op2 = getValue(I.getOperand(1));
2270 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2271 MVT::getSizeInBits(Op2.getValueType()))
2272 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2273 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2274 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2276 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2279 void SelectionDAGLowering::visitICmp(User &I) {
2280 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2281 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2282 predicate = IC->getPredicate();
2283 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2284 predicate = ICmpInst::Predicate(IC->getPredicate());
2285 SDOperand Op1 = getValue(I.getOperand(0));
2286 SDOperand Op2 = getValue(I.getOperand(1));
2287 ISD::CondCode Opcode;
2288 switch (predicate) {
2289 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2290 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2291 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2292 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2293 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2294 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2295 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2296 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2297 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2298 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2300 assert(!"Invalid ICmp predicate value");
2301 Opcode = ISD::SETEQ;
2304 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2307 void SelectionDAGLowering::visitFCmp(User &I) {
2308 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2309 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2310 predicate = FC->getPredicate();
2311 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2312 predicate = FCmpInst::Predicate(FC->getPredicate());
2313 SDOperand Op1 = getValue(I.getOperand(0));
2314 SDOperand Op2 = getValue(I.getOperand(1));
2315 ISD::CondCode Condition, FOC, FPC;
2316 switch (predicate) {
2317 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2318 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2319 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2320 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2321 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2322 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2323 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2324 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2325 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2326 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2327 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2328 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2329 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2330 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2331 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2332 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2334 assert(!"Invalid FCmp predicate value");
2335 FOC = FPC = ISD::SETFALSE;
2338 if (FiniteOnlyFPMath())
2342 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2345 void SelectionDAGLowering::visitSelect(User &I) {
2346 SDOperand Cond = getValue(I.getOperand(0));
2347 SDOperand TrueVal = getValue(I.getOperand(1));
2348 SDOperand FalseVal = getValue(I.getOperand(2));
2349 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2350 TrueVal, FalseVal));
2354 void SelectionDAGLowering::visitTrunc(User &I) {
2355 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2356 SDOperand N = getValue(I.getOperand(0));
2357 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2358 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2361 void SelectionDAGLowering::visitZExt(User &I) {
2362 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2363 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2364 SDOperand N = getValue(I.getOperand(0));
2365 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2366 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2369 void SelectionDAGLowering::visitSExt(User &I) {
2370 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2371 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2372 SDOperand N = getValue(I.getOperand(0));
2373 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2374 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2377 void SelectionDAGLowering::visitFPTrunc(User &I) {
2378 // FPTrunc 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_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2384 void SelectionDAGLowering::visitFPExt(User &I){
2385 // FPTrunc 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_EXTEND, DestVT, N));
2391 void SelectionDAGLowering::visitFPToUI(User &I) {
2392 // FPToUI 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::FP_TO_UINT, DestVT, N));
2398 void SelectionDAGLowering::visitFPToSI(User &I) {
2399 // FPToSI 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::FP_TO_SINT, DestVT, N));
2405 void SelectionDAGLowering::visitUIToFP(User &I) {
2406 // UIToFP is never a no-op cast, no need to check
2407 SDOperand N = getValue(I.getOperand(0));
2408 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2409 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2412 void SelectionDAGLowering::visitSIToFP(User &I){
2413 // UIToFP is never a no-op cast, no need to check
2414 SDOperand N = getValue(I.getOperand(0));
2415 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2416 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2419 void SelectionDAGLowering::visitPtrToInt(User &I) {
2420 // What to do depends on the size of the integer and the size of the pointer.
2421 // We can either truncate, zero extend, or no-op, accordingly.
2422 SDOperand N = getValue(I.getOperand(0));
2423 MVT::ValueType SrcVT = N.getValueType();
2424 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2426 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2427 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2429 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2430 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2431 setValue(&I, Result);
2434 void SelectionDAGLowering::visitIntToPtr(User &I) {
2435 // What to do depends on the size of the integer and the size of the pointer.
2436 // We can either truncate, zero extend, or no-op, accordingly.
2437 SDOperand N = getValue(I.getOperand(0));
2438 MVT::ValueType SrcVT = N.getValueType();
2439 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2440 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2441 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2443 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2444 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2447 void SelectionDAGLowering::visitBitCast(User &I) {
2448 SDOperand N = getValue(I.getOperand(0));
2449 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2451 // BitCast assures us that source and destination are the same size so this
2452 // is either a BIT_CONVERT or a no-op.
2453 if (DestVT != N.getValueType())
2454 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2456 setValue(&I, N); // noop cast.
2459 void SelectionDAGLowering::visitInsertElement(User &I) {
2460 SDOperand InVec = getValue(I.getOperand(0));
2461 SDOperand InVal = getValue(I.getOperand(1));
2462 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2463 getValue(I.getOperand(2)));
2465 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2466 TLI.getValueType(I.getType()),
2467 InVec, InVal, InIdx));
2470 void SelectionDAGLowering::visitExtractElement(User &I) {
2471 SDOperand InVec = getValue(I.getOperand(0));
2472 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2473 getValue(I.getOperand(1)));
2474 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2475 TLI.getValueType(I.getType()), InVec, InIdx));
2478 void SelectionDAGLowering::visitShuffleVector(User &I) {
2479 SDOperand V1 = getValue(I.getOperand(0));
2480 SDOperand V2 = getValue(I.getOperand(1));
2481 SDOperand Mask = getValue(I.getOperand(2));
2483 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2484 TLI.getValueType(I.getType()),
2489 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2490 SDOperand N = getValue(I.getOperand(0));
2491 const Type *Ty = I.getOperand(0)->getType();
2493 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2496 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2497 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2500 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2501 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2502 DAG.getIntPtrConstant(Offset));
2504 Ty = StTy->getElementType(Field);
2506 Ty = cast<SequentialType>(Ty)->getElementType();
2508 // If this is a constant subscript, handle it quickly.
2509 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2510 if (CI->getZExtValue() == 0) continue;
2512 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2513 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2514 DAG.getIntPtrConstant(Offs));
2518 // N = N + Idx * ElementSize;
2519 uint64_t ElementSize = TD->getABITypeSize(Ty);
2520 SDOperand IdxN = getValue(Idx);
2522 // If the index is smaller or larger than intptr_t, truncate or extend
2524 if (IdxN.getValueType() < N.getValueType()) {
2525 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2526 } else if (IdxN.getValueType() > N.getValueType())
2527 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2529 // If this is a multiply by a power of two, turn it into a shl
2530 // immediately. This is a very common case.
2531 if (isPowerOf2_64(ElementSize)) {
2532 unsigned Amt = Log2_64(ElementSize);
2533 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2534 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2535 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2539 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2540 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2541 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2547 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2548 // If this is a fixed sized alloca in the entry block of the function,
2549 // allocate it statically on the stack.
2550 if (FuncInfo.StaticAllocaMap.count(&I))
2551 return; // getValue will auto-populate this.
2553 const Type *Ty = I.getAllocatedType();
2554 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2556 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2559 SDOperand AllocSize = getValue(I.getArraySize());
2560 MVT::ValueType IntPtr = TLI.getPointerTy();
2561 if (IntPtr < AllocSize.getValueType())
2562 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2563 else if (IntPtr > AllocSize.getValueType())
2564 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2566 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2567 DAG.getIntPtrConstant(TySize));
2569 // Handle alignment. If the requested alignment is less than or equal to
2570 // the stack alignment, ignore it. If the size is greater than or equal to
2571 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2572 unsigned StackAlign =
2573 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2574 if (Align <= StackAlign)
2577 // Round the size of the allocation up to the stack alignment size
2578 // by add SA-1 to the size.
2579 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2580 DAG.getIntPtrConstant(StackAlign-1));
2581 // Mask out the low bits for alignment purposes.
2582 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2583 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2585 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2586 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2588 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2590 DAG.setRoot(DSA.getValue(1));
2592 // Inform the Frame Information that we have just allocated a variable-sized
2594 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2597 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2598 SDOperand Ptr = getValue(I.getOperand(0));
2604 // Do not serialize non-volatile loads against each other.
2605 Root = DAG.getRoot();
2608 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2609 Root, I.isVolatile(), I.getAlignment()));
2612 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2613 const Value *SV, SDOperand Root,
2615 unsigned Alignment) {
2617 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2618 isVolatile, Alignment);
2621 DAG.setRoot(L.getValue(1));
2623 PendingLoads.push_back(L.getValue(1));
2629 void SelectionDAGLowering::visitStore(StoreInst &I) {
2630 Value *SrcV = I.getOperand(0);
2631 SDOperand Src = getValue(SrcV);
2632 SDOperand Ptr = getValue(I.getOperand(1));
2633 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2634 I.isVolatile(), I.getAlignment()));
2637 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2639 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2640 unsigned Intrinsic) {
2641 bool HasChain = !I.doesNotAccessMemory();
2642 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2644 // Build the operand list.
2645 SmallVector<SDOperand, 8> Ops;
2646 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2648 // We don't need to serialize loads against other loads.
2649 Ops.push_back(DAG.getRoot());
2651 Ops.push_back(getRoot());
2655 // Add the intrinsic ID as an integer operand.
2656 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2658 // Add all operands of the call to the operand list.
2659 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2660 SDOperand Op = getValue(I.getOperand(i));
2661 assert(TLI.isTypeLegal(Op.getValueType()) &&
2662 "Intrinsic uses a non-legal type?");
2666 std::vector<MVT::ValueType> VTs;
2667 if (I.getType() != Type::VoidTy) {
2668 MVT::ValueType VT = TLI.getValueType(I.getType());
2669 if (MVT::isVector(VT)) {
2670 const VectorType *DestTy = cast<VectorType>(I.getType());
2671 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2673 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2674 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2677 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2681 VTs.push_back(MVT::Other);
2683 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2688 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2689 &Ops[0], Ops.size());
2690 else if (I.getType() != Type::VoidTy)
2691 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2692 &Ops[0], Ops.size());
2694 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2695 &Ops[0], Ops.size());
2698 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2700 PendingLoads.push_back(Chain);
2704 if (I.getType() != Type::VoidTy) {
2705 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2706 MVT::ValueType VT = TLI.getValueType(PTy);
2707 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2709 setValue(&I, Result);
2713 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2714 static GlobalVariable *ExtractTypeInfo (Value *V) {
2715 V = IntrinsicInst::StripPointerCasts(V);
2716 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2717 assert ((GV || isa<ConstantPointerNull>(V)) &&
2718 "TypeInfo must be a global variable or NULL");
2722 /// addCatchInfo - Extract the personality and type infos from an eh.selector
2723 /// call, and add them to the specified machine basic block.
2724 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2725 MachineBasicBlock *MBB) {
2726 // Inform the MachineModuleInfo of the personality for this landing pad.
2727 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2728 assert(CE->getOpcode() == Instruction::BitCast &&
2729 isa<Function>(CE->getOperand(0)) &&
2730 "Personality should be a function");
2731 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2733 // Gather all the type infos for this landing pad and pass them along to
2734 // MachineModuleInfo.
2735 std::vector<GlobalVariable *> TyInfo;
2736 unsigned N = I.getNumOperands();
2738 for (unsigned i = N - 1; i > 2; --i) {
2739 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2740 unsigned FilterLength = CI->getZExtValue();
2741 unsigned FirstCatch = i + FilterLength + !FilterLength;
2742 assert (FirstCatch <= N && "Invalid filter length");
2744 if (FirstCatch < N) {
2745 TyInfo.reserve(N - FirstCatch);
2746 for (unsigned j = FirstCatch; j < N; ++j)
2747 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2748 MMI->addCatchTypeInfo(MBB, TyInfo);
2752 if (!FilterLength) {
2754 MMI->addCleanup(MBB);
2757 TyInfo.reserve(FilterLength - 1);
2758 for (unsigned j = i + 1; j < FirstCatch; ++j)
2759 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2760 MMI->addFilterTypeInfo(MBB, TyInfo);
2769 TyInfo.reserve(N - 3);
2770 for (unsigned j = 3; j < N; ++j)
2771 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2772 MMI->addCatchTypeInfo(MBB, TyInfo);
2777 /// Inlined utility function to implement binary input atomic intrinsics for
2778 // visitIntrinsicCall: I is a call instruction
2779 // Op is the associated NodeType for I
2781 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2782 SDOperand Root = getRoot();
2783 SDOperand O2 = getValue(I.getOperand(2));
2784 SDOperand L = DAG.getAtomic(Op, Root,
2785 getValue(I.getOperand(1)),
2786 O2, O2.getValueType());
2788 DAG.setRoot(L.getValue(1));
2792 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2793 /// we want to emit this as a call to a named external function, return the name
2794 /// otherwise lower it and return null.
2796 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2797 switch (Intrinsic) {
2799 // By default, turn this into a target intrinsic node.
2800 visitTargetIntrinsic(I, Intrinsic);
2802 case Intrinsic::vastart: visitVAStart(I); return 0;
2803 case Intrinsic::vaend: visitVAEnd(I); return 0;
2804 case Intrinsic::vacopy: visitVACopy(I); return 0;
2805 case Intrinsic::returnaddress:
2806 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2807 getValue(I.getOperand(1))));
2809 case Intrinsic::frameaddress:
2810 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2811 getValue(I.getOperand(1))));
2813 case Intrinsic::setjmp:
2814 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2816 case Intrinsic::longjmp:
2817 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2819 case Intrinsic::memcpy_i32:
2820 case Intrinsic::memcpy_i64: {
2821 SDOperand Op1 = getValue(I.getOperand(1));
2822 SDOperand Op2 = getValue(I.getOperand(2));
2823 SDOperand Op3 = getValue(I.getOperand(3));
2824 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2825 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2826 I.getOperand(1), 0, I.getOperand(2), 0));
2829 case Intrinsic::memset_i32:
2830 case Intrinsic::memset_i64: {
2831 SDOperand Op1 = getValue(I.getOperand(1));
2832 SDOperand Op2 = getValue(I.getOperand(2));
2833 SDOperand Op3 = getValue(I.getOperand(3));
2834 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2835 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2836 I.getOperand(1), 0));
2839 case Intrinsic::memmove_i32:
2840 case Intrinsic::memmove_i64: {
2841 SDOperand Op1 = getValue(I.getOperand(1));
2842 SDOperand Op2 = getValue(I.getOperand(2));
2843 SDOperand Op3 = getValue(I.getOperand(3));
2844 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2846 // If the source and destination are known to not be aliases, we can
2847 // lower memmove as memcpy.
2848 uint64_t Size = -1ULL;
2849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2850 Size = C->getValue();
2851 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2852 AliasAnalysis::NoAlias) {
2853 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2854 I.getOperand(1), 0, I.getOperand(2), 0));
2858 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2859 I.getOperand(1), 0, I.getOperand(2), 0));
2862 case Intrinsic::dbg_stoppoint: {
2863 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2864 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2865 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2869 Ops[1] = getValue(SPI.getLineValue());
2870 Ops[2] = getValue(SPI.getColumnValue());
2872 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2873 assert(DD && "Not a debug information descriptor");
2874 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2876 Ops[3] = DAG.getString(CompileUnit->getFileName());
2877 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2879 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2884 case Intrinsic::dbg_region_start: {
2885 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2886 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2887 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2888 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2889 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2890 DAG.getConstant(LabelID, MVT::i32),
2891 DAG.getConstant(0, MVT::i32)));
2896 case Intrinsic::dbg_region_end: {
2897 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2898 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2899 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2900 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2901 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2902 DAG.getConstant(LabelID, MVT::i32),
2903 DAG.getConstant(0, MVT::i32)));
2908 case Intrinsic::dbg_func_start: {
2909 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2911 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2912 Value *SP = FSI.getSubprogram();
2913 if (SP && MMI->Verify(SP)) {
2914 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2915 // what (most?) gdb expects.
2916 DebugInfoDesc *DD = MMI->getDescFor(SP);
2917 assert(DD && "Not a debug information descriptor");
2918 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2919 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2920 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2921 CompileUnit->getFileName());
2922 // Record the source line but does create a label. It will be emitted
2923 // at asm emission time.
2924 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2929 case Intrinsic::dbg_declare: {
2930 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2931 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2932 Value *Variable = DI.getVariable();
2933 if (MMI && Variable && MMI->Verify(Variable))
2934 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2935 getValue(DI.getAddress()), getValue(Variable)));
2939 case Intrinsic::eh_exception: {
2940 if (!CurMBB->isLandingPad()) {
2941 // FIXME: Mark exception register as live in. Hack for PR1508.
2942 unsigned Reg = TLI.getExceptionAddressRegister();
2943 if (Reg) CurMBB->addLiveIn(Reg);
2945 // Insert the EXCEPTIONADDR instruction.
2946 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2948 Ops[0] = DAG.getRoot();
2949 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2951 DAG.setRoot(Op.getValue(1));
2955 case Intrinsic::eh_selector_i32:
2956 case Intrinsic::eh_selector_i64: {
2957 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2958 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2959 MVT::i32 : MVT::i64);
2962 if (CurMBB->isLandingPad())
2963 addCatchInfo(I, MMI, CurMBB);
2966 FuncInfo.CatchInfoLost.insert(&I);
2968 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2969 unsigned Reg = TLI.getExceptionSelectorRegister();
2970 if (Reg) CurMBB->addLiveIn(Reg);
2973 // Insert the EHSELECTION instruction.
2974 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2976 Ops[0] = getValue(I.getOperand(1));
2978 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2980 DAG.setRoot(Op.getValue(1));
2982 setValue(&I, DAG.getConstant(0, VT));
2988 case Intrinsic::eh_typeid_for_i32:
2989 case Intrinsic::eh_typeid_for_i64: {
2990 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2991 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2992 MVT::i32 : MVT::i64);
2995 // Find the type id for the given typeinfo.
2996 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2998 unsigned TypeID = MMI->getTypeIDFor(GV);
2999 setValue(&I, DAG.getConstant(TypeID, VT));
3001 // Return something different to eh_selector.
3002 setValue(&I, DAG.getConstant(1, VT));
3008 case Intrinsic::eh_return: {
3009 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3012 MMI->setCallsEHReturn(true);
3013 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3016 getValue(I.getOperand(1)),
3017 getValue(I.getOperand(2))));
3019 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3025 case Intrinsic::eh_unwind_init: {
3026 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3027 MMI->setCallsUnwindInit(true);
3033 case Intrinsic::eh_dwarf_cfa: {
3034 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3036 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3037 CfaArg = DAG.getNode(ISD::TRUNCATE,
3038 TLI.getPointerTy(), getValue(I.getOperand(1)));
3040 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3041 TLI.getPointerTy(), getValue(I.getOperand(1)));
3043 SDOperand Offset = DAG.getNode(ISD::ADD,
3045 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3046 TLI.getPointerTy()),
3048 setValue(&I, DAG.getNode(ISD::ADD,
3050 DAG.getNode(ISD::FRAMEADDR,
3053 TLI.getPointerTy())),
3058 case Intrinsic::sqrt:
3059 setValue(&I, DAG.getNode(ISD::FSQRT,
3060 getValue(I.getOperand(1)).getValueType(),
3061 getValue(I.getOperand(1))));
3063 case Intrinsic::powi:
3064 setValue(&I, DAG.getNode(ISD::FPOWI,
3065 getValue(I.getOperand(1)).getValueType(),
3066 getValue(I.getOperand(1)),
3067 getValue(I.getOperand(2))));
3069 case Intrinsic::sin:
3070 setValue(&I, DAG.getNode(ISD::FSIN,
3071 getValue(I.getOperand(1)).getValueType(),
3072 getValue(I.getOperand(1))));
3074 case Intrinsic::cos:
3075 setValue(&I, DAG.getNode(ISD::FCOS,
3076 getValue(I.getOperand(1)).getValueType(),
3077 getValue(I.getOperand(1))));
3079 case Intrinsic::pow:
3080 setValue(&I, DAG.getNode(ISD::FPOW,
3081 getValue(I.getOperand(1)).getValueType(),
3082 getValue(I.getOperand(1)),
3083 getValue(I.getOperand(2))));
3085 case Intrinsic::pcmarker: {
3086 SDOperand Tmp = getValue(I.getOperand(1));
3087 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3090 case Intrinsic::readcyclecounter: {
3091 SDOperand Op = getRoot();
3092 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3093 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3096 DAG.setRoot(Tmp.getValue(1));
3099 case Intrinsic::part_select: {
3100 // Currently not implemented: just abort
3101 assert(0 && "part_select intrinsic not implemented");
3104 case Intrinsic::part_set: {
3105 // Currently not implemented: just abort
3106 assert(0 && "part_set intrinsic not implemented");
3109 case Intrinsic::bswap:
3110 setValue(&I, DAG.getNode(ISD::BSWAP,
3111 getValue(I.getOperand(1)).getValueType(),
3112 getValue(I.getOperand(1))));
3114 case Intrinsic::cttz: {
3115 SDOperand Arg = getValue(I.getOperand(1));
3116 MVT::ValueType Ty = Arg.getValueType();
3117 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3118 setValue(&I, result);
3121 case Intrinsic::ctlz: {
3122 SDOperand Arg = getValue(I.getOperand(1));
3123 MVT::ValueType Ty = Arg.getValueType();
3124 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3125 setValue(&I, result);
3128 case Intrinsic::ctpop: {
3129 SDOperand Arg = getValue(I.getOperand(1));
3130 MVT::ValueType Ty = Arg.getValueType();
3131 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3132 setValue(&I, result);
3135 case Intrinsic::stacksave: {
3136 SDOperand Op = getRoot();
3137 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3138 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3140 DAG.setRoot(Tmp.getValue(1));
3143 case Intrinsic::stackrestore: {
3144 SDOperand Tmp = getValue(I.getOperand(1));
3145 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3148 case Intrinsic::var_annotation:
3149 // Discard annotate attributes
3152 case Intrinsic::init_trampoline: {
3154 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3158 Ops[1] = getValue(I.getOperand(1));
3159 Ops[2] = getValue(I.getOperand(2));
3160 Ops[3] = getValue(I.getOperand(3));
3161 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3162 Ops[5] = DAG.getSrcValue(F);
3164 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3165 DAG.getNodeValueTypes(TLI.getPointerTy(),
3170 DAG.setRoot(Tmp.getValue(1));
3174 case Intrinsic::gcroot:
3176 Value *Alloca = I.getOperand(1);
3177 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3179 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3180 GCI->addStackRoot(FI->getIndex(), TypeMap);
3184 case Intrinsic::gcread:
3185 case Intrinsic::gcwrite:
3186 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3189 case Intrinsic::flt_rounds: {
3190 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3194 case Intrinsic::trap: {
3195 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3198 case Intrinsic::prefetch: {
3201 Ops[1] = getValue(I.getOperand(1));
3202 Ops[2] = getValue(I.getOperand(2));
3203 Ops[3] = getValue(I.getOperand(3));
3204 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3208 case Intrinsic::memory_barrier: {
3211 for (int x = 1; x < 6; ++x)
3212 Ops[x] = getValue(I.getOperand(x));
3214 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3217 case Intrinsic::atomic_lcs: {
3218 SDOperand Root = getRoot();
3219 SDOperand O3 = getValue(I.getOperand(3));
3220 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3221 getValue(I.getOperand(1)),
3222 getValue(I.getOperand(2)),
3223 O3, O3.getValueType());
3225 DAG.setRoot(L.getValue(1));
3228 case Intrinsic::atomic_las:
3229 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3230 case Intrinsic::atomic_lss:
3231 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3232 case Intrinsic::atomic_load_and:
3233 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3234 case Intrinsic::atomic_load_or:
3235 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3236 case Intrinsic::atomic_load_xor:
3237 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3238 case Intrinsic::atomic_load_min:
3239 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3240 case Intrinsic::atomic_load_max:
3241 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3242 case Intrinsic::atomic_load_umin:
3243 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3244 case Intrinsic::atomic_load_umax:
3245 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3246 case Intrinsic::atomic_swap:
3247 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
3252 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3254 MachineBasicBlock *LandingPad) {
3255 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3256 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3257 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3258 unsigned BeginLabel = 0, EndLabel = 0;
3260 TargetLowering::ArgListTy Args;
3261 TargetLowering::ArgListEntry Entry;
3262 Args.reserve(CS.arg_size());
3263 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3265 SDOperand ArgNode = getValue(*i);
3266 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3268 unsigned attrInd = i - CS.arg_begin() + 1;
3269 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3270 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3271 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3272 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3273 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3274 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3275 Entry.Alignment = CS.getParamAlignment(attrInd);
3276 Args.push_back(Entry);
3279 if (LandingPad && MMI) {
3280 // Insert a label before the invoke call to mark the try range. This can be
3281 // used to detect deletion of the invoke via the MachineModuleInfo.
3282 BeginLabel = MMI->NextLabelID();
3283 // Both PendingLoads and PendingExports must be flushed here;
3284 // this call might not return.
3286 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3287 DAG.getConstant(BeginLabel, MVT::i32),
3288 DAG.getConstant(1, MVT::i32)));
3291 std::pair<SDOperand,SDOperand> Result =
3292 TLI.LowerCallTo(getRoot(), CS.getType(),
3293 CS.paramHasAttr(0, ParamAttr::SExt),
3294 CS.paramHasAttr(0, ParamAttr::ZExt),
3295 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3297 if (CS.getType() != Type::VoidTy)
3298 setValue(CS.getInstruction(), Result.first);
3299 DAG.setRoot(Result.second);
3301 if (LandingPad && MMI) {
3302 // Insert a label at the end of the invoke call to mark the try range. This
3303 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3304 EndLabel = MMI->NextLabelID();
3305 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3306 DAG.getConstant(EndLabel, MVT::i32),
3307 DAG.getConstant(1, MVT::i32)));
3309 // Inform MachineModuleInfo of range.
3310 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3315 void SelectionDAGLowering::visitCall(CallInst &I) {
3316 const char *RenameFn = 0;
3317 if (Function *F = I.getCalledFunction()) {
3318 if (F->isDeclaration()) {
3319 if (unsigned IID = F->getIntrinsicID()) {
3320 RenameFn = visitIntrinsicCall(I, IID);
3326 // Check for well-known libc/libm calls. If the function is internal, it
3327 // can't be a library call.
3328 unsigned NameLen = F->getNameLen();
3329 if (!F->hasInternalLinkage() && NameLen) {
3330 const char *NameStr = F->getNameStart();
3331 if (NameStr[0] == 'c' &&
3332 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3333 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3334 if (I.getNumOperands() == 3 && // Basic sanity checks.
3335 I.getOperand(1)->getType()->isFloatingPoint() &&
3336 I.getType() == I.getOperand(1)->getType() &&
3337 I.getType() == I.getOperand(2)->getType()) {
3338 SDOperand LHS = getValue(I.getOperand(1));
3339 SDOperand RHS = getValue(I.getOperand(2));
3340 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3344 } else if (NameStr[0] == 'f' &&
3345 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3346 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3347 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3348 if (I.getNumOperands() == 2 && // Basic sanity checks.
3349 I.getOperand(1)->getType()->isFloatingPoint() &&
3350 I.getType() == I.getOperand(1)->getType()) {
3351 SDOperand Tmp = getValue(I.getOperand(1));
3352 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3355 } else if (NameStr[0] == 's' &&
3356 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3357 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3358 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3359 if (I.getNumOperands() == 2 && // Basic sanity checks.
3360 I.getOperand(1)->getType()->isFloatingPoint() &&
3361 I.getType() == I.getOperand(1)->getType()) {
3362 SDOperand Tmp = getValue(I.getOperand(1));
3363 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3366 } else if (NameStr[0] == 'c' &&
3367 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3368 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3369 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3370 if (I.getNumOperands() == 2 && // Basic sanity checks.
3371 I.getOperand(1)->getType()->isFloatingPoint() &&
3372 I.getType() == I.getOperand(1)->getType()) {
3373 SDOperand Tmp = getValue(I.getOperand(1));
3374 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3379 } else if (isa<InlineAsm>(I.getOperand(0))) {
3386 Callee = getValue(I.getOperand(0));
3388 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3390 LowerCallTo(&I, Callee, I.isTailCall());
3394 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3395 if (isa<UndefValue>(I.getOperand(0))) {
3396 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3397 setValue(&I, Undef);
3401 // To add support for individual return values with aggregate types,
3402 // we'd need a way to take a getresult index and determine which
3403 // values of the Call SDNode are associated with it.
3404 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3405 "Individual return values must not be aggregates!");
3407 SDOperand Call = getValue(I.getOperand(0));
3408 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3412 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3413 /// this value and returns the result as a ValueVT value. This uses
3414 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3415 /// If the Flag pointer is NULL, no flag is used.
3416 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3418 SDOperand *Flag) const {
3419 // Assemble the legal parts into the final values.
3420 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3421 SmallVector<SDOperand, 8> Parts;
3422 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3423 // Copy the legal parts from the registers.
3424 MVT::ValueType ValueVT = ValueVTs[Value];
3425 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3426 MVT::ValueType RegisterVT = RegVTs[Value];
3428 Parts.resize(NumRegs);
3429 for (unsigned i = 0; i != NumRegs; ++i) {
3432 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3434 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3435 *Flag = P.getValue(2);
3437 Chain = P.getValue(1);
3441 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3446 if (ValueVTs.size() == 1)
3449 return DAG.getNode(ISD::MERGE_VALUES,
3450 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3451 &Values[0], ValueVTs.size());
3454 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3455 /// specified value into the registers specified by this object. This uses
3456 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3457 /// If the Flag pointer is NULL, no flag is used.
3458 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3459 SDOperand &Chain, SDOperand *Flag) const {
3460 // Get the list of the values's legal parts.
3461 unsigned NumRegs = Regs.size();
3462 SmallVector<SDOperand, 8> Parts(NumRegs);
3463 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3464 MVT::ValueType ValueVT = ValueVTs[Value];
3465 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3466 MVT::ValueType RegisterVT = RegVTs[Value];
3468 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3469 &Parts[Part], NumParts, RegisterVT);
3473 // Copy the parts into the registers.
3474 SmallVector<SDOperand, 8> Chains(NumRegs);
3475 for (unsigned i = 0; i != NumRegs; ++i) {
3478 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3480 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3481 *Flag = Part.getValue(1);
3483 Chains[i] = Part.getValue(0);
3486 if (NumRegs == 1 || Flag)
3487 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3488 // flagged to it. That is the CopyToReg nodes and the user are considered
3489 // a single scheduling unit. If we create a TokenFactor and return it as
3490 // chain, then the TokenFactor is both a predecessor (operand) of the
3491 // user as well as a successor (the TF operands are flagged to the user).
3492 // c1, f1 = CopyToReg
3493 // c2, f2 = CopyToReg
3494 // c3 = TokenFactor c1, c2
3497 Chain = Chains[NumRegs-1];
3499 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3502 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3503 /// operand list. This adds the code marker and includes the number of
3504 /// values added into it.
3505 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3506 std::vector<SDOperand> &Ops) const {
3507 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3508 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3509 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3510 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3511 MVT::ValueType RegisterVT = RegVTs[Value];
3512 for (unsigned i = 0; i != NumRegs; ++i)
3513 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3517 /// isAllocatableRegister - If the specified register is safe to allocate,
3518 /// i.e. it isn't a stack pointer or some other special register, return the
3519 /// register class for the register. Otherwise, return null.
3520 static const TargetRegisterClass *
3521 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3522 const TargetLowering &TLI,
3523 const TargetRegisterInfo *TRI) {
3524 MVT::ValueType FoundVT = MVT::Other;
3525 const TargetRegisterClass *FoundRC = 0;
3526 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3527 E = TRI->regclass_end(); RCI != E; ++RCI) {
3528 MVT::ValueType ThisVT = MVT::Other;
3530 const TargetRegisterClass *RC = *RCI;
3531 // If none of the the value types for this register class are valid, we
3532 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3533 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3535 if (TLI.isTypeLegal(*I)) {
3536 // If we have already found this register in a different register class,
3537 // choose the one with the largest VT specified. For example, on
3538 // PowerPC, we favor f64 register classes over f32.
3539 if (FoundVT == MVT::Other ||
3540 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3547 if (ThisVT == MVT::Other) continue;
3549 // NOTE: This isn't ideal. In particular, this might allocate the
3550 // frame pointer in functions that need it (due to them not being taken
3551 // out of allocation, because a variable sized allocation hasn't been seen
3552 // yet). This is a slight code pessimization, but should still work.
3553 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3554 E = RC->allocation_order_end(MF); I != E; ++I)
3556 // We found a matching register class. Keep looking at others in case
3557 // we find one with larger registers that this physreg is also in.
3568 /// AsmOperandInfo - This contains information for each constraint that we are
3570 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3571 /// CallOperand - If this is the result output operand or a clobber
3572 /// this is null, otherwise it is the incoming operand to the CallInst.
3573 /// This gets modified as the asm is processed.
3574 SDOperand CallOperand;
3576 /// AssignedRegs - If this is a register or register class operand, this
3577 /// contains the set of register corresponding to the operand.
3578 RegsForValue AssignedRegs;
3580 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3581 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3584 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3585 /// busy in OutputRegs/InputRegs.
3586 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3587 std::set<unsigned> &OutputRegs,
3588 std::set<unsigned> &InputRegs,
3589 const TargetRegisterInfo &TRI) const {
3591 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3592 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3595 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3596 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3601 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3603 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3604 const TargetRegisterInfo &TRI) {
3605 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3607 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3608 for (; *Aliases; ++Aliases)
3609 Regs.insert(*Aliases);
3612 } // end anon namespace.
3615 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3616 /// specified operand. We prefer to assign virtual registers, to allow the
3617 /// register allocator handle the assignment process. However, if the asm uses
3618 /// features that we can't model on machineinstrs, we have SDISel do the
3619 /// allocation. This produces generally horrible, but correct, code.
3621 /// OpInfo describes the operand.
3622 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3623 /// or any explicitly clobbered registers.
3624 /// Input and OutputRegs are the set of already allocated physical registers.
3626 void SelectionDAGLowering::
3627 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3628 std::set<unsigned> &OutputRegs,
3629 std::set<unsigned> &InputRegs) {
3630 // Compute whether this value requires an input register, an output register,
3632 bool isOutReg = false;
3633 bool isInReg = false;
3634 switch (OpInfo.Type) {
3635 case InlineAsm::isOutput:
3638 // If this is an early-clobber output, or if there is an input
3639 // constraint that matches this, we need to reserve the input register
3640 // so no other inputs allocate to it.
3641 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3643 case InlineAsm::isInput:
3647 case InlineAsm::isClobber:
3654 MachineFunction &MF = DAG.getMachineFunction();
3655 SmallVector<unsigned, 4> Regs;
3657 // If this is a constraint for a single physreg, or a constraint for a
3658 // register class, find it.
3659 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3660 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3661 OpInfo.ConstraintVT);
3663 unsigned NumRegs = 1;
3664 if (OpInfo.ConstraintVT != MVT::Other)
3665 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3666 MVT::ValueType RegVT;
3667 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3670 // If this is a constraint for a specific physical register, like {r17},
3672 if (PhysReg.first) {
3673 if (OpInfo.ConstraintVT == MVT::Other)
3674 ValueVT = *PhysReg.second->vt_begin();
3676 // Get the actual register value type. This is important, because the user
3677 // may have asked for (e.g.) the AX register in i32 type. We need to
3678 // remember that AX is actually i16 to get the right extension.
3679 RegVT = *PhysReg.second->vt_begin();
3681 // This is a explicit reference to a physical register.
3682 Regs.push_back(PhysReg.first);
3684 // If this is an expanded reference, add the rest of the regs to Regs.
3686 TargetRegisterClass::iterator I = PhysReg.second->begin();
3687 TargetRegisterClass::iterator E = PhysReg.second->end();
3688 for (; *I != PhysReg.first; ++I)
3689 assert(I != E && "Didn't find reg!");
3691 // Already added the first reg.
3693 for (; NumRegs; --NumRegs, ++I) {
3694 assert(I != E && "Ran out of registers to allocate!");
3698 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3699 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3700 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3704 // Otherwise, if this was a reference to an LLVM register class, create vregs
3705 // for this reference.
3706 std::vector<unsigned> RegClassRegs;
3707 const TargetRegisterClass *RC = PhysReg.second;
3709 // If this is an early clobber or tied register, our regalloc doesn't know
3710 // how to maintain the constraint. If it isn't, go ahead and create vreg
3711 // and let the regalloc do the right thing.
3712 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3713 // If there is some other early clobber and this is an input register,
3714 // then we are forced to pre-allocate the input reg so it doesn't
3715 // conflict with the earlyclobber.
3716 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3717 RegVT = *PhysReg.second->vt_begin();
3719 if (OpInfo.ConstraintVT == MVT::Other)
3722 // Create the appropriate number of virtual registers.
3723 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3724 for (; NumRegs; --NumRegs)
3725 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3727 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3731 // Otherwise, we can't allocate it. Let the code below figure out how to
3732 // maintain these constraints.
3733 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3736 // This is a reference to a register class that doesn't directly correspond
3737 // to an LLVM register class. Allocate NumRegs consecutive, available,
3738 // registers from the class.
3739 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3740 OpInfo.ConstraintVT);
3743 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3744 unsigned NumAllocated = 0;
3745 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3746 unsigned Reg = RegClassRegs[i];
3747 // See if this register is available.
3748 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3749 (isInReg && InputRegs.count(Reg))) { // Already used.
3750 // Make sure we find consecutive registers.
3755 // Check to see if this register is allocatable (i.e. don't give out the
3758 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3759 if (!RC) { // Couldn't allocate this register.
3760 // Reset NumAllocated to make sure we return consecutive registers.
3766 // Okay, this register is good, we can use it.
3769 // If we allocated enough consecutive registers, succeed.
3770 if (NumAllocated == NumRegs) {
3771 unsigned RegStart = (i-NumAllocated)+1;
3772 unsigned RegEnd = i+1;
3773 // Mark all of the allocated registers used.
3774 for (unsigned i = RegStart; i != RegEnd; ++i)
3775 Regs.push_back(RegClassRegs[i]);
3777 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
3778 OpInfo.ConstraintVT);
3779 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3784 // Otherwise, we couldn't allocate enough registers for this.
3788 /// visitInlineAsm - Handle a call to an InlineAsm object.
3790 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3791 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3793 /// ConstraintOperands - Information about all of the constraints.
3794 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3796 SDOperand Chain = getRoot();
3799 std::set<unsigned> OutputRegs, InputRegs;
3801 // Do a prepass over the constraints, canonicalizing them, and building up the
3802 // ConstraintOperands list.
3803 std::vector<InlineAsm::ConstraintInfo>
3804 ConstraintInfos = IA->ParseConstraints();
3806 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3807 // constraint. If so, we can't let the register allocator allocate any input
3808 // registers, because it will not know to avoid the earlyclobbered output reg.
3809 bool SawEarlyClobber = false;
3811 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3812 unsigned ResNo = 0; // ResNo - The result number of the next output.
3813 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3814 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3815 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3817 MVT::ValueType OpVT = MVT::Other;
3819 // Compute the value type for each operand.
3820 switch (OpInfo.Type) {
3821 case InlineAsm::isOutput:
3822 // Indirect outputs just consume an argument.
3823 if (OpInfo.isIndirect) {
3824 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3827 // The return value of the call is this value. As such, there is no
3828 // corresponding argument.
3829 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3830 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3831 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3833 assert(ResNo == 0 && "Asm only has one result!");
3834 OpVT = TLI.getValueType(CS.getType());
3838 case InlineAsm::isInput:
3839 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3841 case InlineAsm::isClobber:
3846 // If this is an input or an indirect output, process the call argument.
3847 // BasicBlocks are labels, currently appearing only in asm's.
3848 if (OpInfo.CallOperandVal) {
3849 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3850 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3852 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3853 const Type *OpTy = OpInfo.CallOperandVal->getType();
3854 // If this is an indirect operand, the operand is a pointer to the
3856 if (OpInfo.isIndirect)
3857 OpTy = cast<PointerType>(OpTy)->getElementType();
3859 // If OpTy is not a first-class value, it may be a struct/union that we
3860 // can tile with integers.
3861 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3862 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3870 OpTy = IntegerType::get(BitSize);
3875 OpVT = TLI.getValueType(OpTy, true);
3879 OpInfo.ConstraintVT = OpVT;
3881 // Compute the constraint code and ConstraintType to use.
3882 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
3884 // Keep track of whether we see an earlyclobber.
3885 SawEarlyClobber |= OpInfo.isEarlyClobber;
3887 // If we see a clobber of a register, it is an early clobber.
3888 if (!SawEarlyClobber &&
3889 OpInfo.Type == InlineAsm::isClobber &&
3890 OpInfo.ConstraintType == TargetLowering::C_Register) {
3891 // Note that we want to ignore things that we don't trick here, like
3892 // dirflag, fpsr, flags, etc.
3893 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3894 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3895 OpInfo.ConstraintVT);
3896 if (PhysReg.first || PhysReg.second) {
3897 // This is a register we know of.
3898 SawEarlyClobber = true;
3902 // If this is a memory input, and if the operand is not indirect, do what we
3903 // need to to provide an address for the memory input.
3904 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3905 !OpInfo.isIndirect) {
3906 assert(OpInfo.Type == InlineAsm::isInput &&
3907 "Can only indirectify direct input operands!");
3909 // Memory operands really want the address of the value. If we don't have
3910 // an indirect input, put it in the constpool if we can, otherwise spill
3911 // it to a stack slot.
3913 // If the operand is a float, integer, or vector constant, spill to a
3914 // constant pool entry to get its address.
3915 Value *OpVal = OpInfo.CallOperandVal;
3916 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3917 isa<ConstantVector>(OpVal)) {
3918 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3919 TLI.getPointerTy());
3921 // Otherwise, create a stack slot and emit a store to it before the
3923 const Type *Ty = OpVal->getType();
3924 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3925 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3926 MachineFunction &MF = DAG.getMachineFunction();
3927 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3928 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3929 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3930 OpInfo.CallOperand = StackSlot;
3933 // There is no longer a Value* corresponding to this operand.
3934 OpInfo.CallOperandVal = 0;
3935 // It is now an indirect operand.
3936 OpInfo.isIndirect = true;
3939 // If this constraint is for a specific register, allocate it before
3941 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3942 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3944 ConstraintInfos.clear();
3947 // Second pass - Loop over all of the operands, assigning virtual or physregs
3948 // to registerclass operands.
3949 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3950 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3952 // C_Register operands have already been allocated, Other/Memory don't need
3954 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3955 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3958 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3959 std::vector<SDOperand> AsmNodeOperands;
3960 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3961 AsmNodeOperands.push_back(
3962 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3965 // Loop over all of the inputs, copying the operand values into the
3966 // appropriate registers and processing the output regs.
3967 RegsForValue RetValRegs;
3969 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3970 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3972 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3973 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
3975 switch (OpInfo.Type) {
3976 case InlineAsm::isOutput: {
3977 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3978 OpInfo.ConstraintType != TargetLowering::C_Register) {
3979 // Memory output, or 'other' output (e.g. 'X' constraint).
3980 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3982 // Add information to the INLINEASM node to know about this output.
3983 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3984 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3985 TLI.getPointerTy()));
3986 AsmNodeOperands.push_back(OpInfo.CallOperand);
3990 // Otherwise, this is a register or register class output.
3992 // Copy the output from the appropriate register. Find a register that
3994 if (OpInfo.AssignedRegs.Regs.empty()) {
3995 cerr << "Couldn't allocate output reg for contraint '"
3996 << OpInfo.ConstraintCode << "'!\n";
4000 // If this is an indirect operand, store through the pointer after the
4002 if (OpInfo.isIndirect) {
4003 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4004 OpInfo.CallOperandVal));
4006 // This is the result value of the call.
4007 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4008 // Concatenate this output onto the outputs list.
4009 RetValRegs.append(OpInfo.AssignedRegs);
4012 // Add information to the INLINEASM node to know that this register is
4014 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4018 case InlineAsm::isInput: {
4019 SDOperand InOperandVal = OpInfo.CallOperand;
4021 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4022 // If this is required to match an output register we have already set,
4023 // just use its register.
4024 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4026 // Scan until we find the definition we already emitted of this operand.
4027 // When we find it, create a RegsForValue operand.
4028 unsigned CurOp = 2; // The first operand.
4029 for (; OperandNo; --OperandNo) {
4030 // Advance to the next operand.
4032 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4033 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4034 (NumOps & 7) == 4 /*MEM*/) &&
4035 "Skipped past definitions?");
4036 CurOp += (NumOps>>3)+1;
4040 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4041 if ((NumOps & 7) == 2 /*REGDEF*/) {
4042 // Add NumOps>>3 registers to MatchedRegs.
4043 RegsForValue MatchedRegs;
4044 MatchedRegs.TLI = &TLI;
4045 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4046 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4047 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4049 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4050 MatchedRegs.Regs.push_back(Reg);
4053 // Use the produced MatchedRegs object to
4054 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4055 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4058 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4059 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4060 // Add information to the INLINEASM node to know about this input.
4061 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4062 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4063 TLI.getPointerTy()));
4064 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4069 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4070 assert(!OpInfo.isIndirect &&
4071 "Don't know how to handle indirect other inputs yet!");
4073 std::vector<SDOperand> Ops;
4074 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4077 cerr << "Invalid operand for inline asm constraint '"
4078 << OpInfo.ConstraintCode << "'!\n";
4082 // Add information to the INLINEASM node to know about this input.
4083 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4084 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4085 TLI.getPointerTy()));
4086 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4088 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4089 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4090 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4091 "Memory operands expect pointer values");
4093 // Add information to the INLINEASM node to know about this input.
4094 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4095 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4096 TLI.getPointerTy()));
4097 AsmNodeOperands.push_back(InOperandVal);
4101 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4102 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4103 "Unknown constraint type!");
4104 assert(!OpInfo.isIndirect &&
4105 "Don't know how to handle indirect register inputs yet!");
4107 // Copy the input into the appropriate registers.
4108 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4109 "Couldn't allocate input reg!");
4111 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4113 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4117 case InlineAsm::isClobber: {
4118 // Add the clobbered value to the operand list, so that the register
4119 // allocator is aware that the physreg got clobbered.
4120 if (!OpInfo.AssignedRegs.Regs.empty())
4121 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4128 // Finish up input operands.
4129 AsmNodeOperands[0] = Chain;
4130 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4132 Chain = DAG.getNode(ISD::INLINEASM,
4133 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4134 &AsmNodeOperands[0], AsmNodeOperands.size());
4135 Flag = Chain.getValue(1);
4137 // If this asm returns a register value, copy the result from that register
4138 // and set it as the value of the call.
4139 if (!RetValRegs.Regs.empty()) {
4140 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4142 // If any of the results of the inline asm is a vector, it may have the
4143 // wrong width/num elts. This can happen for register classes that can
4144 // contain multiple different value types. The preg or vreg allocated may
4145 // not have the same VT as was expected. Convert it to the right type with
4147 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4148 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4149 if (MVT::isVector(Val.Val->getValueType(i)))
4150 Val = DAG.getNode(ISD::BIT_CONVERT,
4151 TLI.getValueType(ResSTy->getElementType(i)), Val);
4154 if (MVT::isVector(Val.getValueType()))
4155 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4159 setValue(CS.getInstruction(), Val);
4162 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4164 // Process indirect outputs, first output all of the flagged copies out of
4166 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4167 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4168 Value *Ptr = IndirectStoresToEmit[i].second;
4169 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4170 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4173 // Emit the non-flagged stores from the physregs.
4174 SmallVector<SDOperand, 8> OutChains;
4175 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4176 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4177 getValue(StoresToEmit[i].second),
4178 StoresToEmit[i].second, 0));
4179 if (!OutChains.empty())
4180 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4181 &OutChains[0], OutChains.size());
4186 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4187 SDOperand Src = getValue(I.getOperand(0));
4189 MVT::ValueType IntPtr = TLI.getPointerTy();
4191 if (IntPtr < Src.getValueType())
4192 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4193 else if (IntPtr > Src.getValueType())
4194 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4196 // Scale the source by the type size.
4197 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4198 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4199 Src, DAG.getIntPtrConstant(ElementSize));
4201 TargetLowering::ArgListTy Args;
4202 TargetLowering::ArgListEntry Entry;
4204 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4205 Args.push_back(Entry);
4207 std::pair<SDOperand,SDOperand> Result =
4208 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4209 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4210 setValue(&I, Result.first); // Pointers always fit in registers
4211 DAG.setRoot(Result.second);
4214 void SelectionDAGLowering::visitFree(FreeInst &I) {
4215 TargetLowering::ArgListTy Args;
4216 TargetLowering::ArgListEntry Entry;
4217 Entry.Node = getValue(I.getOperand(0));
4218 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4219 Args.push_back(Entry);
4220 MVT::ValueType IntPtr = TLI.getPointerTy();
4221 std::pair<SDOperand,SDOperand> Result =
4222 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4223 CallingConv::C, true,
4224 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4225 DAG.setRoot(Result.second);
4228 // EmitInstrWithCustomInserter - This method should be implemented by targets
4229 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4230 // instructions are special in various ways, which require special support to
4231 // insert. The specified MachineInstr is created but not inserted into any
4232 // basic blocks, and the scheduler passes ownership of it to this method.
4233 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4234 MachineBasicBlock *MBB) {
4235 cerr << "If a target marks an instruction with "
4236 << "'usesCustomDAGSchedInserter', it must implement "
4237 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4242 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4243 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4244 getValue(I.getOperand(1)),
4245 DAG.getSrcValue(I.getOperand(1))));
4248 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4249 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4250 getValue(I.getOperand(0)),
4251 DAG.getSrcValue(I.getOperand(0)));
4253 DAG.setRoot(V.getValue(1));
4256 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4257 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4258 getValue(I.getOperand(1)),
4259 DAG.getSrcValue(I.getOperand(1))));
4262 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4263 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4264 getValue(I.getOperand(1)),
4265 getValue(I.getOperand(2)),
4266 DAG.getSrcValue(I.getOperand(1)),
4267 DAG.getSrcValue(I.getOperand(2))));
4270 /// TargetLowering::LowerArguments - This is the default LowerArguments
4271 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4272 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4273 /// integrated into SDISel.
4274 std::vector<SDOperand>
4275 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4276 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4277 std::vector<SDOperand> Ops;
4278 Ops.push_back(DAG.getRoot());
4279 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4280 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4282 // Add one result value for each formal argument.
4283 std::vector<MVT::ValueType> RetVals;
4285 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4287 MVT::ValueType VT = getValueType(I->getType());
4288 ISD::ArgFlagsTy Flags;
4289 unsigned OriginalAlignment =
4290 getTargetData()->getABITypeAlignment(I->getType());
4292 if (F.paramHasAttr(j, ParamAttr::ZExt))
4294 if (F.paramHasAttr(j, ParamAttr::SExt))
4296 if (F.paramHasAttr(j, ParamAttr::InReg))
4298 if (F.paramHasAttr(j, ParamAttr::StructRet))
4300 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4302 const PointerType *Ty = cast<PointerType>(I->getType());
4303 const Type *ElementTy = Ty->getElementType();
4304 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4305 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4306 // For ByVal, alignment should be passed from FE. BE will guess if
4307 // this info is not there but there are cases it cannot get right.
4308 if (F.getParamAlignment(j))
4309 FrameAlign = F.getParamAlignment(j);
4310 Flags.setByValAlign(FrameAlign);
4311 Flags.setByValSize(FrameSize);
4313 if (F.paramHasAttr(j, ParamAttr::Nest))
4315 Flags.setOrigAlign(OriginalAlignment);
4317 MVT::ValueType RegisterVT = getRegisterType(VT);
4318 unsigned NumRegs = getNumRegisters(VT);
4319 for (unsigned i = 0; i != NumRegs; ++i) {
4320 RetVals.push_back(RegisterVT);
4321 ISD::ArgFlagsTy MyFlags = Flags;
4322 if (NumRegs > 1 && i == 0)
4324 // if it isn't first piece, alignment must be 1
4326 MyFlags.setOrigAlign(1);
4327 Ops.push_back(DAG.getArgFlags(MyFlags));
4331 RetVals.push_back(MVT::Other);
4334 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4335 DAG.getVTList(&RetVals[0], RetVals.size()),
4336 &Ops[0], Ops.size()).Val;
4338 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4339 // allows exposing the loads that may be part of the argument access to the
4340 // first DAGCombiner pass.
4341 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4343 // The number of results should match up, except that the lowered one may have
4344 // an extra flag result.
4345 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4346 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4347 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4348 && "Lowering produced unexpected number of results!");
4349 Result = TmpRes.Val;
4351 unsigned NumArgRegs = Result->getNumValues() - 1;
4352 DAG.setRoot(SDOperand(Result, NumArgRegs));
4354 // Set up the return result vector.
4358 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4360 MVT::ValueType VT = getValueType(I->getType());
4361 MVT::ValueType PartVT = getRegisterType(VT);
4363 unsigned NumParts = getNumRegisters(VT);
4364 SmallVector<SDOperand, 4> Parts(NumParts);
4365 for (unsigned j = 0; j != NumParts; ++j)
4366 Parts[j] = SDOperand(Result, i++);
4368 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4369 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4370 AssertOp = ISD::AssertSext;
4371 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4372 AssertOp = ISD::AssertZext;
4374 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4377 assert(i == NumArgRegs && "Argument register count mismatch!");
4382 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4383 /// implementation, which just inserts an ISD::CALL node, which is later custom
4384 /// lowered by the target to something concrete. FIXME: When all targets are
4385 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4386 std::pair<SDOperand, SDOperand>
4387 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4388 bool RetSExt, bool RetZExt, bool isVarArg,
4389 unsigned CallingConv, bool isTailCall,
4391 ArgListTy &Args, SelectionDAG &DAG) {
4392 SmallVector<SDOperand, 32> Ops;
4393 Ops.push_back(Chain); // Op#0 - Chain
4394 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4395 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4396 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4397 Ops.push_back(Callee);
4399 // Handle all of the outgoing arguments.
4400 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4401 MVT::ValueType VT = getValueType(Args[i].Ty);
4402 SDOperand Op = Args[i].Node;
4403 ISD::ArgFlagsTy Flags;
4404 unsigned OriginalAlignment =
4405 getTargetData()->getABITypeAlignment(Args[i].Ty);
4411 if (Args[i].isInReg)
4415 if (Args[i].isByVal) {
4417 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4418 const Type *ElementTy = Ty->getElementType();
4419 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4420 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4421 // For ByVal, alignment should come from FE. BE will guess if this
4422 // info is not there but there are cases it cannot get right.
4423 if (Args[i].Alignment)
4424 FrameAlign = Args[i].Alignment;
4425 Flags.setByValAlign(FrameAlign);
4426 Flags.setByValSize(FrameSize);
4430 Flags.setOrigAlign(OriginalAlignment);
4432 MVT::ValueType PartVT = getRegisterType(VT);
4433 unsigned NumParts = getNumRegisters(VT);
4434 SmallVector<SDOperand, 4> Parts(NumParts);
4435 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4438 ExtendKind = ISD::SIGN_EXTEND;
4439 else if (Args[i].isZExt)
4440 ExtendKind = ISD::ZERO_EXTEND;
4442 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4444 for (unsigned i = 0; i != NumParts; ++i) {
4445 // if it isn't first piece, alignment must be 1
4446 ISD::ArgFlagsTy MyFlags = Flags;
4447 if (NumParts > 1 && i == 0)
4450 MyFlags.setOrigAlign(1);
4452 Ops.push_back(Parts[i]);
4453 Ops.push_back(DAG.getArgFlags(MyFlags));
4457 // Figure out the result value types. We start by making a list of
4458 // the potentially illegal return value types.
4459 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4460 SmallVector<MVT::ValueType, 4> RetTys;
4461 ComputeValueVTs(*this, RetTy, RetTys);
4463 // Then we translate that to a list of legal types.
4464 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4465 MVT::ValueType VT = RetTys[I];
4466 MVT::ValueType RegisterVT = getRegisterType(VT);
4467 unsigned NumRegs = getNumRegisters(VT);
4468 for (unsigned i = 0; i != NumRegs; ++i)
4469 LoweredRetTys.push_back(RegisterVT);
4472 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4474 // Create the CALL node.
4475 SDOperand Res = DAG.getNode(ISD::CALL,
4476 DAG.getVTList(&LoweredRetTys[0],
4477 LoweredRetTys.size()),
4478 &Ops[0], Ops.size());
4479 Chain = Res.getValue(LoweredRetTys.size() - 1);
4481 // Gather up the call result into a single value.
4482 if (RetTy != Type::VoidTy) {
4483 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4486 AssertOp = ISD::AssertSext;
4488 AssertOp = ISD::AssertZext;
4490 SmallVector<SDOperand, 4> ReturnValues;
4492 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4493 MVT::ValueType VT = RetTys[I];
4494 MVT::ValueType RegisterVT = getRegisterType(VT);
4495 unsigned NumRegs = getNumRegisters(VT);
4496 unsigned RegNoEnd = NumRegs + RegNo;
4497 SmallVector<SDOperand, 4> Results;
4498 for (; RegNo != RegNoEnd; ++RegNo)
4499 Results.push_back(Res.getValue(RegNo));
4500 SDOperand ReturnValue =
4501 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4503 ReturnValues.push_back(ReturnValue);
4505 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4506 DAG.getNode(ISD::MERGE_VALUES,
4507 DAG.getVTList(&RetTys[0], RetTys.size()),
4508 &ReturnValues[0], ReturnValues.size());
4511 return std::make_pair(Res, Chain);
4514 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4515 assert(0 && "LowerOperation not implemented for this target!");
4520 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4521 SelectionDAG &DAG) {
4522 assert(0 && "CustomPromoteOperation not implemented for this target!");
4527 //===----------------------------------------------------------------------===//
4528 // SelectionDAGISel code
4529 //===----------------------------------------------------------------------===//
4531 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4532 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4535 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4536 AU.addRequired<AliasAnalysis>();
4537 AU.addRequired<CollectorModuleMetadata>();
4538 AU.setPreservesAll();
4541 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4542 // Get alias analysis for load/store combining.
4543 AA = &getAnalysis<AliasAnalysis>();
4545 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4546 if (MF.getFunction()->hasCollector())
4547 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4550 RegInfo = &MF.getRegInfo();
4551 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4553 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4555 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4556 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4557 // Mark landing pad.
4558 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4560 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4561 SelectBasicBlock(I, MF, FuncInfo);
4563 // Add function live-ins to entry block live-in set.
4564 BasicBlock *EntryBB = &Fn.getEntryBlock();
4565 BB = FuncInfo.MBBMap[EntryBB];
4566 if (!RegInfo->livein_empty())
4567 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4568 E = RegInfo->livein_end(); I != E; ++I)
4569 BB->addLiveIn(I->first);
4572 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4573 "Not all catch info was assigned to a landing pad!");
4579 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4580 SDOperand Op = getValue(V);
4581 assert((Op.getOpcode() != ISD::CopyFromReg ||
4582 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4583 "Copy from a reg to the same reg!");
4584 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4586 RegsForValue RFV(TLI, Reg, V->getType());
4587 SDOperand Chain = DAG.getEntryNode();
4588 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4589 PendingExports.push_back(Chain);
4592 void SelectionDAGISel::
4593 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4594 // If this is the entry block, emit arguments.
4595 Function &F = *LLVMBB->getParent();
4596 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4597 SDOperand OldRoot = SDL.DAG.getRoot();
4598 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4601 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4603 if (!AI->use_empty()) {
4604 SDL.setValue(AI, Args[a]);
4606 // If this argument is live outside of the entry block, insert a copy from
4607 // whereever we got it to the vreg that other BB's will reference it as.
4608 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4609 if (VMI != FuncInfo.ValueMap.end()) {
4610 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4614 // Finally, if the target has anything special to do, allow it to do so.
4615 // FIXME: this should insert code into the DAG!
4616 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4619 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4620 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4621 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4622 if (isSelector(I)) {
4623 // Apply the catch info to DestBB.
4624 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4626 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4627 FLI.CatchInfoFound.insert(I);
4632 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4633 /// whether object offset >= 0.
4635 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4636 if (!isa<FrameIndexSDNode>(Op)) return false;
4638 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4639 int FrameIdx = FrameIdxNode->getIndex();
4640 return MFI->isFixedObjectIndex(FrameIdx) &&
4641 MFI->getObjectOffset(FrameIdx) >= 0;
4644 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4645 /// possibly be overwritten when lowering the outgoing arguments in a tail
4646 /// call. Currently the implementation of this call is very conservative and
4647 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4648 /// virtual registers would be overwritten by direct lowering.
4649 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4650 MachineFrameInfo * MFI) {
4651 RegisterSDNode * OpReg = NULL;
4652 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4653 (Op.getOpcode()== ISD::CopyFromReg &&
4654 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4655 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4656 (Op.getOpcode() == ISD::LOAD &&
4657 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4658 (Op.getOpcode() == ISD::MERGE_VALUES &&
4659 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4660 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4666 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4667 /// DAG and fixes their tailcall attribute operand.
4668 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4669 TargetLowering& TLI) {
4670 SDNode * Ret = NULL;
4671 SDOperand Terminator = DAG.getRoot();
4674 if (Terminator.getOpcode() == ISD::RET) {
4675 Ret = Terminator.Val;
4678 // Fix tail call attribute of CALL nodes.
4679 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4680 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4681 if (BI->getOpcode() == ISD::CALL) {
4682 SDOperand OpRet(Ret, 0);
4683 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4684 bool isMarkedTailCall =
4685 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4686 // If CALL node has tail call attribute set to true and the call is not
4687 // eligible (no RET or the target rejects) the attribute is fixed to
4688 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4689 // must correctly identify tail call optimizable calls.
4690 if (!isMarkedTailCall) continue;
4692 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4693 // Not eligible. Mark CALL node as non tail call.
4694 SmallVector<SDOperand, 32> Ops;
4696 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4697 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4701 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4703 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4705 // Look for tail call clobbered arguments. Emit a series of
4706 // copyto/copyfrom virtual register nodes to protect them.
4707 SmallVector<SDOperand, 32> Ops;
4708 SDOperand Chain = OpCall.getOperand(0), InFlag;
4710 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4711 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4713 if (idx > 4 && (idx % 2)) {
4714 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4715 getArgFlags().isByVal();
4716 MachineFunction &MF = DAG.getMachineFunction();
4717 MachineFrameInfo *MFI = MF.getFrameInfo();
4719 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
4720 MVT::ValueType VT = Arg.getValueType();
4721 unsigned VReg = MF.getRegInfo().
4722 createVirtualRegister(TLI.getRegClassFor(VT));
4723 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4724 InFlag = Chain.getValue(1);
4725 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4726 Chain = Arg.getValue(1);
4727 InFlag = Arg.getValue(2);
4732 // Link in chain of CopyTo/CopyFromReg.
4734 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4740 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4741 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4742 FunctionLoweringInfo &FuncInfo) {
4743 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
4745 // Lower any arguments needed in this block if this is the entry block.
4746 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4747 LowerArguments(LLVMBB, SDL);
4749 BB = FuncInfo.MBBMap[LLVMBB];
4750 SDL.setCurrentBasicBlock(BB);
4752 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4754 if (MMI && BB->isLandingPad()) {
4755 // Add a label to mark the beginning of the landing pad. Deletion of the
4756 // landing pad can thus be detected via the MachineModuleInfo.
4757 unsigned LabelID = MMI->addLandingPad(BB);
4758 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4759 DAG.getConstant(LabelID, MVT::i32),
4760 DAG.getConstant(1, MVT::i32)));
4762 // Mark exception register as live in.
4763 unsigned Reg = TLI.getExceptionAddressRegister();
4764 if (Reg) BB->addLiveIn(Reg);
4766 // Mark exception selector register as live in.
4767 Reg = TLI.getExceptionSelectorRegister();
4768 if (Reg) BB->addLiveIn(Reg);
4770 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4771 // function and list of typeids logically belong to the invoke (or, if you
4772 // like, the basic block containing the invoke), and need to be associated
4773 // with it in the dwarf exception handling tables. Currently however the
4774 // information is provided by an intrinsic (eh.selector) that can be moved
4775 // to unexpected places by the optimizers: if the unwind edge is critical,
4776 // then breaking it can result in the intrinsics being in the successor of
4777 // the landing pad, not the landing pad itself. This results in exceptions
4778 // not being caught because no typeids are associated with the invoke.
4779 // This may not be the only way things can go wrong, but it is the only way
4780 // we try to work around for the moment.
4781 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4783 if (Br && Br->isUnconditional()) { // Critical edge?
4784 BasicBlock::iterator I, E;
4785 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4790 // No catch info found - try to extract some from the successor.
4791 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4795 // Lower all of the non-terminator instructions.
4796 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4800 // Ensure that all instructions which are used outside of their defining
4801 // blocks are available as virtual registers. Invoke is handled elsewhere.
4802 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4803 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4804 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4805 if (VMI != FuncInfo.ValueMap.end())
4806 SDL.CopyValueToVirtualRegister(I, VMI->second);
4809 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4810 // ensure constants are generated when needed. Remember the virtual registers
4811 // that need to be added to the Machine PHI nodes as input. We cannot just
4812 // directly add them, because expansion might result in multiple MBB's for one
4813 // BB. As such, the start of the BB might correspond to a different MBB than
4816 TerminatorInst *TI = LLVMBB->getTerminator();
4818 // Emit constants only once even if used by multiple PHI nodes.
4819 std::map<Constant*, unsigned> ConstantsOut;
4821 // Vector bool would be better, but vector<bool> is really slow.
4822 std::vector<unsigned char> SuccsHandled;
4823 if (TI->getNumSuccessors())
4824 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4826 // Check successor nodes' PHI nodes that expect a constant to be available
4828 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4829 BasicBlock *SuccBB = TI->getSuccessor(succ);
4830 if (!isa<PHINode>(SuccBB->begin())) continue;
4831 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4833 // If this terminator has multiple identical successors (common for
4834 // switches), only handle each succ once.
4835 unsigned SuccMBBNo = SuccMBB->getNumber();
4836 if (SuccsHandled[SuccMBBNo]) continue;
4837 SuccsHandled[SuccMBBNo] = true;
4839 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4842 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4843 // nodes and Machine PHI nodes, but the incoming operands have not been
4845 for (BasicBlock::iterator I = SuccBB->begin();
4846 (PN = dyn_cast<PHINode>(I)); ++I) {
4847 // Ignore dead phi's.
4848 if (PN->use_empty()) continue;
4851 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4853 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4854 unsigned &RegOut = ConstantsOut[C];
4856 RegOut = FuncInfo.CreateRegForValue(C);
4857 SDL.CopyValueToVirtualRegister(C, RegOut);
4861 Reg = FuncInfo.ValueMap[PHIOp];
4863 assert(isa<AllocaInst>(PHIOp) &&
4864 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4865 "Didn't codegen value into a register!??");
4866 Reg = FuncInfo.CreateRegForValue(PHIOp);
4867 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
4871 // Remember that this register needs to added to the machine PHI node as
4872 // the input for this MBB.
4873 MVT::ValueType VT = TLI.getValueType(PN->getType());
4874 unsigned NumRegisters = TLI.getNumRegisters(VT);
4875 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4876 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4879 ConstantsOut.clear();
4881 // Lower the terminator after the copies are emitted.
4882 SDL.visit(*LLVMBB->getTerminator());
4884 // Copy over any CaseBlock records that may now exist due to SwitchInst
4885 // lowering, as well as any jump table information.
4886 SwitchCases.clear();
4887 SwitchCases = SDL.SwitchCases;
4889 JTCases = SDL.JTCases;
4890 BitTestCases.clear();
4891 BitTestCases = SDL.BitTestCases;
4893 // Make sure the root of the DAG is up-to-date.
4894 DAG.setRoot(SDL.getControlRoot());
4896 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4897 // with correct tailcall attribute so that the target can rely on the tailcall
4898 // attribute indicating whether the call is really eligible for tail call
4900 CheckDAGForTailCallsAndFixThem(DAG, TLI);
4903 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4904 DOUT << "Lowered selection DAG:\n";
4907 // Run the DAG combiner in pre-legalize mode.
4908 DAG.Combine(false, *AA);
4910 DOUT << "Optimized lowered selection DAG:\n";
4913 // Second step, hack on the DAG until it only uses operations and types that
4914 // the target supports.
4915 #if 0 // Enable this some day.
4916 DAG.LegalizeTypes();
4917 // Someday even later, enable a dag combine pass here.
4921 DOUT << "Legalized selection DAG:\n";
4924 // Run the DAG combiner in post-legalize mode.
4925 DAG.Combine(true, *AA);
4927 DOUT << "Optimized legalized selection DAG:\n";
4930 if (ViewISelDAGs) DAG.viewGraph();
4932 // Third, instruction select all of the operations to machine code, adding the
4933 // code to the MachineBasicBlock.
4934 InstructionSelectBasicBlock(DAG);
4936 DOUT << "Selected machine code:\n";
4940 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4941 FunctionLoweringInfo &FuncInfo) {
4942 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4944 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4947 // First step, lower LLVM code to some DAG. This DAG may use operations and
4948 // types that are not supported by the target.
4949 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4951 // Second step, emit the lowered DAG as machine code.
4952 CodeGenAndEmitDAG(DAG);
4955 DOUT << "Total amount of phi nodes to update: "
4956 << PHINodesToUpdate.size() << "\n";
4957 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4958 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4959 << ", " << PHINodesToUpdate[i].second << ")\n";);
4961 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4962 // PHI nodes in successors.
4963 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4964 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4965 MachineInstr *PHI = PHINodesToUpdate[i].first;
4966 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4967 "This is not a machine PHI node that we are updating!");
4968 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4970 PHI->addOperand(MachineOperand::CreateMBB(BB));
4975 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4976 // Lower header first, if it wasn't already lowered
4977 if (!BitTestCases[i].Emitted) {
4978 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4980 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
4981 // Set the current basic block to the mbb we wish to insert the code into
4982 BB = BitTestCases[i].Parent;
4983 HSDL.setCurrentBasicBlock(BB);
4985 HSDL.visitBitTestHeader(BitTestCases[i]);
4986 HSDAG.setRoot(HSDL.getRoot());
4987 CodeGenAndEmitDAG(HSDAG);
4990 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4991 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4993 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
4994 // Set the current basic block to the mbb we wish to insert the code into
4995 BB = BitTestCases[i].Cases[j].ThisBB;
4996 BSDL.setCurrentBasicBlock(BB);
4999 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5000 BitTestCases[i].Reg,
5001 BitTestCases[i].Cases[j]);
5003 BSDL.visitBitTestCase(BitTestCases[i].Default,
5004 BitTestCases[i].Reg,
5005 BitTestCases[i].Cases[j]);
5008 BSDAG.setRoot(BSDL.getRoot());
5009 CodeGenAndEmitDAG(BSDAG);
5013 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5014 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5015 MachineBasicBlock *PHIBB = PHI->getParent();
5016 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5017 "This is not a machine PHI node that we are updating!");
5018 // This is "default" BB. We have two jumps to it. From "header" BB and
5019 // from last "case" BB.
5020 if (PHIBB == BitTestCases[i].Default) {
5021 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5023 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5024 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5026 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5029 // One of "cases" BB.
5030 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5031 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5032 if (cBB->succ_end() !=
5033 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5034 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5036 PHI->addOperand(MachineOperand::CreateMBB(cBB));
5042 // If the JumpTable record is filled in, then we need to emit a jump table.
5043 // Updating the PHI nodes is tricky in this case, since we need to determine
5044 // whether the PHI is a successor of the range check MBB or the jump table MBB
5045 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5046 // Lower header first, if it wasn't already lowered
5047 if (!JTCases[i].first.Emitted) {
5048 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5050 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5051 // Set the current basic block to the mbb we wish to insert the code into
5052 BB = JTCases[i].first.HeaderBB;
5053 HSDL.setCurrentBasicBlock(BB);
5055 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5056 HSDAG.setRoot(HSDL.getRoot());
5057 CodeGenAndEmitDAG(HSDAG);
5060 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5062 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5063 // Set the current basic block to the mbb we wish to insert the code into
5064 BB = JTCases[i].second.MBB;
5065 JSDL.setCurrentBasicBlock(BB);
5067 JSDL.visitJumpTable(JTCases[i].second);
5068 JSDAG.setRoot(JSDL.getRoot());
5069 CodeGenAndEmitDAG(JSDAG);
5072 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5073 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5074 MachineBasicBlock *PHIBB = PHI->getParent();
5075 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5076 "This is not a machine PHI node that we are updating!");
5077 // "default" BB. We can go there only from header BB.
5078 if (PHIBB == JTCases[i].second.Default) {
5079 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5081 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5083 // JT BB. Just iterate over successors here
5084 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5085 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5087 PHI->addOperand(MachineOperand::CreateMBB(BB));
5092 // If the switch block involved a branch to one of the actual successors, we
5093 // need to update PHI nodes in that block.
5094 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5095 MachineInstr *PHI = PHINodesToUpdate[i].first;
5096 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5097 "This is not a machine PHI node that we are updating!");
5098 if (BB->isSuccessor(PHI->getParent())) {
5099 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5101 PHI->addOperand(MachineOperand::CreateMBB(BB));
5105 // If we generated any switch lowering information, build and codegen any
5106 // additional DAGs necessary.
5107 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5108 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5110 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5112 // Set the current basic block to the mbb we wish to insert the code into
5113 BB = SwitchCases[i].ThisBB;
5114 SDL.setCurrentBasicBlock(BB);
5117 SDL.visitSwitchCase(SwitchCases[i]);
5118 SDAG.setRoot(SDL.getRoot());
5119 CodeGenAndEmitDAG(SDAG);
5121 // Handle any PHI nodes in successors of this chunk, as if we were coming
5122 // from the original BB before switch expansion. Note that PHI nodes can
5123 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5124 // handle them the right number of times.
5125 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5126 for (MachineBasicBlock::iterator Phi = BB->begin();
5127 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5128 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5129 for (unsigned pn = 0; ; ++pn) {
5130 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5131 if (PHINodesToUpdate[pn].first == Phi) {
5132 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5134 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5140 // Don't process RHS if same block as LHS.
5141 if (BB == SwitchCases[i].FalseBB)
5142 SwitchCases[i].FalseBB = 0;
5144 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5145 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5146 SwitchCases[i].FalseBB = 0;
5148 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5153 //===----------------------------------------------------------------------===//
5154 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5155 /// target node in the graph.
5156 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5157 if (ViewSchedDAGs) DAG.viewGraph();
5159 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5163 RegisterScheduler::setDefault(Ctor);
5166 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5169 if (ViewSUnitDAGs) SL->viewGraph();
5175 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5176 return new HazardRecognizer();
5179 //===----------------------------------------------------------------------===//
5180 // Helper functions used by the generated instruction selector.
5181 //===----------------------------------------------------------------------===//
5182 // Calls to these methods are generated by tblgen.
5184 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5185 /// the dag combiner simplified the 255, we still want to match. RHS is the
5186 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5187 /// specified in the .td file (e.g. 255).
5188 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5189 int64_t DesiredMaskS) const {
5190 const APInt &ActualMask = RHS->getAPIntValue();
5191 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5193 // If the actual mask exactly matches, success!
5194 if (ActualMask == DesiredMask)
5197 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5198 if (ActualMask.intersects(~DesiredMask))
5201 // Otherwise, the DAG Combiner may have proven that the value coming in is
5202 // either already zero or is not demanded. Check for known zero input bits.
5203 APInt NeededMask = DesiredMask & ~ActualMask;
5204 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5207 // TODO: check to see if missing bits are just not demanded.
5209 // Otherwise, this pattern doesn't match.
5213 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5214 /// the dag combiner simplified the 255, we still want to match. RHS is the
5215 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5216 /// specified in the .td file (e.g. 255).
5217 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5218 int64_t DesiredMaskS) const {
5219 const APInt &ActualMask = RHS->getAPIntValue();
5220 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5222 // If the actual mask exactly matches, success!
5223 if (ActualMask == DesiredMask)
5226 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5227 if (ActualMask.intersects(~DesiredMask))
5230 // Otherwise, the DAG Combiner may have proven that the value coming in is
5231 // either already zero or is not demanded. Check for known zero input bits.
5232 APInt NeededMask = DesiredMask & ~ActualMask;
5234 APInt KnownZero, KnownOne;
5235 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5237 // If all the missing bits in the or are already known to be set, match!
5238 if ((NeededMask & KnownOne) == NeededMask)
5241 // TODO: check to see if missing bits are just not demanded.
5243 // Otherwise, this pattern doesn't match.
5248 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5249 /// by tblgen. Others should not call it.
5250 void SelectionDAGISel::
5251 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5252 std::vector<SDOperand> InOps;
5253 std::swap(InOps, Ops);
5255 Ops.push_back(InOps[0]); // input chain.
5256 Ops.push_back(InOps[1]); // input asm string.
5258 unsigned i = 2, e = InOps.size();
5259 if (InOps[e-1].getValueType() == MVT::Flag)
5260 --e; // Don't process a flag operand if it is here.
5263 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5264 if ((Flags & 7) != 4 /*MEM*/) {
5265 // Just skip over this operand, copying the operands verbatim.
5266 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5267 i += (Flags >> 3) + 1;
5269 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5270 // Otherwise, this is a memory operand. Ask the target to select it.
5271 std::vector<SDOperand> SelOps;
5272 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5273 cerr << "Could not match memory address. Inline asm failure!\n";
5277 // Add this to the output node.
5278 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5279 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5281 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5286 // Add the flag input back if present.
5287 if (e != InOps.size())
5288 Ops.push_back(InOps.back());
5291 char SelectionDAGISel::ID = 0;