1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/SchedulerRegistry.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/SSARegMap.h"
37 #include "llvm/Target/MRegisterInfo.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetFrameInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/Compiler.h"
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
61 //===---------------------------------------------------------------------===//
63 /// RegisterScheduler class - Track the registration of instruction schedulers.
65 //===---------------------------------------------------------------------===//
66 MachinePassRegistry RegisterScheduler::Registry;
68 //===---------------------------------------------------------------------===//
70 /// ISHeuristic command line option for instruction schedulers.
72 //===---------------------------------------------------------------------===//
74 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
77 cl::init(&createDefaultScheduler),
78 cl::desc("Instruction schedulers available:"));
80 static RegisterScheduler
81 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
85 namespace { struct AsmOperandInfo; }
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
92 struct VISIBILITY_HIDDEN RegsForValue {
93 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
96 std::vector<unsigned> Regs;
98 /// RegVT - The value type of each register.
100 MVT::ValueType RegVT;
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
112 RegsForValue(const std::vector<unsigned> ®s,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
121 SDOperand &Chain, SDOperand &Flag) const;
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
134 std::vector<SDOperand> &Ops) const;
139 //===--------------------------------------------------------------------===//
140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
157 //===--------------------------------------------------------------------===//
158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
160 class FunctionLoweringInfo {
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
175 DenseMap<const Value*, unsigned> ValueMap;
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
182 unsigned MakeReg(MVT::ValueType VT) {
183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 /// isExportedInst - Return true if the specified value is an instruction
187 /// exported from its block.
188 bool isExportedInst(const Value *V) {
189 return ValueMap.count(V);
192 unsigned CreateRegForValue(const Value *V);
194 unsigned InitializeRegForValue(const Value *V) {
195 unsigned &R = ValueMap[V];
196 assert(R == 0 && "Already initialized this value register!");
197 return R = CreateRegForValue(V);
202 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
203 /// PHI nodes or outside of the basic block that defines it, or used by a
204 /// switch instruction, which may expand to multiple basic blocks.
205 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206 if (isa<PHINode>(I)) return true;
207 BasicBlock *BB = I->getParent();
208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
210 // FIXME: Remove switchinst special case.
211 isa<SwitchInst>(*UI))
216 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
217 /// entry block, return true. This includes arguments used by switches, since
218 /// the switch may expand into multiple basic blocks.
219 static bool isOnlyUsedInEntryBlock(Argument *A) {
220 BasicBlock *Entry = A->getParent()->begin();
221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
223 return false; // Use not in entry block.
227 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
228 Function &fn, MachineFunction &mf)
229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
231 // Create a vreg for each argument register that is not dead and is used
232 // outside of the entry block for the function.
233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
235 if (!isOnlyUsedInEntryBlock(AI))
236 InitializeRegForValue(AI);
238 // Initialize the mapping of values to registers. This is only set up for
239 // instruction values that are used outside of the block that defines
241 Function::iterator BB = Fn.begin(), EB = Fn.end();
242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
245 const Type *Ty = AI->getAllocatedType();
246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
248 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
251 TySize *= CUI->getZExtValue(); // Get total allocated size.
252 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
253 StaticAllocaMap[AI] =
254 MF.getFrameInfo()->CreateStackObject(TySize, Align);
257 for (; BB != EB; ++BB)
258 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
259 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
260 if (!isa<AllocaInst>(I) ||
261 !StaticAllocaMap.count(cast<AllocaInst>(I)))
262 InitializeRegForValue(I);
264 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
265 // also creates the initial PHI MachineInstrs, though none of the input
266 // operands are populated.
267 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
268 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
270 MF.getBasicBlockList().push_back(MBB);
272 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
275 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
276 if (PN->use_empty()) continue;
278 MVT::ValueType VT = TLI.getValueType(PN->getType());
279 unsigned NumElements;
280 if (VT != MVT::Vector)
281 NumElements = TLI.getNumElements(VT);
283 MVT::ValueType VT1,VT2;
285 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
288 unsigned PHIReg = ValueMap[PN];
289 assert(PHIReg && "PHI node does not have an assigned virtual register!");
290 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
291 for (unsigned i = 0; i != NumElements; ++i)
292 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
297 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
298 /// the correctly promoted or expanded types. Assign these registers
299 /// consecutive vreg numbers and return the first assigned number.
300 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
301 MVT::ValueType VT = TLI.getValueType(V->getType());
303 // The number of multiples of registers that we need, to, e.g., split up
304 // a <2 x int64> -> 4 x i32 registers.
305 unsigned NumVectorRegs = 1;
307 // If this is a vector type, figure out what type it will decompose into
308 // and how many of the elements it will use.
309 if (VT == MVT::Vector) {
310 const VectorType *PTy = cast<VectorType>(V->getType());
311 unsigned NumElts = PTy->getNumElements();
312 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
313 MVT::ValueType VecTy = MVT::getVectorType(EltTy, NumElts);
315 // Divide the input until we get to a supported size. This will always
316 // end with a scalar if the target doesn't support vectors.
317 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
320 VecTy = MVT::getVectorType(EltTy, NumElts);
323 // Check that VecTy isn't a 1-element vector.
324 if (NumElts == 1 && VecTy == MVT::Other)
330 // The common case is that we will only create one register for this
331 // value. If we have that case, create and return the virtual register.
332 unsigned NV = TLI.getNumElements(VT);
334 // If we are promoting this value, pick the next largest supported type.
335 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
336 unsigned Reg = MakeReg(PromotedType);
337 // If this is a vector of supported or promoted types (e.g. 4 x i16),
338 // create all of the registers.
339 for (unsigned i = 1; i != NumVectorRegs; ++i)
340 MakeReg(PromotedType);
344 // If this value is represented with multiple target registers, make sure
345 // to create enough consecutive registers of the right (smaller) type.
346 VT = TLI.getTypeToExpandTo(VT);
347 unsigned R = MakeReg(VT);
348 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
353 //===----------------------------------------------------------------------===//
354 /// SelectionDAGLowering - This is the common target-independent lowering
355 /// implementation that is parameterized by a TargetLowering object.
356 /// Also, targets can overload any lowering method.
359 class SelectionDAGLowering {
360 MachineBasicBlock *CurMBB;
362 DenseMap<const Value*, SDOperand> NodeMap;
364 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
365 /// them up and then emit token factor nodes when possible. This allows us to
366 /// get simple disambiguation between loads without worrying about alias
368 std::vector<SDOperand> PendingLoads;
370 /// Case - A struct to record the Value for a switch case, and the
371 /// case's target basic block.
375 MachineBasicBlock* BB;
377 Case() : Low(0), High(0), BB(0) { }
378 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
379 Low(low), High(high), BB(bb) { }
380 uint64_t size() const {
381 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
382 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
383 return (rHigh - rLow + 1ULL);
389 MachineBasicBlock* BB;
392 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
393 Mask(mask), BB(bb), Bits(bits) { }
396 typedef std::vector<Case> CaseVector;
397 typedef std::vector<CaseBits> CaseBitsVector;
398 typedef CaseVector::iterator CaseItr;
399 typedef std::pair<CaseItr, CaseItr> CaseRange;
401 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
402 /// of conditional branches.
404 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
405 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
407 /// CaseBB - The MBB in which to emit the compare and branch
408 MachineBasicBlock *CaseBB;
409 /// LT, GE - If nonzero, we know the current case value must be less-than or
410 /// greater-than-or-equal-to these Constants.
413 /// Range - A pair of iterators representing the range of case values to be
414 /// processed at this point in the binary search tree.
418 typedef std::vector<CaseRec> CaseRecVector;
420 /// The comparison function for sorting the switch case values in the vector.
421 /// WARNING: Case ranges should be disjoint!
423 bool operator () (const Case& C1, const Case& C2) {
424 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
425 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
426 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
427 return CI1->getValue().slt(CI2->getValue());
432 bool operator () (const CaseBits& C1, const CaseBits& C2) {
433 return C1.Bits > C2.Bits;
437 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
440 // TLI - This is information that describes the available target features we
441 // need for lowering. This indicates when operations are unavailable,
442 // implemented with a libcall, etc.
445 const TargetData *TD;
447 /// SwitchCases - Vector of CaseBlock structures used to communicate
448 /// SwitchInst code generation information.
449 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
450 /// JTCases - Vector of JumpTable structures used to communicate
451 /// SwitchInst code generation information.
452 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
453 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
455 /// FuncInfo - Information about the function as a whole.
457 FunctionLoweringInfo &FuncInfo;
459 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
460 FunctionLoweringInfo &funcinfo)
461 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
465 /// getRoot - Return the current virtual root of the Selection DAG.
467 SDOperand getRoot() {
468 if (PendingLoads.empty())
469 return DAG.getRoot();
471 if (PendingLoads.size() == 1) {
472 SDOperand Root = PendingLoads[0];
474 PendingLoads.clear();
478 // Otherwise, we have to make a token factor node.
479 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
480 &PendingLoads[0], PendingLoads.size());
481 PendingLoads.clear();
486 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
488 void visit(Instruction &I) { visit(I.getOpcode(), I); }
490 void visit(unsigned Opcode, User &I) {
491 // Note: this doesn't use InstVisitor, because it has to work with
492 // ConstantExpr's in addition to instructions.
494 default: assert(0 && "Unknown instruction type encountered!");
496 // Build the switch statement using the Instruction.def file.
497 #define HANDLE_INST(NUM, OPCODE, CLASS) \
498 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
499 #include "llvm/Instruction.def"
503 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
505 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
506 const Value *SV, SDOperand Root,
507 bool isVolatile, unsigned Alignment);
509 SDOperand getIntPtrConstant(uint64_t Val) {
510 return DAG.getConstant(Val, TLI.getPointerTy());
513 SDOperand getValue(const Value *V);
515 void setValue(const Value *V, SDOperand NewN) {
516 SDOperand &N = NodeMap[V];
517 assert(N.Val == 0 && "Already set a value for this node!");
521 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
522 std::set<unsigned> &OutputRegs,
523 std::set<unsigned> &InputRegs);
525 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
526 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
528 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
529 void ExportFromCurrentBlock(Value *V);
530 void LowerCallTo(Instruction &I,
531 const Type *CalledValueTy, unsigned CallingConv,
532 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
533 MachineBasicBlock *LandingPad = NULL);
535 // Terminator instructions.
536 void visitRet(ReturnInst &I);
537 void visitBr(BranchInst &I);
538 void visitSwitch(SwitchInst &I);
539 void visitUnreachable(UnreachableInst &I) { /* noop */ }
541 // Helpers for visitSwitch
542 bool handleSmallSwitchRange(CaseRec& CR,
543 CaseRecVector& WorkList,
545 MachineBasicBlock* Default);
546 bool handleJTSwitchCase(CaseRec& CR,
547 CaseRecVector& WorkList,
549 MachineBasicBlock* Default);
550 bool handleBTSplitSwitchCase(CaseRec& CR,
551 CaseRecVector& WorkList,
553 MachineBasicBlock* Default);
554 bool handleBitTestsSwitchCase(CaseRec& CR,
555 CaseRecVector& WorkList,
557 MachineBasicBlock* Default);
558 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
559 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
560 void visitBitTestCase(MachineBasicBlock* NextMBB,
562 SelectionDAGISel::BitTestCase &B);
563 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
564 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
565 SelectionDAGISel::JumpTableHeader &JTH);
567 // These all get lowered before this pass.
568 void visitInvoke(InvokeInst &I);
569 void visitInvoke(InvokeInst &I, bool AsTerminator);
570 void visitUnwind(UnwindInst &I);
572 void visitScalarBinary(User &I, unsigned OpCode);
573 void visitVectorBinary(User &I, unsigned OpCode);
574 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
575 void visitShift(User &I, unsigned Opcode);
576 void visitAdd(User &I) {
577 if (isa<VectorType>(I.getType()))
578 visitVectorBinary(I, ISD::VADD);
579 else if (I.getType()->isFloatingPoint())
580 visitScalarBinary(I, ISD::FADD);
582 visitScalarBinary(I, ISD::ADD);
584 void visitSub(User &I);
585 void visitMul(User &I) {
586 if (isa<VectorType>(I.getType()))
587 visitVectorBinary(I, ISD::VMUL);
588 else if (I.getType()->isFloatingPoint())
589 visitScalarBinary(I, ISD::FMUL);
591 visitScalarBinary(I, ISD::MUL);
593 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
594 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
595 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
596 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
597 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
598 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
599 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
600 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
601 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
602 void visitShl (User &I) { visitShift(I, ISD::SHL); }
603 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
604 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
605 void visitICmp(User &I);
606 void visitFCmp(User &I);
607 // Visit the conversion instructions
608 void visitTrunc(User &I);
609 void visitZExt(User &I);
610 void visitSExt(User &I);
611 void visitFPTrunc(User &I);
612 void visitFPExt(User &I);
613 void visitFPToUI(User &I);
614 void visitFPToSI(User &I);
615 void visitUIToFP(User &I);
616 void visitSIToFP(User &I);
617 void visitPtrToInt(User &I);
618 void visitIntToPtr(User &I);
619 void visitBitCast(User &I);
621 void visitExtractElement(User &I);
622 void visitInsertElement(User &I);
623 void visitShuffleVector(User &I);
625 void visitGetElementPtr(User &I);
626 void visitSelect(User &I);
628 void visitMalloc(MallocInst &I);
629 void visitFree(FreeInst &I);
630 void visitAlloca(AllocaInst &I);
631 void visitLoad(LoadInst &I);
632 void visitStore(StoreInst &I);
633 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
634 void visitCall(CallInst &I);
635 void visitInlineAsm(CallInst &I);
636 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
637 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
639 void visitVAStart(CallInst &I);
640 void visitVAArg(VAArgInst &I);
641 void visitVAEnd(CallInst &I);
642 void visitVACopy(CallInst &I);
644 void visitMemIntrinsic(CallInst &I, unsigned Op);
646 void visitUserOp1(Instruction &I) {
647 assert(0 && "UserOp1 should not exist at instruction selection time!");
650 void visitUserOp2(Instruction &I) {
651 assert(0 && "UserOp2 should not exist at instruction selection time!");
655 } // end namespace llvm
657 SDOperand SelectionDAGLowering::getValue(const Value *V) {
658 SDOperand &N = NodeMap[V];
661 const Type *VTy = V->getType();
662 MVT::ValueType VT = TLI.getValueType(VTy);
663 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
664 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
665 visit(CE->getOpcode(), *CE);
666 SDOperand N1 = NodeMap[V];
667 assert(N1.Val && "visit didn't populate the ValueMap!");
669 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
670 return N = DAG.getGlobalAddress(GV, VT);
671 } else if (isa<ConstantPointerNull>(C)) {
672 return N = DAG.getConstant(0, TLI.getPointerTy());
673 } else if (isa<UndefValue>(C)) {
674 if (!isa<VectorType>(VTy))
675 return N = DAG.getNode(ISD::UNDEF, VT);
677 // Create a VBUILD_VECTOR of undef nodes.
678 const VectorType *PTy = cast<VectorType>(VTy);
679 unsigned NumElements = PTy->getNumElements();
680 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
682 SmallVector<SDOperand, 8> Ops;
683 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
685 // Create a VConstant node with generic Vector type.
686 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
687 Ops.push_back(DAG.getValueType(PVT));
688 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
689 &Ops[0], Ops.size());
690 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
691 return N = DAG.getConstantFP(CFP->getValue(), VT);
692 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
693 unsigned NumElements = PTy->getNumElements();
694 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
696 // Now that we know the number and type of the elements, push a
697 // Constant or ConstantFP node onto the ops list for each element of
698 // the packed constant.
699 SmallVector<SDOperand, 8> Ops;
700 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
701 for (unsigned i = 0; i != NumElements; ++i)
702 Ops.push_back(getValue(CP->getOperand(i)));
704 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
706 if (MVT::isFloatingPoint(PVT))
707 Op = DAG.getConstantFP(0, PVT);
709 Op = DAG.getConstant(0, PVT);
710 Ops.assign(NumElements, Op);
713 // Create a VBUILD_VECTOR node with generic Vector type.
714 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
715 Ops.push_back(DAG.getValueType(PVT));
716 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
719 // Canonicalize all constant ints to be unsigned.
720 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
724 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
725 std::map<const AllocaInst*, int>::iterator SI =
726 FuncInfo.StaticAllocaMap.find(AI);
727 if (SI != FuncInfo.StaticAllocaMap.end())
728 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
731 unsigned InReg = FuncInfo.ValueMap[V];
732 assert(InReg && "Value not in map!");
734 // If this type is not legal, make it so now.
735 if (VT != MVT::Vector) {
736 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
737 // Source must be expanded. This input value is actually coming from the
738 // register pair InReg and InReg+1.
739 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
740 unsigned NumVals = TLI.getNumElements(VT);
741 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
743 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
745 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
746 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
747 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
750 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
751 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
752 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
753 N = MVT::isFloatingPoint(VT)
754 ? DAG.getNode(ISD::FP_ROUND, VT, N)
755 : DAG.getNode(ISD::TRUNCATE, VT, N);
758 // Otherwise, if this is a vector, make it available as a generic vector
760 MVT::ValueType PTyElementVT, PTyLegalElementVT;
761 const VectorType *PTy = cast<VectorType>(VTy);
762 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
765 // Build a VBUILD_VECTOR with the input registers.
766 SmallVector<SDOperand, 8> Ops;
767 if (PTyElementVT == PTyLegalElementVT) {
768 // If the value types are legal, just VBUILD the CopyFromReg nodes.
769 for (unsigned i = 0; i != NE; ++i)
770 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
772 } else if (PTyElementVT < PTyLegalElementVT) {
773 // If the register was promoted, use TRUNCATE or FP_ROUND as appropriate.
774 for (unsigned i = 0; i != NE; ++i) {
775 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
777 if (MVT::isFloatingPoint(PTyElementVT))
778 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
780 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
784 // If the register was expanded, use BUILD_PAIR.
785 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
786 for (unsigned i = 0; i != NE/2; ++i) {
787 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
789 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
791 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
795 Ops.push_back(DAG.getConstant(NE, MVT::i32));
796 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
797 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
799 // Finally, use a VBIT_CONVERT to make this available as the appropriate
801 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
802 DAG.getConstant(PTy->getNumElements(),
804 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
811 void SelectionDAGLowering::visitRet(ReturnInst &I) {
812 if (I.getNumOperands() == 0) {
813 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
816 SmallVector<SDOperand, 8> NewValues;
817 NewValues.push_back(getRoot());
818 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
819 SDOperand RetOp = getValue(I.getOperand(i));
821 // If this is an integer return value, we need to promote it ourselves to
822 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
824 // FIXME: C calling convention requires the return type to be promoted to
825 // at least 32-bit. But this is not necessary for non-C calling conventions.
826 if (MVT::isInteger(RetOp.getValueType()) &&
827 RetOp.getValueType() < MVT::i64) {
828 MVT::ValueType TmpVT;
829 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
830 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
833 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
834 const ParamAttrsList *Attrs = FTy->getParamAttrs();
835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
836 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
837 ExtendKind = ISD::SIGN_EXTEND;
838 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
839 ExtendKind = ISD::ZERO_EXTEND;
840 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
842 NewValues.push_back(RetOp);
843 NewValues.push_back(DAG.getConstant(false, MVT::i32));
845 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
846 &NewValues[0], NewValues.size()));
849 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
850 /// the current basic block, add it to ValueMap now so that we'll get a
852 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
853 // No need to export constants.
854 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
857 if (FuncInfo.isExportedInst(V)) return;
859 unsigned Reg = FuncInfo.InitializeRegForValue(V);
860 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
863 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
864 const BasicBlock *FromBB) {
865 // The operands of the setcc have to be in this block. We don't know
866 // how to export them from some other block.
867 if (Instruction *VI = dyn_cast<Instruction>(V)) {
868 // Can export from current BB.
869 if (VI->getParent() == FromBB)
872 // Is already exported, noop.
873 return FuncInfo.isExportedInst(V);
876 // If this is an argument, we can export it if the BB is the entry block or
877 // if it is already exported.
878 if (isa<Argument>(V)) {
879 if (FromBB == &FromBB->getParent()->getEntryBlock())
882 // Otherwise, can only export this if it is already exported.
883 return FuncInfo.isExportedInst(V);
886 // Otherwise, constants can always be exported.
890 static bool InBlock(const Value *V, const BasicBlock *BB) {
891 if (const Instruction *I = dyn_cast<Instruction>(V))
892 return I->getParent() == BB;
896 /// FindMergedConditions - If Cond is an expression like
897 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
898 MachineBasicBlock *TBB,
899 MachineBasicBlock *FBB,
900 MachineBasicBlock *CurBB,
902 // If this node is not part of the or/and tree, emit it as a branch.
903 Instruction *BOp = dyn_cast<Instruction>(Cond);
905 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
906 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
907 BOp->getParent() != CurBB->getBasicBlock() ||
908 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
909 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
910 const BasicBlock *BB = CurBB->getBasicBlock();
912 // If the leaf of the tree is a comparison, merge the condition into
914 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
915 // The operands of the cmp have to be in this block. We don't know
916 // how to export them from some other block. If this is the first block
917 // of the sequence, no exporting is needed.
919 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
920 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
921 BOp = cast<Instruction>(Cond);
922 ISD::CondCode Condition;
923 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
924 switch (IC->getPredicate()) {
925 default: assert(0 && "Unknown icmp predicate opcode!");
926 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
927 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
928 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
929 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
930 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
931 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
932 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
933 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
934 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
935 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
937 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
938 ISD::CondCode FPC, FOC;
939 switch (FC->getPredicate()) {
940 default: assert(0 && "Unknown fcmp predicate opcode!");
941 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
942 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
943 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
944 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
945 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
946 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
947 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
948 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
949 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
950 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
951 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
952 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
953 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
954 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
955 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
956 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
958 if (FiniteOnlyFPMath())
963 Condition = ISD::SETEQ; // silence warning.
964 assert(0 && "Unknown compare instruction");
967 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
968 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
969 SwitchCases.push_back(CB);
973 // Create a CaseBlock record representing this branch.
974 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
975 NULL, TBB, FBB, CurBB);
976 SwitchCases.push_back(CB);
981 // Create TmpBB after CurBB.
982 MachineFunction::iterator BBI = CurBB;
983 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
984 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
986 if (Opc == Instruction::Or) {
995 // Emit the LHS condition.
996 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
998 // Emit the RHS condition into TmpBB.
999 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1001 assert(Opc == Instruction::And && "Unknown merge op!");
1002 // Codegen X & Y as:
1009 // This requires creation of TmpBB after CurBB.
1011 // Emit the LHS condition.
1012 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1014 // Emit the RHS condition into TmpBB.
1015 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1019 /// If the set of cases should be emitted as a series of branches, return true.
1020 /// If we should emit this as a bunch of and/or'd together conditions, return
1023 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1024 if (Cases.size() != 2) return true;
1026 // If this is two comparisons of the same values or'd or and'd together, they
1027 // will get folded into a single comparison, so don't emit two blocks.
1028 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1029 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1030 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1031 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1038 void SelectionDAGLowering::visitBr(BranchInst &I) {
1039 // Update machine-CFG edges.
1040 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1042 // Figure out which block is immediately after the current one.
1043 MachineBasicBlock *NextBlock = 0;
1044 MachineFunction::iterator BBI = CurMBB;
1045 if (++BBI != CurMBB->getParent()->end())
1048 if (I.isUnconditional()) {
1049 // If this is not a fall-through branch, emit the branch.
1050 if (Succ0MBB != NextBlock)
1051 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1052 DAG.getBasicBlock(Succ0MBB)));
1054 // Update machine-CFG edges.
1055 CurMBB->addSuccessor(Succ0MBB);
1060 // If this condition is one of the special cases we handle, do special stuff
1062 Value *CondVal = I.getCondition();
1063 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1065 // If this is a series of conditions that are or'd or and'd together, emit
1066 // this as a sequence of branches instead of setcc's with and/or operations.
1067 // For example, instead of something like:
1080 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1081 if (BOp->hasOneUse() &&
1082 (BOp->getOpcode() == Instruction::And ||
1083 BOp->getOpcode() == Instruction::Or)) {
1084 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1085 // If the compares in later blocks need to use values not currently
1086 // exported from this block, export them now. This block should always
1087 // be the first entry.
1088 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1090 // Allow some cases to be rejected.
1091 if (ShouldEmitAsBranches(SwitchCases)) {
1092 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1093 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1094 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1097 // Emit the branch for this block.
1098 visitSwitchCase(SwitchCases[0]);
1099 SwitchCases.erase(SwitchCases.begin());
1103 // Okay, we decided not to do this, remove any inserted MBB's and clear
1105 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1106 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1108 SwitchCases.clear();
1112 // Create a CaseBlock record representing this branch.
1113 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1114 NULL, Succ0MBB, Succ1MBB, CurMBB);
1115 // Use visitSwitchCase to actually insert the fast branch sequence for this
1117 visitSwitchCase(CB);
1120 /// visitSwitchCase - Emits the necessary code to represent a single node in
1121 /// the binary search tree resulting from lowering a switch instruction.
1122 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1124 SDOperand CondLHS = getValue(CB.CmpLHS);
1126 // Build the setcc now.
1127 if (CB.CmpMHS == NULL) {
1128 // Fold "(X == true)" to X and "(X == false)" to !X to
1129 // handle common cases produced by branch lowering.
1130 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1132 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1133 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1134 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1136 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1138 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1140 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1141 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1143 SDOperand CmpOp = getValue(CB.CmpMHS);
1144 MVT::ValueType VT = CmpOp.getValueType();
1146 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1147 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1149 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1150 Cond = DAG.getSetCC(MVT::i1, SUB,
1151 DAG.getConstant(High-Low, VT), ISD::SETULE);
1156 // Set NextBlock to be the MBB immediately after the current one, if any.
1157 // This is used to avoid emitting unnecessary branches to the next block.
1158 MachineBasicBlock *NextBlock = 0;
1159 MachineFunction::iterator BBI = CurMBB;
1160 if (++BBI != CurMBB->getParent()->end())
1163 // If the lhs block is the next block, invert the condition so that we can
1164 // fall through to the lhs instead of the rhs block.
1165 if (CB.TrueBB == NextBlock) {
1166 std::swap(CB.TrueBB, CB.FalseBB);
1167 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1168 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1170 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1171 DAG.getBasicBlock(CB.TrueBB));
1172 if (CB.FalseBB == NextBlock)
1173 DAG.setRoot(BrCond);
1175 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1176 DAG.getBasicBlock(CB.FalseBB)));
1177 // Update successor info
1178 CurMBB->addSuccessor(CB.TrueBB);
1179 CurMBB->addSuccessor(CB.FalseBB);
1182 /// visitJumpTable - Emit JumpTable node in the current MBB
1183 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1184 // Emit the code for the jump table
1185 assert(JT.Reg != -1U && "Should lower JT Header first!");
1186 MVT::ValueType PTy = TLI.getPointerTy();
1187 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1188 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1189 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1194 /// visitJumpTableHeader - This function emits necessary code to produce index
1195 /// in the JumpTable from switch case.
1196 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1197 SelectionDAGISel::JumpTableHeader &JTH) {
1198 // Subtract the lowest switch case value from the value being switched on
1199 // and conditional branch to default mbb if the result is greater than the
1200 // difference between smallest and largest cases.
1201 SDOperand SwitchOp = getValue(JTH.SValue);
1202 MVT::ValueType VT = SwitchOp.getValueType();
1203 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1204 DAG.getConstant(JTH.First, VT));
1206 // The SDNode we just created, which holds the value being switched on
1207 // minus the the smallest case value, needs to be copied to a virtual
1208 // register so it can be used as an index into the jump table in a
1209 // subsequent basic block. This value may be smaller or larger than the
1210 // target's pointer type, and therefore require extension or truncating.
1211 if (VT > TLI.getPointerTy())
1212 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1214 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1216 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1217 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1218 JT.Reg = JumpTableReg;
1220 // Emit the range check for the jump table, and branch to the default
1221 // block for the switch statement if the value being switched on exceeds
1222 // the largest case in the switch.
1223 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1224 DAG.getConstant(JTH.Last-JTH.First,VT),
1227 // Set NextBlock to be the MBB immediately after the current one, if any.
1228 // This is used to avoid emitting unnecessary branches to the next block.
1229 MachineBasicBlock *NextBlock = 0;
1230 MachineFunction::iterator BBI = CurMBB;
1231 if (++BBI != CurMBB->getParent()->end())
1234 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1235 DAG.getBasicBlock(JT.Default));
1237 if (JT.MBB == NextBlock)
1238 DAG.setRoot(BrCond);
1240 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1241 DAG.getBasicBlock(JT.MBB)));
1246 /// visitBitTestHeader - This function emits necessary code to produce value
1247 /// suitable for "bit tests"
1248 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1249 // Subtract the minimum value
1250 SDOperand SwitchOp = getValue(B.SValue);
1251 MVT::ValueType VT = SwitchOp.getValueType();
1252 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1253 DAG.getConstant(B.First, VT));
1256 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1257 DAG.getConstant(B.Range, VT),
1261 if (VT > TLI.getShiftAmountTy())
1262 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1264 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1266 // Make desired shift
1267 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1268 DAG.getConstant(1, TLI.getPointerTy()),
1271 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1272 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1275 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1276 DAG.getBasicBlock(B.Default));
1278 // Set NextBlock to be the MBB immediately after the current one, if any.
1279 // This is used to avoid emitting unnecessary branches to the next block.
1280 MachineBasicBlock *NextBlock = 0;
1281 MachineFunction::iterator BBI = CurMBB;
1282 if (++BBI != CurMBB->getParent()->end())
1285 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1286 if (MBB == NextBlock)
1287 DAG.setRoot(BrRange);
1289 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1290 DAG.getBasicBlock(MBB)));
1292 CurMBB->addSuccessor(B.Default);
1293 CurMBB->addSuccessor(MBB);
1298 /// visitBitTestCase - this function produces one "bit test"
1299 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1301 SelectionDAGISel::BitTestCase &B) {
1302 // Emit bit tests and jumps
1303 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1305 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1307 DAG.getConstant(B.Mask,
1308 TLI.getPointerTy()));
1309 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1310 DAG.getConstant(0, TLI.getPointerTy()),
1312 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1313 AndCmp, DAG.getBasicBlock(B.TargetBB));
1315 // Set NextBlock to be the MBB immediately after the current one, if any.
1316 // This is used to avoid emitting unnecessary branches to the next block.
1317 MachineBasicBlock *NextBlock = 0;
1318 MachineFunction::iterator BBI = CurMBB;
1319 if (++BBI != CurMBB->getParent()->end())
1322 if (NextMBB == NextBlock)
1325 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1326 DAG.getBasicBlock(NextMBB)));
1328 CurMBB->addSuccessor(B.TargetBB);
1329 CurMBB->addSuccessor(NextMBB);
1334 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1335 assert(0 && "Should never be visited directly");
1337 void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
1338 // Retrieve successors.
1339 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1340 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1342 if (!AsTerminator) {
1343 // Mark landing pad so that it doesn't get deleted in branch folding.
1344 LandingPad->setIsLandingPad();
1346 LowerCallTo(I, I.getCalledValue()->getType(),
1349 getValue(I.getOperand(0)),
1352 // Update successor info
1353 CurMBB->addSuccessor(Return);
1354 CurMBB->addSuccessor(LandingPad);
1356 // Drop into normal successor.
1357 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1358 DAG.getBasicBlock(Return)));
1362 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1365 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1366 /// small case ranges).
1367 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1368 CaseRecVector& WorkList,
1370 MachineBasicBlock* Default) {
1371 Case& BackCase = *(CR.Range.second-1);
1373 // Size is the number of Cases represented by this range.
1374 unsigned Size = CR.Range.second - CR.Range.first;
1378 // Get the MachineFunction which holds the current MBB. This is used when
1379 // inserting any additional MBBs necessary to represent the switch.
1380 MachineFunction *CurMF = CurMBB->getParent();
1382 // Figure out which block is immediately after the current one.
1383 MachineBasicBlock *NextBlock = 0;
1384 MachineFunction::iterator BBI = CR.CaseBB;
1386 if (++BBI != CurMBB->getParent()->end())
1389 // TODO: If any two of the cases has the same destination, and if one value
1390 // is the same as the other, but has one bit unset that the other has set,
1391 // use bit manipulation to do two compares at once. For example:
1392 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1394 // Rearrange the case blocks so that the last one falls through if possible.
1395 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1396 // The last case block won't fall through into 'NextBlock' if we emit the
1397 // branches in this order. See if rearranging a case value would help.
1398 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1399 if (I->BB == NextBlock) {
1400 std::swap(*I, BackCase);
1406 // Create a CaseBlock record representing a conditional branch to
1407 // the Case's target mbb if the value being switched on SV is equal
1409 MachineBasicBlock *CurBlock = CR.CaseBB;
1410 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1411 MachineBasicBlock *FallThrough;
1413 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1414 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1416 // If the last case doesn't match, go to the default block.
1417 FallThrough = Default;
1420 Value *RHS, *LHS, *MHS;
1422 if (I->High == I->Low) {
1423 // This is just small small case range :) containing exactly 1 case
1425 LHS = SV; RHS = I->High; MHS = NULL;
1428 LHS = I->Low; MHS = SV; RHS = I->High;
1430 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1431 I->BB, FallThrough, CurBlock);
1433 // If emitting the first comparison, just call visitSwitchCase to emit the
1434 // code into the current block. Otherwise, push the CaseBlock onto the
1435 // vector to be later processed by SDISel, and insert the node's MBB
1436 // before the next MBB.
1437 if (CurBlock == CurMBB)
1438 visitSwitchCase(CB);
1440 SwitchCases.push_back(CB);
1442 CurBlock = FallThrough;
1448 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1449 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1450 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1453 /// handleJTSwitchCase - Emit jumptable for current switch case range
1454 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1455 CaseRecVector& WorkList,
1457 MachineBasicBlock* Default) {
1458 Case& FrontCase = *CR.Range.first;
1459 Case& BackCase = *(CR.Range.second-1);
1461 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1462 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1465 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1469 if (!areJTsAllowed(TLI) || TSize <= 3)
1472 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1476 DOUT << "Lowering jump table\n"
1477 << "First entry: " << First << ". Last entry: " << Last << "\n"
1478 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1480 // Get the MachineFunction which holds the current MBB. This is used when
1481 // inserting any additional MBBs necessary to represent the switch.
1482 MachineFunction *CurMF = CurMBB->getParent();
1484 // Figure out which block is immediately after the current one.
1485 MachineBasicBlock *NextBlock = 0;
1486 MachineFunction::iterator BBI = CR.CaseBB;
1488 if (++BBI != CurMBB->getParent()->end())
1491 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1493 // Create a new basic block to hold the code for loading the address
1494 // of the jump table, and jumping to it. Update successor information;
1495 // we will either branch to the default case for the switch, or the jump
1497 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1498 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1499 CR.CaseBB->addSuccessor(Default);
1500 CR.CaseBB->addSuccessor(JumpTableBB);
1502 // Build a vector of destination BBs, corresponding to each target
1503 // of the jump table. If the value of the jump table slot corresponds to
1504 // a case statement, push the case's BB onto the vector, otherwise, push
1506 std::vector<MachineBasicBlock*> DestBBs;
1507 int64_t TEI = First;
1508 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1509 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1510 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1512 if ((Low <= TEI) && (TEI <= High)) {
1513 DestBBs.push_back(I->BB);
1517 DestBBs.push_back(Default);
1521 // Update successor info. Add one edge to each unique successor.
1522 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1523 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1524 E = DestBBs.end(); I != E; ++I) {
1525 if (!SuccsHandled[(*I)->getNumber()]) {
1526 SuccsHandled[(*I)->getNumber()] = true;
1527 JumpTableBB->addSuccessor(*I);
1531 // Create a jump table index for this jump table, or return an existing
1533 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1535 // Set the jump table information so that we can codegen it as a second
1536 // MachineBasicBlock
1537 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1538 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1539 (CR.CaseBB == CurMBB));
1540 if (CR.CaseBB == CurMBB)
1541 visitJumpTableHeader(JT, JTH);
1543 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1548 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1550 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1551 CaseRecVector& WorkList,
1553 MachineBasicBlock* Default) {
1554 // Get the MachineFunction which holds the current MBB. This is used when
1555 // inserting any additional MBBs necessary to represent the switch.
1556 MachineFunction *CurMF = CurMBB->getParent();
1558 // Figure out which block is immediately after the current one.
1559 MachineBasicBlock *NextBlock = 0;
1560 MachineFunction::iterator BBI = CR.CaseBB;
1562 if (++BBI != CurMBB->getParent()->end())
1565 Case& FrontCase = *CR.Range.first;
1566 Case& BackCase = *(CR.Range.second-1);
1567 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1569 // Size is the number of Cases represented by this range.
1570 unsigned Size = CR.Range.second - CR.Range.first;
1572 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1573 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1575 CaseItr Pivot = CR.Range.first + Size/2;
1577 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1578 // (heuristically) allow us to emit JumpTable's later.
1580 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1584 uint64_t LSize = FrontCase.size();
1585 uint64_t RSize = TSize-LSize;
1586 DOUT << "Selecting best pivot: \n"
1587 << "First: " << First << ", Last: " << Last <<"\n"
1588 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1589 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1591 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1592 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1593 assert((RBegin-LEnd>=1) && "Invalid case distance");
1594 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1595 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1596 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1597 // Should always split in some non-trivial place
1599 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1600 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1601 << "Metric: " << Metric << "\n";
1602 if (FMetric < Metric) {
1605 DOUT << "Current metric set to: " << FMetric << "\n";
1611 if (areJTsAllowed(TLI)) {
1612 // If our case is dense we *really* should handle it earlier!
1613 assert((FMetric > 0) && "Should handle dense range earlier!");
1615 Pivot = CR.Range.first + Size/2;
1618 CaseRange LHSR(CR.Range.first, Pivot);
1619 CaseRange RHSR(Pivot, CR.Range.second);
1620 Constant *C = Pivot->Low;
1621 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1623 // We know that we branch to the LHS if the Value being switched on is
1624 // less than the Pivot value, C. We use this to optimize our binary
1625 // tree a bit, by recognizing that if SV is greater than or equal to the
1626 // LHS's Case Value, and that Case Value is exactly one less than the
1627 // Pivot's Value, then we can branch directly to the LHS's Target,
1628 // rather than creating a leaf node for it.
1629 if ((LHSR.second - LHSR.first) == 1 &&
1630 LHSR.first->High == CR.GE &&
1631 cast<ConstantInt>(C)->getSExtValue() ==
1632 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1633 TrueBB = LHSR.first->BB;
1635 TrueBB = new MachineBasicBlock(LLVMBB);
1636 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1637 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1640 // Similar to the optimization above, if the Value being switched on is
1641 // known to be less than the Constant CR.LT, and the current Case Value
1642 // is CR.LT - 1, then we can branch directly to the target block for
1643 // the current Case Value, rather than emitting a RHS leaf node for it.
1644 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1645 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1646 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1647 FalseBB = RHSR.first->BB;
1649 FalseBB = new MachineBasicBlock(LLVMBB);
1650 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1651 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1654 // Create a CaseBlock record representing a conditional branch to
1655 // the LHS node if the value being switched on SV is less than C.
1656 // Otherwise, branch to LHS.
1657 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1658 TrueBB, FalseBB, CR.CaseBB);
1660 if (CR.CaseBB == CurMBB)
1661 visitSwitchCase(CB);
1663 SwitchCases.push_back(CB);
1668 /// handleBitTestsSwitchCase - if current case range has few destination and
1669 /// range span less, than machine word bitwidth, encode case range into series
1670 /// of masks and emit bit tests with these masks.
1671 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1672 CaseRecVector& WorkList,
1674 MachineBasicBlock* Default){
1675 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1677 Case& FrontCase = *CR.Range.first;
1678 Case& BackCase = *(CR.Range.second-1);
1680 // Get the MachineFunction which holds the current MBB. This is used when
1681 // inserting any additional MBBs necessary to represent the switch.
1682 MachineFunction *CurMF = CurMBB->getParent();
1684 unsigned numCmps = 0;
1685 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1687 // Single case counts one, case range - two.
1688 if (I->Low == I->High)
1694 // Count unique destinations
1695 SmallSet<MachineBasicBlock*, 4> Dests;
1696 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1697 Dests.insert(I->BB);
1698 if (Dests.size() > 3)
1699 // Don't bother the code below, if there are too much unique destinations
1702 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1703 << "Total number of comparisons: " << numCmps << "\n";
1705 // Compute span of values.
1706 Constant* minValue = FrontCase.Low;
1707 Constant* maxValue = BackCase.High;
1708 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1709 cast<ConstantInt>(minValue)->getSExtValue();
1710 DOUT << "Compare range: " << range << "\n"
1711 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1712 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1714 if (range>=IntPtrBits ||
1715 (!(Dests.size() == 1 && numCmps >= 3) &&
1716 !(Dests.size() == 2 && numCmps >= 5) &&
1717 !(Dests.size() >= 3 && numCmps >= 6)))
1720 DOUT << "Emitting bit tests\n";
1721 int64_t lowBound = 0;
1723 // Optimize the case where all the case values fit in a
1724 // word without having to subtract minValue. In this case,
1725 // we can optimize away the subtraction.
1726 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1727 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1728 range = cast<ConstantInt>(maxValue)->getSExtValue();
1730 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1733 CaseBitsVector CasesBits;
1734 unsigned i, count = 0;
1736 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1737 MachineBasicBlock* Dest = I->BB;
1738 for (i = 0; i < count; ++i)
1739 if (Dest == CasesBits[i].BB)
1743 assert((count < 3) && "Too much destinations to test!");
1744 CasesBits.push_back(CaseBits(0, Dest, 0));
1748 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1749 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1751 for (uint64_t j = lo; j <= hi; j++) {
1752 CasesBits[i].Mask |= 1ULL << j;
1753 CasesBits[i].Bits++;
1757 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1759 SelectionDAGISel::BitTestInfo BTC;
1761 // Figure out which block is immediately after the current one.
1762 MachineFunction::iterator BBI = CR.CaseBB;
1765 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1768 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1769 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1770 << ", BB: " << CasesBits[i].BB << "\n";
1772 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1773 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1774 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1779 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
1780 -1U, (CR.CaseBB == CurMBB),
1781 CR.CaseBB, Default, BTC);
1783 if (CR.CaseBB == CurMBB)
1784 visitBitTestHeader(BTB);
1786 BitTestCases.push_back(BTB);
1792 // Clusterify - Transform simple list of Cases into list of CaseRange's
1793 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1794 const SwitchInst& SI) {
1795 unsigned numCmps = 0;
1797 // Start with "simple" cases
1798 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1799 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1800 Cases.push_back(Case(SI.getSuccessorValue(i),
1801 SI.getSuccessorValue(i),
1804 sort(Cases.begin(), Cases.end(), CaseCmp());
1806 // Merge case into clusters
1807 if (Cases.size()>=2)
1808 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1809 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1810 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1811 MachineBasicBlock* nextBB = J->BB;
1812 MachineBasicBlock* currentBB = I->BB;
1814 // If the two neighboring cases go to the same destination, merge them
1815 // into a single case.
1816 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1824 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1825 if (I->Low != I->High)
1826 // A range counts double, since it requires two compares.
1833 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1834 // Figure out which block is immediately after the current one.
1835 MachineBasicBlock *NextBlock = 0;
1836 MachineFunction::iterator BBI = CurMBB;
1838 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1840 // If there is only the default destination, branch to it if it is not the
1841 // next basic block. Otherwise, just fall through.
1842 if (SI.getNumOperands() == 2) {
1843 // Update machine-CFG edges.
1845 // If this is not a fall-through branch, emit the branch.
1846 if (Default != NextBlock)
1847 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1848 DAG.getBasicBlock(Default)));
1850 CurMBB->addSuccessor(Default);
1854 // If there are any non-default case statements, create a vector of Cases
1855 // representing each one, and sort the vector so that we can efficiently
1856 // create a binary search tree from them.
1858 unsigned numCmps = Clusterify(Cases, SI);
1859 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1860 << ". Total compares: " << numCmps << "\n";
1862 // Get the Value to be switched on and default basic blocks, which will be
1863 // inserted into CaseBlock records, representing basic blocks in the binary
1865 Value *SV = SI.getOperand(0);
1867 // Push the initial CaseRec onto the worklist
1868 CaseRecVector WorkList;
1869 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1871 while (!WorkList.empty()) {
1872 // Grab a record representing a case range to process off the worklist
1873 CaseRec CR = WorkList.back();
1874 WorkList.pop_back();
1876 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1879 // If the range has few cases (two or less) emit a series of specific
1881 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1884 // If the switch has more than 5 blocks, and at least 40% dense, and the
1885 // target supports indirect branches, then emit a jump table rather than
1886 // lowering the switch to a binary tree of conditional branches.
1887 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1890 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1891 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1892 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1897 void SelectionDAGLowering::visitSub(User &I) {
1898 // -0.0 - X --> fneg
1899 const Type *Ty = I.getType();
1900 if (isa<VectorType>(Ty)) {
1901 visitVectorBinary(I, ISD::VSUB);
1902 } else if (Ty->isFloatingPoint()) {
1903 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1904 if (CFP->isExactlyValue(-0.0)) {
1905 SDOperand Op2 = getValue(I.getOperand(1));
1906 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1909 visitScalarBinary(I, ISD::FSUB);
1911 visitScalarBinary(I, ISD::SUB);
1914 void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
1915 SDOperand Op1 = getValue(I.getOperand(0));
1916 SDOperand Op2 = getValue(I.getOperand(1));
1918 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1922 SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1923 assert(isa<VectorType>(I.getType()));
1924 const VectorType *Ty = cast<VectorType>(I.getType());
1925 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
1927 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1928 getValue(I.getOperand(0)),
1929 getValue(I.getOperand(1)),
1930 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1934 void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1935 unsigned VectorOp) {
1936 if (isa<VectorType>(I.getType()))
1937 visitVectorBinary(I, VectorOp);
1939 visitScalarBinary(I, ScalarOp);
1942 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1943 SDOperand Op1 = getValue(I.getOperand(0));
1944 SDOperand Op2 = getValue(I.getOperand(1));
1946 if (TLI.getShiftAmountTy() < Op2.getValueType())
1947 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1948 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1949 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1951 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1954 void SelectionDAGLowering::visitICmp(User &I) {
1955 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1956 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1957 predicate = IC->getPredicate();
1958 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1959 predicate = ICmpInst::Predicate(IC->getPredicate());
1960 SDOperand Op1 = getValue(I.getOperand(0));
1961 SDOperand Op2 = getValue(I.getOperand(1));
1962 ISD::CondCode Opcode;
1963 switch (predicate) {
1964 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1965 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1966 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1967 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1968 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1969 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1970 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1971 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1972 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1973 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1975 assert(!"Invalid ICmp predicate value");
1976 Opcode = ISD::SETEQ;
1979 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1982 void SelectionDAGLowering::visitFCmp(User &I) {
1983 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1984 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1985 predicate = FC->getPredicate();
1986 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1987 predicate = FCmpInst::Predicate(FC->getPredicate());
1988 SDOperand Op1 = getValue(I.getOperand(0));
1989 SDOperand Op2 = getValue(I.getOperand(1));
1990 ISD::CondCode Condition, FOC, FPC;
1991 switch (predicate) {
1992 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1993 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1994 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1995 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1996 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1997 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1998 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1999 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2000 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2001 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2002 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2003 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2004 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2005 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2006 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2007 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2009 assert(!"Invalid FCmp predicate value");
2010 FOC = FPC = ISD::SETFALSE;
2013 if (FiniteOnlyFPMath())
2017 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2020 void SelectionDAGLowering::visitSelect(User &I) {
2021 SDOperand Cond = getValue(I.getOperand(0));
2022 SDOperand TrueVal = getValue(I.getOperand(1));
2023 SDOperand FalseVal = getValue(I.getOperand(2));
2024 if (!isa<VectorType>(I.getType())) {
2025 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2026 TrueVal, FalseVal));
2028 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2029 *(TrueVal.Val->op_end()-2),
2030 *(TrueVal.Val->op_end()-1)));
2035 void SelectionDAGLowering::visitTrunc(User &I) {
2036 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2037 SDOperand N = getValue(I.getOperand(0));
2038 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2039 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2042 void SelectionDAGLowering::visitZExt(User &I) {
2043 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2044 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2045 SDOperand N = getValue(I.getOperand(0));
2046 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2047 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2050 void SelectionDAGLowering::visitSExt(User &I) {
2051 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2052 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2053 SDOperand N = getValue(I.getOperand(0));
2054 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2055 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2058 void SelectionDAGLowering::visitFPTrunc(User &I) {
2059 // FPTrunc is never a no-op cast, no need to check
2060 SDOperand N = getValue(I.getOperand(0));
2061 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2062 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2065 void SelectionDAGLowering::visitFPExt(User &I){
2066 // FPTrunc is never a no-op cast, no need to check
2067 SDOperand N = getValue(I.getOperand(0));
2068 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2069 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2072 void SelectionDAGLowering::visitFPToUI(User &I) {
2073 // FPToUI is never a no-op cast, no need to check
2074 SDOperand N = getValue(I.getOperand(0));
2075 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2076 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2079 void SelectionDAGLowering::visitFPToSI(User &I) {
2080 // FPToSI is never a no-op cast, no need to check
2081 SDOperand N = getValue(I.getOperand(0));
2082 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2083 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2086 void SelectionDAGLowering::visitUIToFP(User &I) {
2087 // UIToFP is never a no-op cast, no need to check
2088 SDOperand N = getValue(I.getOperand(0));
2089 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2090 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2093 void SelectionDAGLowering::visitSIToFP(User &I){
2094 // UIToFP is never a no-op cast, no need to check
2095 SDOperand N = getValue(I.getOperand(0));
2096 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2097 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2100 void SelectionDAGLowering::visitPtrToInt(User &I) {
2101 // What to do depends on the size of the integer and the size of the pointer.
2102 // We can either truncate, zero extend, or no-op, accordingly.
2103 SDOperand N = getValue(I.getOperand(0));
2104 MVT::ValueType SrcVT = N.getValueType();
2105 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2107 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2108 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2110 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2111 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2112 setValue(&I, Result);
2115 void SelectionDAGLowering::visitIntToPtr(User &I) {
2116 // What to do depends on the size of the integer and the size of the pointer.
2117 // We can either truncate, zero extend, or no-op, accordingly.
2118 SDOperand N = getValue(I.getOperand(0));
2119 MVT::ValueType SrcVT = N.getValueType();
2120 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2121 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2122 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2124 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2125 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2128 void SelectionDAGLowering::visitBitCast(User &I) {
2129 SDOperand N = getValue(I.getOperand(0));
2130 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2131 if (DestVT == MVT::Vector) {
2132 // This is a cast to a vector from something else.
2133 // Get information about the output vector.
2134 const VectorType *DestTy = cast<VectorType>(I.getType());
2135 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2136 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2137 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2138 DAG.getValueType(EltVT)));
2141 MVT::ValueType SrcVT = N.getValueType();
2142 if (SrcVT == MVT::Vector) {
2143 // This is a cast from a vctor to something else.
2144 // Get information about the input vector.
2145 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
2149 // BitCast assures us that source and destination are the same size so this
2150 // is either a BIT_CONVERT or a no-op.
2151 if (DestVT != N.getValueType())
2152 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2154 setValue(&I, N); // noop cast.
2157 void SelectionDAGLowering::visitInsertElement(User &I) {
2158 SDOperand InVec = getValue(I.getOperand(0));
2159 SDOperand InVal = getValue(I.getOperand(1));
2160 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2161 getValue(I.getOperand(2)));
2163 SDOperand Num = *(InVec.Val->op_end()-2);
2164 SDOperand Typ = *(InVec.Val->op_end()-1);
2165 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2166 InVec, InVal, InIdx, Num, Typ));
2169 void SelectionDAGLowering::visitExtractElement(User &I) {
2170 SDOperand InVec = getValue(I.getOperand(0));
2171 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2172 getValue(I.getOperand(1)));
2173 SDOperand Typ = *(InVec.Val->op_end()-1);
2174 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2175 TLI.getValueType(I.getType()), InVec, InIdx));
2178 void SelectionDAGLowering::visitShuffleVector(User &I) {
2179 SDOperand V1 = getValue(I.getOperand(0));
2180 SDOperand V2 = getValue(I.getOperand(1));
2181 SDOperand Mask = getValue(I.getOperand(2));
2183 SDOperand Num = *(V1.Val->op_end()-2);
2184 SDOperand Typ = *(V2.Val->op_end()-1);
2185 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2186 V1, V2, Mask, Num, Typ));
2190 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2191 SDOperand N = getValue(I.getOperand(0));
2192 const Type *Ty = I.getOperand(0)->getType();
2194 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2197 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2198 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2201 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2202 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2203 getIntPtrConstant(Offset));
2205 Ty = StTy->getElementType(Field);
2207 Ty = cast<SequentialType>(Ty)->getElementType();
2209 // If this is a constant subscript, handle it quickly.
2210 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2211 if (CI->getZExtValue() == 0) continue;
2213 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2214 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2218 // N = N + Idx * ElementSize;
2219 uint64_t ElementSize = TD->getTypeSize(Ty);
2220 SDOperand IdxN = getValue(Idx);
2222 // If the index is smaller or larger than intptr_t, truncate or extend
2224 if (IdxN.getValueType() < N.getValueType()) {
2225 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2226 } else if (IdxN.getValueType() > N.getValueType())
2227 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2229 // If this is a multiply by a power of two, turn it into a shl
2230 // immediately. This is a very common case.
2231 if (isPowerOf2_64(ElementSize)) {
2232 unsigned Amt = Log2_64(ElementSize);
2233 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2234 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2235 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2239 SDOperand Scale = getIntPtrConstant(ElementSize);
2240 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2241 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2247 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2248 // If this is a fixed sized alloca in the entry block of the function,
2249 // allocate it statically on the stack.
2250 if (FuncInfo.StaticAllocaMap.count(&I))
2251 return; // getValue will auto-populate this.
2253 const Type *Ty = I.getAllocatedType();
2254 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
2256 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2259 SDOperand AllocSize = getValue(I.getArraySize());
2260 MVT::ValueType IntPtr = TLI.getPointerTy();
2261 if (IntPtr < AllocSize.getValueType())
2262 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2263 else if (IntPtr > AllocSize.getValueType())
2264 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2266 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2267 getIntPtrConstant(TySize));
2269 // Handle alignment. If the requested alignment is less than or equal to the
2270 // stack alignment, ignore it and round the size of the allocation up to the
2271 // stack alignment size. If the size is greater than the stack alignment, we
2272 // note this in the DYNAMIC_STACKALLOC node.
2273 unsigned StackAlign =
2274 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2275 if (Align <= StackAlign) {
2277 // Add SA-1 to the size.
2278 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2279 getIntPtrConstant(StackAlign-1));
2280 // Mask out the low bits for alignment purposes.
2281 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2282 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2285 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
2286 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2288 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2290 DAG.setRoot(DSA.getValue(1));
2292 // Inform the Frame Information that we have just allocated a variable-sized
2294 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2297 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2298 SDOperand Ptr = getValue(I.getOperand(0));
2304 // Do not serialize non-volatile loads against each other.
2305 Root = DAG.getRoot();
2308 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2309 Root, I.isVolatile(), I.getAlignment()));
2312 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2313 const Value *SV, SDOperand Root,
2315 unsigned Alignment) {
2317 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
2318 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
2319 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2320 DAG.getSrcValue(SV));
2322 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2323 isVolatile, Alignment);
2327 DAG.setRoot(L.getValue(1));
2329 PendingLoads.push_back(L.getValue(1));
2335 void SelectionDAGLowering::visitStore(StoreInst &I) {
2336 Value *SrcV = I.getOperand(0);
2337 SDOperand Src = getValue(SrcV);
2338 SDOperand Ptr = getValue(I.getOperand(1));
2339 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2340 I.isVolatile(), I.getAlignment()));
2343 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2344 /// access memory and has no other side effects at all.
2345 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2346 #define GET_NO_MEMORY_INTRINSICS
2347 #include "llvm/Intrinsics.gen"
2348 #undef GET_NO_MEMORY_INTRINSICS
2352 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2353 // have any side-effects or if it only reads memory.
2354 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2355 #define GET_SIDE_EFFECT_INFO
2356 #include "llvm/Intrinsics.gen"
2357 #undef GET_SIDE_EFFECT_INFO
2361 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2363 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2364 unsigned Intrinsic) {
2365 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
2366 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
2368 // Build the operand list.
2369 SmallVector<SDOperand, 8> Ops;
2370 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2372 // We don't need to serialize loads against other loads.
2373 Ops.push_back(DAG.getRoot());
2375 Ops.push_back(getRoot());
2379 // Add the intrinsic ID as an integer operand.
2380 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2382 // Add all operands of the call to the operand list.
2383 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2384 SDOperand Op = getValue(I.getOperand(i));
2386 // If this is a vector type, force it to the right vector type.
2387 if (Op.getValueType() == MVT::Vector) {
2388 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
2389 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2391 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2392 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2393 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2396 assert(TLI.isTypeLegal(Op.getValueType()) &&
2397 "Intrinsic uses a non-legal type?");
2401 std::vector<MVT::ValueType> VTs;
2402 if (I.getType() != Type::VoidTy) {
2403 MVT::ValueType VT = TLI.getValueType(I.getType());
2404 if (VT == MVT::Vector) {
2405 const VectorType *DestTy = cast<VectorType>(I.getType());
2406 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2408 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2409 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2412 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2416 VTs.push_back(MVT::Other);
2418 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2423 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2424 &Ops[0], Ops.size());
2425 else if (I.getType() != Type::VoidTy)
2426 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2427 &Ops[0], Ops.size());
2429 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2430 &Ops[0], Ops.size());
2433 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2435 PendingLoads.push_back(Chain);
2439 if (I.getType() != Type::VoidTy) {
2440 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2441 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2442 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2443 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2444 DAG.getValueType(EVT));
2446 setValue(&I, Result);
2450 /// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2451 /// (possibly constant folded), return it. Otherwise return NULL.
2452 static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2453 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2455 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2456 if (CE->getOpcode() == Instruction::BitCast)
2457 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2458 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2459 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2460 if (!CE->getOperand(i)->isNullValue())
2462 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2468 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2469 /// we want to emit this as a call to a named external function, return the name
2470 /// otherwise lower it and return null.
2472 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2473 switch (Intrinsic) {
2475 // By default, turn this into a target intrinsic node.
2476 visitTargetIntrinsic(I, Intrinsic);
2478 case Intrinsic::vastart: visitVAStart(I); return 0;
2479 case Intrinsic::vaend: visitVAEnd(I); return 0;
2480 case Intrinsic::vacopy: visitVACopy(I); return 0;
2481 case Intrinsic::returnaddress:
2482 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2483 getValue(I.getOperand(1))));
2485 case Intrinsic::frameaddress:
2486 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2487 getValue(I.getOperand(1))));
2489 case Intrinsic::setjmp:
2490 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2492 case Intrinsic::longjmp:
2493 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2495 case Intrinsic::memcpy_i32:
2496 case Intrinsic::memcpy_i64:
2497 visitMemIntrinsic(I, ISD::MEMCPY);
2499 case Intrinsic::memset_i32:
2500 case Intrinsic::memset_i64:
2501 visitMemIntrinsic(I, ISD::MEMSET);
2503 case Intrinsic::memmove_i32:
2504 case Intrinsic::memmove_i64:
2505 visitMemIntrinsic(I, ISD::MEMMOVE);
2508 case Intrinsic::dbg_stoppoint: {
2509 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2510 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2511 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2515 Ops[1] = getValue(SPI.getLineValue());
2516 Ops[2] = getValue(SPI.getColumnValue());
2518 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2519 assert(DD && "Not a debug information descriptor");
2520 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2522 Ops[3] = DAG.getString(CompileUnit->getFileName());
2523 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2525 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2530 case Intrinsic::dbg_region_start: {
2531 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2532 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2533 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2534 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2535 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2536 DAG.getConstant(LabelID, MVT::i32)));
2541 case Intrinsic::dbg_region_end: {
2542 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2543 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2544 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2545 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2546 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2547 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2552 case Intrinsic::dbg_func_start: {
2553 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2554 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2555 if (MMI && FSI.getSubprogram() &&
2556 MMI->Verify(FSI.getSubprogram())) {
2557 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2558 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2559 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2564 case Intrinsic::dbg_declare: {
2565 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2566 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2567 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2568 SDOperand AddressOp = getValue(DI.getAddress());
2569 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2570 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2576 case Intrinsic::eh_exception: {
2577 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2580 // Add a label to mark the beginning of the landing pad. Deletion of the
2581 // landing pad can thus be detected via the MachineModuleInfo.
2582 unsigned LabelID = MMI->addLandingPad(CurMBB);
2583 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2584 DAG.getConstant(LabelID, MVT::i32)));
2586 // Mark exception register as live in.
2587 unsigned Reg = TLI.getExceptionAddressRegister();
2588 if (Reg) CurMBB->addLiveIn(Reg);
2590 // Insert the EXCEPTIONADDR instruction.
2591 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2593 Ops[0] = DAG.getRoot();
2594 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2596 DAG.setRoot(Op.getValue(1));
2598 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2603 case Intrinsic::eh_selector:
2604 case Intrinsic::eh_filter:{
2605 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2608 // Inform the MachineModuleInfo of the personality for this landing pad.
2609 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2610 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2611 isa<Function>(CE->getOperand(0)) &&
2612 "Personality should be a function");
2613 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
2615 // Gather all the type infos for this landing pad and pass them along to
2616 // MachineModuleInfo.
2617 std::vector<GlobalVariable *> TyInfo;
2618 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2619 Constant *C = cast<Constant>(I.getOperand(i));
2620 GlobalVariable *GV = ExtractGlobalVariable(C);
2621 assert (GV || isa<ConstantPointerNull>(C) &&
2622 "TypeInfo must be a global variable or NULL");
2623 TyInfo.push_back(GV);
2625 if (Intrinsic == Intrinsic::eh_filter)
2626 MMI->addFilterTypeInfo(CurMBB, TyInfo);
2628 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2630 // Mark exception selector register as live in.
2631 unsigned Reg = TLI.getExceptionSelectorRegister();
2632 if (Reg) CurMBB->addLiveIn(Reg);
2634 // Insert the EHSELECTION instruction.
2635 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2637 Ops[0] = getValue(I.getOperand(1));
2639 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2641 DAG.setRoot(Op.getValue(1));
2643 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2649 case Intrinsic::eh_typeid_for: {
2650 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2653 // Find the type id for the given typeinfo.
2654 Constant *C = cast<Constant>(I.getOperand(1));
2655 GlobalVariable *GV = ExtractGlobalVariable(C);
2656 assert (GV || isa<ConstantPointerNull>(C) &&
2657 "TypeInfo must be a global variable or NULL");
2659 unsigned TypeID = MMI->getTypeIDFor(GV);
2660 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2662 setValue(&I, DAG.getConstant(0, MVT::i32));
2668 case Intrinsic::sqrt_f32:
2669 case Intrinsic::sqrt_f64:
2670 setValue(&I, DAG.getNode(ISD::FSQRT,
2671 getValue(I.getOperand(1)).getValueType(),
2672 getValue(I.getOperand(1))));
2674 case Intrinsic::powi_f32:
2675 case Intrinsic::powi_f64:
2676 setValue(&I, DAG.getNode(ISD::FPOWI,
2677 getValue(I.getOperand(1)).getValueType(),
2678 getValue(I.getOperand(1)),
2679 getValue(I.getOperand(2))));
2681 case Intrinsic::pcmarker: {
2682 SDOperand Tmp = getValue(I.getOperand(1));
2683 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2686 case Intrinsic::readcyclecounter: {
2687 SDOperand Op = getRoot();
2688 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2689 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2692 DAG.setRoot(Tmp.getValue(1));
2695 case Intrinsic::part_select: {
2696 // Currently not implemented: just abort
2697 assert(0 && "part_select intrinsic not implemented");
2700 case Intrinsic::part_set: {
2701 // Currently not implemented: just abort
2702 assert(0 && "part_set intrinsic not implemented");
2705 case Intrinsic::bswap:
2706 setValue(&I, DAG.getNode(ISD::BSWAP,
2707 getValue(I.getOperand(1)).getValueType(),
2708 getValue(I.getOperand(1))));
2710 case Intrinsic::cttz: {
2711 SDOperand Arg = getValue(I.getOperand(1));
2712 MVT::ValueType Ty = Arg.getValueType();
2713 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2715 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2716 else if (Ty > MVT::i32)
2717 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2718 setValue(&I, result);
2721 case Intrinsic::ctlz: {
2722 SDOperand Arg = getValue(I.getOperand(1));
2723 MVT::ValueType Ty = Arg.getValueType();
2724 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2726 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2727 else if (Ty > MVT::i32)
2728 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2729 setValue(&I, result);
2732 case Intrinsic::ctpop: {
2733 SDOperand Arg = getValue(I.getOperand(1));
2734 MVT::ValueType Ty = Arg.getValueType();
2735 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2737 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2738 else if (Ty > MVT::i32)
2739 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2740 setValue(&I, result);
2743 case Intrinsic::stacksave: {
2744 SDOperand Op = getRoot();
2745 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2746 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2748 DAG.setRoot(Tmp.getValue(1));
2751 case Intrinsic::stackrestore: {
2752 SDOperand Tmp = getValue(I.getOperand(1));
2753 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2756 case Intrinsic::prefetch:
2757 // FIXME: Currently discarding prefetches.
2763 void SelectionDAGLowering::LowerCallTo(Instruction &I,
2764 const Type *CalledValueTy,
2765 unsigned CallingConv,
2767 SDOperand Callee, unsigned OpIdx,
2768 MachineBasicBlock *LandingPad) {
2769 const PointerType *PT = cast<PointerType>(CalledValueTy);
2770 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2771 const ParamAttrsList *Attrs = FTy->getParamAttrs();
2772 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2773 unsigned BeginLabel = 0, EndLabel = 0;
2775 TargetLowering::ArgListTy Args;
2776 TargetLowering::ArgListEntry Entry;
2777 Args.reserve(I.getNumOperands());
2778 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2779 Value *Arg = I.getOperand(i);
2780 SDOperand ArgNode = getValue(Arg);
2781 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2783 unsigned attrInd = i - OpIdx + 1;
2784 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2785 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2786 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2787 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
2788 Args.push_back(Entry);
2791 if (ExceptionHandling) {
2792 // Insert a label before the invoke call to mark the try range. This can be
2793 // used to detect deletion of the invoke via the MachineModuleInfo.
2794 BeginLabel = MMI->NextLabelID();
2795 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2796 DAG.getConstant(BeginLabel, MVT::i32)));
2799 std::pair<SDOperand,SDOperand> Result =
2800 TLI.LowerCallTo(getRoot(), I.getType(),
2801 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
2802 FTy->isVarArg(), CallingConv, IsTailCall,
2804 if (I.getType() != Type::VoidTy)
2805 setValue(&I, Result.first);
2806 DAG.setRoot(Result.second);
2808 if (ExceptionHandling) {
2809 // Insert a label at the end of the invoke call to mark the try range. This
2810 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2811 EndLabel = MMI->NextLabelID();
2812 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2813 DAG.getConstant(EndLabel, MVT::i32)));
2815 // Inform MachineModuleInfo of range.
2816 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2821 void SelectionDAGLowering::visitCall(CallInst &I) {
2822 const char *RenameFn = 0;
2823 if (Function *F = I.getCalledFunction()) {
2824 if (F->isDeclaration())
2825 if (unsigned IID = F->getIntrinsicID()) {
2826 RenameFn = visitIntrinsicCall(I, IID);
2829 } else { // Not an LLVM intrinsic.
2830 const std::string &Name = F->getName();
2831 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2832 if (I.getNumOperands() == 3 && // Basic sanity checks.
2833 I.getOperand(1)->getType()->isFloatingPoint() &&
2834 I.getType() == I.getOperand(1)->getType() &&
2835 I.getType() == I.getOperand(2)->getType()) {
2836 SDOperand LHS = getValue(I.getOperand(1));
2837 SDOperand RHS = getValue(I.getOperand(2));
2838 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2842 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2843 if (I.getNumOperands() == 2 && // Basic sanity checks.
2844 I.getOperand(1)->getType()->isFloatingPoint() &&
2845 I.getType() == I.getOperand(1)->getType()) {
2846 SDOperand Tmp = getValue(I.getOperand(1));
2847 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2850 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2851 if (I.getNumOperands() == 2 && // Basic sanity checks.
2852 I.getOperand(1)->getType()->isFloatingPoint() &&
2853 I.getType() == I.getOperand(1)->getType()) {
2854 SDOperand Tmp = getValue(I.getOperand(1));
2855 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2858 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2859 if (I.getNumOperands() == 2 && // Basic sanity checks.
2860 I.getOperand(1)->getType()->isFloatingPoint() &&
2861 I.getType() == I.getOperand(1)->getType()) {
2862 SDOperand Tmp = getValue(I.getOperand(1));
2863 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2868 } else if (isa<InlineAsm>(I.getOperand(0))) {
2875 Callee = getValue(I.getOperand(0));
2877 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2879 LowerCallTo(I, I.getCalledValue()->getType(),
2887 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2888 SDOperand &Chain, SDOperand &Flag)const{
2889 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2890 Chain = Val.getValue(1);
2891 Flag = Val.getValue(2);
2893 // If the result was expanded, copy from the top part.
2894 if (Regs.size() > 1) {
2895 assert(Regs.size() == 2 &&
2896 "Cannot expand to more than 2 elts yet!");
2897 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2898 Chain = Hi.getValue(1);
2899 Flag = Hi.getValue(2);
2900 if (DAG.getTargetLoweringInfo().isLittleEndian())
2901 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2903 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2906 // Otherwise, if the return value was promoted or extended, truncate it to the
2907 // appropriate type.
2908 if (RegVT == ValueVT)
2911 if (MVT::isVector(RegVT)) {
2912 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2913 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2914 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2916 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2919 if (MVT::isInteger(RegVT)) {
2920 if (ValueVT < RegVT)
2921 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2923 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2926 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2927 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2930 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2931 /// specified value into the registers specified by this object. This uses
2932 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2933 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2934 SDOperand &Chain, SDOperand &Flag,
2935 MVT::ValueType PtrVT) const {
2936 if (Regs.size() == 1) {
2937 // If there is a single register and the types differ, this must be
2939 if (RegVT != ValueVT) {
2940 if (MVT::isVector(RegVT)) {
2941 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2942 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2943 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
2944 if (RegVT < ValueVT)
2945 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2947 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2948 } else if (MVT::isFloatingPoint(RegVT) &&
2949 MVT::isFloatingPoint(Val.getValueType())) {
2950 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2951 } else if (MVT::getSizeInBits(RegVT) ==
2952 MVT::getSizeInBits(Val.getValueType())) {
2953 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2955 assert(0 && "Unknown mismatch!");
2958 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2959 Flag = Chain.getValue(1);
2961 std::vector<unsigned> R(Regs);
2962 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2963 std::reverse(R.begin(), R.end());
2965 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2966 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2967 DAG.getConstant(i, PtrVT));
2968 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2969 Flag = Chain.getValue(1);
2974 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2975 /// operand list. This adds the code marker and includes the number of
2976 /// values added into it.
2977 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2978 std::vector<SDOperand> &Ops) const {
2979 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2980 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
2981 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2982 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2985 /// isAllocatableRegister - If the specified register is safe to allocate,
2986 /// i.e. it isn't a stack pointer or some other special register, return the
2987 /// register class for the register. Otherwise, return null.
2988 static const TargetRegisterClass *
2989 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2990 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2991 MVT::ValueType FoundVT = MVT::Other;
2992 const TargetRegisterClass *FoundRC = 0;
2993 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2994 E = MRI->regclass_end(); RCI != E; ++RCI) {
2995 MVT::ValueType ThisVT = MVT::Other;
2997 const TargetRegisterClass *RC = *RCI;
2998 // If none of the the value types for this register class are valid, we
2999 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3000 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3002 if (TLI.isTypeLegal(*I)) {
3003 // If we have already found this register in a different register class,
3004 // choose the one with the largest VT specified. For example, on
3005 // PowerPC, we favor f64 register classes over f32.
3006 if (FoundVT == MVT::Other ||
3007 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3014 if (ThisVT == MVT::Other) continue;
3016 // NOTE: This isn't ideal. In particular, this might allocate the
3017 // frame pointer in functions that need it (due to them not being taken
3018 // out of allocation, because a variable sized allocation hasn't been seen
3019 // yet). This is a slight code pessimization, but should still work.
3020 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3021 E = RC->allocation_order_end(MF); I != E; ++I)
3023 // We found a matching register class. Keep looking at others in case
3024 // we find one with larger registers that this physreg is also in.
3035 /// AsmOperandInfo - This contains information for each constraint that we are
3037 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3038 /// ConstraintCode - This contains the actual string for the code, like "m".
3039 std::string ConstraintCode;
3041 /// ConstraintType - Information about the constraint code, e.g. Register,
3042 /// RegisterClass, Memory, Other, Unknown.
3043 TargetLowering::ConstraintType ConstraintType;
3045 /// CallOperand/CallOperandval - If this is the result output operand or a
3046 /// clobber, this is null, otherwise it is the incoming operand to the
3047 /// CallInst. This gets modified as the asm is processed.
3048 SDOperand CallOperand;
3049 Value *CallOperandVal;
3051 /// ConstraintVT - The ValueType for the operand value.
3052 MVT::ValueType ConstraintVT;
3054 /// AssignedRegs - If this is a register or register class operand, this
3055 /// contains the set of register corresponding to the operand.
3056 RegsForValue AssignedRegs;
3058 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3059 : InlineAsm::ConstraintInfo(info),
3060 ConstraintType(TargetLowering::C_Unknown),
3061 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3064 void ComputeConstraintToUse(const TargetLowering &TLI);
3066 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3067 /// busy in OutputRegs/InputRegs.
3068 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3069 std::set<unsigned> &OutputRegs,
3070 std::set<unsigned> &InputRegs) const {
3072 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3074 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3077 } // end anon namespace.
3079 /// getConstraintGenerality - Return an integer indicating how general CT is.
3080 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3082 default: assert(0 && "Unknown constraint type!");
3083 case TargetLowering::C_Other:
3084 case TargetLowering::C_Unknown:
3086 case TargetLowering::C_Register:
3088 case TargetLowering::C_RegisterClass:
3090 case TargetLowering::C_Memory:
3095 void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3096 assert(!Codes.empty() && "Must have at least one constraint");
3098 std::string *Current = &Codes[0];
3099 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3100 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3101 ConstraintCode = *Current;
3102 ConstraintType = CurType;
3106 unsigned CurGenerality = getConstraintGenerality(CurType);
3108 // If we have multiple constraints, try to pick the most general one ahead
3109 // of time. This isn't a wonderful solution, but handles common cases.
3110 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3111 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3112 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3113 if (ThisGenerality > CurGenerality) {
3114 // This constraint letter is more general than the previous one,
3117 Current = &Codes[j];
3118 CurGenerality = ThisGenerality;
3122 ConstraintCode = *Current;
3123 ConstraintType = CurType;
3127 void SelectionDAGLowering::
3128 GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
3129 std::set<unsigned> &OutputRegs,
3130 std::set<unsigned> &InputRegs) {
3131 // Compute whether this value requires an input register, an output register,
3133 bool isOutReg = false;
3134 bool isInReg = false;
3135 switch (OpInfo.Type) {
3136 case InlineAsm::isOutput:
3139 // If this is an early-clobber output, or if there is an input
3140 // constraint that matches this, we need to reserve the input register
3141 // so no other inputs allocate to it.
3142 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3144 case InlineAsm::isInput:
3148 case InlineAsm::isClobber:
3155 MachineFunction &MF = DAG.getMachineFunction();
3156 std::vector<unsigned> Regs;
3158 // If this is a constraint for a single physreg, or a constraint for a
3159 // register class, find it.
3160 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3161 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3162 OpInfo.ConstraintVT);
3164 unsigned NumRegs = 1;
3165 if (OpInfo.ConstraintVT != MVT::Other)
3166 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT);
3167 MVT::ValueType RegVT;
3168 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3171 // If this is a constraint for a specific physical register, like {r17},
3173 if (PhysReg.first) {
3174 if (OpInfo.ConstraintVT == MVT::Other)
3175 ValueVT = *PhysReg.second->vt_begin();
3177 // Get the actual register value type. This is important, because the user
3178 // may have asked for (e.g.) the AX register in i32 type. We need to
3179 // remember that AX is actually i16 to get the right extension.
3180 RegVT = *PhysReg.second->vt_begin();
3182 // This is a explicit reference to a physical register.
3183 Regs.push_back(PhysReg.first);
3185 // If this is an expanded reference, add the rest of the regs to Regs.
3187 TargetRegisterClass::iterator I = PhysReg.second->begin();
3188 TargetRegisterClass::iterator E = PhysReg.second->end();
3189 for (; *I != PhysReg.first; ++I)
3190 assert(I != E && "Didn't find reg!");
3192 // Already added the first reg.
3194 for (; NumRegs; --NumRegs, ++I) {
3195 assert(I != E && "Ran out of registers to allocate!");
3199 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3200 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3204 // Otherwise, if this was a reference to an LLVM register class, create vregs
3205 // for this reference.
3206 std::vector<unsigned> RegClassRegs;
3207 if (PhysReg.second) {
3208 // If this is an early clobber or tied register, our regalloc doesn't know
3209 // how to maintain the constraint. If it isn't, go ahead and create vreg
3210 // and let the regalloc do the right thing.
3211 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3212 // If there is some other early clobber and this is an input register,
3213 // then we are forced to pre-allocate the input reg so it doesn't
3214 // conflict with the earlyclobber.
3215 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3216 RegVT = *PhysReg.second->vt_begin();
3218 if (OpInfo.ConstraintVT == MVT::Other)
3221 // Create the appropriate number of virtual registers.
3222 SSARegMap *RegMap = MF.getSSARegMap();
3223 for (; NumRegs; --NumRegs)
3224 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3226 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3227 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3231 // Otherwise, we can't allocate it. Let the code below figure out how to
3232 // maintain these constraints.
3233 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3236 // This is a reference to a register class that doesn't directly correspond
3237 // to an LLVM register class. Allocate NumRegs consecutive, available,
3238 // registers from the class.
3239 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3240 OpInfo.ConstraintVT);
3243 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3244 unsigned NumAllocated = 0;
3245 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3246 unsigned Reg = RegClassRegs[i];
3247 // See if this register is available.
3248 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3249 (isInReg && InputRegs.count(Reg))) { // Already used.
3250 // Make sure we find consecutive registers.
3255 // Check to see if this register is allocatable (i.e. don't give out the
3257 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3259 // Make sure we find consecutive registers.
3264 // Okay, this register is good, we can use it.
3267 // If we allocated enough consecutive registers, succeed.
3268 if (NumAllocated == NumRegs) {
3269 unsigned RegStart = (i-NumAllocated)+1;
3270 unsigned RegEnd = i+1;
3271 // Mark all of the allocated registers used.
3272 for (unsigned i = RegStart; i != RegEnd; ++i)
3273 Regs.push_back(RegClassRegs[i]);
3275 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3276 OpInfo.ConstraintVT);
3277 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3282 // Otherwise, we couldn't allocate enough registers for this.
3287 /// visitInlineAsm - Handle a call to an InlineAsm object.
3289 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3290 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3292 /// ConstraintOperands - Information about all of the constraints.
3293 std::vector<AsmOperandInfo> ConstraintOperands;
3295 SDOperand Chain = getRoot();
3298 std::set<unsigned> OutputRegs, InputRegs;
3300 // Do a prepass over the constraints, canonicalizing them, and building up the
3301 // ConstraintOperands list.
3302 std::vector<InlineAsm::ConstraintInfo>
3303 ConstraintInfos = IA->ParseConstraints();
3305 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3306 // constraint. If so, we can't let the register allocator allocate any input
3307 // registers, because it will not know to avoid the earlyclobbered output reg.
3308 bool SawEarlyClobber = false;
3310 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
3311 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3312 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3313 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3315 MVT::ValueType OpVT = MVT::Other;
3317 // Compute the value type for each operand.
3318 switch (OpInfo.Type) {
3319 case InlineAsm::isOutput:
3320 if (!OpInfo.isIndirect) {
3321 // The return value of the call is this value. As such, there is no
3322 // corresponding argument.
3323 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3324 OpVT = TLI.getValueType(I.getType());
3326 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3329 case InlineAsm::isInput:
3330 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3332 case InlineAsm::isClobber:
3337 // If this is an input or an indirect output, process the call argument.
3338 if (OpInfo.CallOperandVal) {
3339 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3340 const Type *OpTy = OpInfo.CallOperandVal->getType();
3341 // If this is an indirect operand, the operand is a pointer to the
3343 if (OpInfo.isIndirect)
3344 OpTy = cast<PointerType>(OpTy)->getElementType();
3346 // If OpTy is not a first-class value, it may be a struct/union that we
3347 // can tile with integers.
3348 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3349 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3357 OpTy = IntegerType::get(BitSize);
3362 OpVT = TLI.getValueType(OpTy, true);
3365 OpInfo.ConstraintVT = OpVT;
3367 // Compute the constraint code and ConstraintType to use.
3368 OpInfo.ComputeConstraintToUse(TLI);
3370 // Keep track of whether we see an earlyclobber.
3371 SawEarlyClobber |= OpInfo.isEarlyClobber;
3373 // If this is a memory input, and if the operand is not indirect, do what we
3374 // need to to provide an address for the memory input.
3375 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3376 !OpInfo.isIndirect) {
3377 assert(OpInfo.Type == InlineAsm::isInput &&
3378 "Can only indirectify direct input operands!");
3380 // Memory operands really want the address of the value. If we don't have
3381 // an indirect input, put it in the constpool if we can, otherwise spill
3382 // it to a stack slot.
3384 // If the operand is a float, integer, or vector constant, spill to a
3385 // constant pool entry to get its address.
3386 Value *OpVal = OpInfo.CallOperandVal;
3387 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3388 isa<ConstantVector>(OpVal)) {
3389 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3390 TLI.getPointerTy());
3392 // Otherwise, create a stack slot and emit a store to it before the
3394 const Type *Ty = OpVal->getType();
3395 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3396 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3397 MachineFunction &MF = DAG.getMachineFunction();
3398 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3399 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3400 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3401 OpInfo.CallOperand = StackSlot;
3404 // There is no longer a Value* corresponding to this operand.
3405 OpInfo.CallOperandVal = 0;
3406 // It is now an indirect operand.
3407 OpInfo.isIndirect = true;
3410 // If this constraint is for a specific register, allocate it before
3412 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3413 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3415 ConstraintInfos.clear();
3418 // Second pass - Loop over all of the operands, assigning virtual or physregs
3419 // to registerclass operands.
3420 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3421 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3423 // C_Register operands have already been allocated, Other/Memory don't need
3425 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3426 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3429 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3430 std::vector<SDOperand> AsmNodeOperands;
3431 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3432 AsmNodeOperands.push_back(
3433 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3436 // Loop over all of the inputs, copying the operand values into the
3437 // appropriate registers and processing the output regs.
3438 RegsForValue RetValRegs;
3440 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3441 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3443 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3444 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3446 switch (OpInfo.Type) {
3447 case InlineAsm::isOutput: {
3448 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3449 OpInfo.ConstraintType != TargetLowering::C_Register) {
3450 // Memory output, or 'other' output (e.g. 'X' constraint).
3451 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3453 // Add information to the INLINEASM node to know about this output.
3454 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3455 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3456 TLI.getPointerTy()));
3457 AsmNodeOperands.push_back(OpInfo.CallOperand);
3461 // Otherwise, this is a register or register class output.
3463 // Copy the output from the appropriate register. Find a register that
3465 if (OpInfo.AssignedRegs.Regs.empty()) {
3466 cerr << "Couldn't allocate output reg for contraint '"
3467 << OpInfo.ConstraintCode << "'!\n";
3471 if (!OpInfo.isIndirect) {
3472 // This is the result value of the call.
3473 assert(RetValRegs.Regs.empty() &&
3474 "Cannot have multiple output constraints yet!");
3475 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3476 RetValRegs = OpInfo.AssignedRegs;
3478 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3479 OpInfo.CallOperandVal));
3482 // Add information to the INLINEASM node to know that this register is
3484 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3488 case InlineAsm::isInput: {
3489 SDOperand InOperandVal = OpInfo.CallOperand;
3491 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3492 // If this is required to match an output register we have already set,
3493 // just use its register.
3494 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3496 // Scan until we find the definition we already emitted of this operand.
3497 // When we find it, create a RegsForValue operand.
3498 unsigned CurOp = 2; // The first operand.
3499 for (; OperandNo; --OperandNo) {
3500 // Advance to the next operand.
3502 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3503 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3504 (NumOps & 7) == 4 /*MEM*/) &&
3505 "Skipped past definitions?");
3506 CurOp += (NumOps>>3)+1;
3510 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3511 if ((NumOps & 7) == 2 /*REGDEF*/) {
3512 // Add NumOps>>3 registers to MatchedRegs.
3513 RegsForValue MatchedRegs;
3514 MatchedRegs.ValueVT = InOperandVal.getValueType();
3515 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3516 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3518 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3519 MatchedRegs.Regs.push_back(Reg);
3522 // Use the produced MatchedRegs object to
3523 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3524 TLI.getPointerTy());
3525 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3528 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3529 assert(0 && "matching constraints for memory operands unimp");
3533 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
3534 assert(!OpInfo.isIndirect &&
3535 "Don't know how to handle indirect other inputs yet!");
3537 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3538 OpInfo.ConstraintCode[0],
3540 if (!InOperandVal.Val) {
3541 cerr << "Invalid operand for inline asm constraint '"
3542 << OpInfo.ConstraintCode << "'!\n";
3546 // Add information to the INLINEASM node to know about this input.
3547 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3548 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3549 TLI.getPointerTy()));
3550 AsmNodeOperands.push_back(InOperandVal);
3552 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
3553 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
3554 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3555 "Memory operands expect pointer values");
3557 // Add information to the INLINEASM node to know about this input.
3558 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3559 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3560 TLI.getPointerTy()));
3561 AsmNodeOperands.push_back(InOperandVal);
3565 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3566 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3567 "Unknown constraint type!");
3568 assert(!OpInfo.isIndirect &&
3569 "Don't know how to handle indirect register inputs yet!");
3571 // Copy the input into the appropriate registers.
3572 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3573 "Couldn't allocate input reg!");
3575 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3576 TLI.getPointerTy());
3578 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3582 case InlineAsm::isClobber: {
3583 // Add the clobbered value to the operand list, so that the register
3584 // allocator is aware that the physreg got clobbered.
3585 if (!OpInfo.AssignedRegs.Regs.empty())
3586 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3593 // Finish up input operands.
3594 AsmNodeOperands[0] = Chain;
3595 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3597 Chain = DAG.getNode(ISD::INLINEASM,
3598 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3599 &AsmNodeOperands[0], AsmNodeOperands.size());
3600 Flag = Chain.getValue(1);
3602 // If this asm returns a register value, copy the result from that register
3603 // and set it as the value of the call.
3604 if (!RetValRegs.Regs.empty()) {
3605 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3607 // If the result of the inline asm is a vector, it may have the wrong
3608 // width/num elts. Make sure to convert it to the right type with
3610 if (Val.getValueType() == MVT::Vector) {
3611 const VectorType *VTy = cast<VectorType>(I.getType());
3612 unsigned DesiredNumElts = VTy->getNumElements();
3613 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3615 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3616 DAG.getConstant(DesiredNumElts, MVT::i32),
3617 DAG.getValueType(DesiredEltVT));
3623 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3625 // Process indirect outputs, first output all of the flagged copies out of
3627 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3628 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3629 Value *Ptr = IndirectStoresToEmit[i].second;
3630 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3631 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
3634 // Emit the non-flagged stores from the physregs.
3635 SmallVector<SDOperand, 8> OutChains;
3636 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
3637 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
3638 getValue(StoresToEmit[i].second),
3639 StoresToEmit[i].second, 0));
3640 if (!OutChains.empty())
3641 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3642 &OutChains[0], OutChains.size());
3647 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3648 SDOperand Src = getValue(I.getOperand(0));
3650 MVT::ValueType IntPtr = TLI.getPointerTy();
3652 if (IntPtr < Src.getValueType())
3653 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3654 else if (IntPtr > Src.getValueType())
3655 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
3657 // Scale the source by the type size.
3658 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
3659 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3660 Src, getIntPtrConstant(ElementSize));
3662 TargetLowering::ArgListTy Args;
3663 TargetLowering::ArgListEntry Entry;
3665 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3666 Args.push_back(Entry);
3668 std::pair<SDOperand,SDOperand> Result =
3669 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
3670 DAG.getExternalSymbol("malloc", IntPtr),
3672 setValue(&I, Result.first); // Pointers always fit in registers
3673 DAG.setRoot(Result.second);
3676 void SelectionDAGLowering::visitFree(FreeInst &I) {
3677 TargetLowering::ArgListTy Args;
3678 TargetLowering::ArgListEntry Entry;
3679 Entry.Node = getValue(I.getOperand(0));
3680 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3681 Args.push_back(Entry);
3682 MVT::ValueType IntPtr = TLI.getPointerTy();
3683 std::pair<SDOperand,SDOperand> Result =
3684 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3685 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3686 DAG.setRoot(Result.second);
3689 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
3690 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3691 // instructions are special in various ways, which require special support to
3692 // insert. The specified MachineInstr is created but not inserted into any
3693 // basic blocks, and the scheduler passes ownership of it to this method.
3694 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3695 MachineBasicBlock *MBB) {
3696 cerr << "If a target marks an instruction with "
3697 << "'usesCustomDAGSchedInserter', it must implement "
3698 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3703 void SelectionDAGLowering::visitVAStart(CallInst &I) {
3704 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3705 getValue(I.getOperand(1)),
3706 DAG.getSrcValue(I.getOperand(1))));
3709 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3710 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3711 getValue(I.getOperand(0)),
3712 DAG.getSrcValue(I.getOperand(0)));
3714 DAG.setRoot(V.getValue(1));
3717 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3718 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3719 getValue(I.getOperand(1)),
3720 DAG.getSrcValue(I.getOperand(1))));
3723 void SelectionDAGLowering::visitVACopy(CallInst &I) {
3724 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3725 getValue(I.getOperand(1)),
3726 getValue(I.getOperand(2)),
3727 DAG.getSrcValue(I.getOperand(1)),
3728 DAG.getSrcValue(I.getOperand(2))));
3731 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3732 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3733 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3734 unsigned &i, SelectionDAG &DAG,
3735 TargetLowering &TLI) {
3736 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3737 return SDOperand(Arg, i++);
3739 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3740 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3742 return DAG.getNode(ISD::BIT_CONVERT, VT,
3743 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3744 } else if (NumVals == 2) {
3745 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3746 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3747 if (!TLI.isLittleEndian())
3749 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3751 // Value scalarized into many values. Unimp for now.
3752 assert(0 && "Cannot expand i64 -> i16 yet!");
3757 /// TargetLowering::LowerArguments - This is the default LowerArguments
3758 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3759 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3760 /// integrated into SDISel.
3761 std::vector<SDOperand>
3762 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3763 const FunctionType *FTy = F.getFunctionType();
3764 const ParamAttrsList *Attrs = FTy->getParamAttrs();
3765 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3766 std::vector<SDOperand> Ops;
3767 Ops.push_back(DAG.getRoot());
3768 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3769 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3771 // Add one result value for each formal argument.
3772 std::vector<MVT::ValueType> RetVals;
3774 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3776 MVT::ValueType VT = getValueType(I->getType());
3777 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3778 unsigned OriginalAlignment =
3779 getTargetData()->getABITypeAlignment(I->getType());
3781 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3782 // that is zero extended!
3783 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
3784 Flags &= ~(ISD::ParamFlags::SExt);
3785 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
3786 Flags |= ISD::ParamFlags::SExt;
3787 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
3788 Flags |= ISD::ParamFlags::InReg;
3789 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
3790 Flags |= ISD::ParamFlags::StructReturn;
3791 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
3793 switch (getTypeAction(VT)) {
3794 default: assert(0 && "Unknown type action!");
3796 RetVals.push_back(VT);
3797 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3800 RetVals.push_back(getTypeToTransformTo(VT));
3801 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3804 if (VT != MVT::Vector) {
3805 // If this is a large integer, it needs to be broken up into small
3806 // integers. Figure out what the destination type is and how many small
3807 // integers it turns into.
3808 MVT::ValueType NVT = getTypeToExpandTo(VT);
3809 unsigned NumVals = getNumElements(VT);
3810 for (unsigned i = 0; i != NumVals; ++i) {
3811 RetVals.push_back(NVT);
3812 // if it isn't first piece, alignment must be 1
3814 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3815 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3816 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3819 // Otherwise, this is a vector type. We only support legal vectors
3821 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3822 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
3824 // Figure out if there is a Packed type corresponding to this Vector
3825 // type. If so, convert to the vector type.
3826 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3827 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3828 RetVals.push_back(TVT);
3829 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3831 assert(0 && "Don't support illegal by-val vector arguments yet!");
3838 RetVals.push_back(MVT::Other);
3841 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3842 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3843 &Ops[0], Ops.size()).Val;
3845 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
3847 // Set up the return result vector.
3851 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3853 MVT::ValueType VT = getValueType(I->getType());
3855 switch (getTypeAction(VT)) {
3856 default: assert(0 && "Unknown type action!");
3858 Ops.push_back(SDOperand(Result, i++));
3861 SDOperand Op(Result, i++);
3862 if (MVT::isInteger(VT)) {
3863 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
3864 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3865 DAG.getValueType(VT));
3866 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
3867 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3868 DAG.getValueType(VT));
3869 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3871 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3872 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3878 if (VT != MVT::Vector) {
3879 // If this is a large integer or a floating point node that needs to be
3880 // expanded, it needs to be reassembled from small integers. Figure out
3881 // what the source elt type is and how many small integers it is.
3882 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
3884 // Otherwise, this is a vector type. We only support legal vectors
3886 const VectorType *PTy = cast<VectorType>(I->getType());
3887 unsigned NumElems = PTy->getNumElements();
3888 const Type *EltTy = PTy->getElementType();
3890 // Figure out if there is a Packed type corresponding to this Vector
3891 // type. If so, convert to the vector type.
3892 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3893 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3894 SDOperand N = SDOperand(Result, i++);
3895 // Handle copies from generic vectors to registers.
3896 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3897 DAG.getConstant(NumElems, MVT::i32),
3898 DAG.getValueType(getValueType(EltTy)));
3901 assert(0 && "Don't support illegal by-val vector arguments yet!");
3912 /// ExpandScalarCallArgs - Recursively expand call argument node by
3913 /// bit_converting it or extract a pair of elements from the larger node.
3914 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3916 SmallVector<SDOperand, 32> &Ops,
3918 TargetLowering &TLI,
3919 bool isFirst = true) {
3921 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3922 // if it isn't first piece, alignment must be 1
3924 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3925 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3927 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3931 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3932 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3934 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3935 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
3936 } else if (NumVals == 2) {
3937 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3938 DAG.getConstant(0, TLI.getPointerTy()));
3939 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3940 DAG.getConstant(1, TLI.getPointerTy()));
3941 if (!TLI.isLittleEndian())
3943 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3944 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
3946 // Value scalarized into many values. Unimp for now.
3947 assert(0 && "Cannot expand i64 -> i16 yet!");
3951 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3952 /// implementation, which just inserts an ISD::CALL node, which is later custom
3953 /// lowered by the target to something concrete. FIXME: When all targets are
3954 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3955 std::pair<SDOperand, SDOperand>
3956 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3957 bool RetTyIsSigned, bool isVarArg,
3958 unsigned CallingConv, bool isTailCall,
3960 ArgListTy &Args, SelectionDAG &DAG) {
3961 SmallVector<SDOperand, 32> Ops;
3962 Ops.push_back(Chain); // Op#0 - Chain
3963 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3964 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3965 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3966 Ops.push_back(Callee);
3968 // Handle all of the outgoing arguments.
3969 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3970 MVT::ValueType VT = getValueType(Args[i].Ty);
3971 SDOperand Op = Args[i].Node;
3972 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3973 unsigned OriginalAlignment =
3974 getTargetData()->getABITypeAlignment(Args[i].Ty);
3977 Flags |= ISD::ParamFlags::SExt;
3979 Flags |= ISD::ParamFlags::ZExt;
3980 if (Args[i].isInReg)
3981 Flags |= ISD::ParamFlags::InReg;
3983 Flags |= ISD::ParamFlags::StructReturn;
3984 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
3986 switch (getTypeAction(VT)) {
3987 default: assert(0 && "Unknown type action!");
3990 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3993 if (MVT::isInteger(VT)) {
3996 ExtOp = ISD::SIGN_EXTEND;
3997 else if (Args[i].isZExt)
3998 ExtOp = ISD::ZERO_EXTEND;
4000 ExtOp = ISD::ANY_EXTEND;
4001 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
4003 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
4004 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
4007 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4010 if (VT != MVT::Vector) {
4011 // If this is a large integer, it needs to be broken down into small
4012 // integers. Figure out what the source elt type is and how many small
4014 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
4016 // Otherwise, this is a vector type. We only support legal vectors
4018 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
4019 unsigned NumElems = PTy->getNumElements();
4020 const Type *EltTy = PTy->getElementType();
4022 // Figure out if there is a Packed type corresponding to this Vector
4023 // type. If so, convert to the vector type.
4024 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4025 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4026 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
4027 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
4029 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4031 assert(0 && "Don't support illegal by-val vector call args yet!");
4039 // Figure out the result value types.
4040 SmallVector<MVT::ValueType, 4> RetTys;
4042 if (RetTy != Type::VoidTy) {
4043 MVT::ValueType VT = getValueType(RetTy);
4044 switch (getTypeAction(VT)) {
4045 default: assert(0 && "Unknown type action!");
4047 RetTys.push_back(VT);
4050 RetTys.push_back(getTypeToTransformTo(VT));
4053 if (VT != MVT::Vector) {
4054 // If this is a large integer, it needs to be reassembled from small
4055 // integers. Figure out what the source elt type is and how many small
4057 MVT::ValueType NVT = getTypeToExpandTo(VT);
4058 unsigned NumVals = getNumElements(VT);
4059 for (unsigned i = 0; i != NumVals; ++i)
4060 RetTys.push_back(NVT);
4062 // Otherwise, this is a vector type. We only support legal vectors
4064 const VectorType *PTy = cast<VectorType>(RetTy);
4065 unsigned NumElems = PTy->getNumElements();
4066 const Type *EltTy = PTy->getElementType();
4068 // Figure out if there is a Packed type corresponding to this Vector
4069 // type. If so, convert to the vector type.
4070 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4071 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4072 RetTys.push_back(TVT);
4074 assert(0 && "Don't support illegal by-val vector call results yet!");
4081 RetTys.push_back(MVT::Other); // Always has a chain.
4083 // Finally, create the CALL node.
4084 SDOperand Res = DAG.getNode(ISD::CALL,
4085 DAG.getVTList(&RetTys[0], RetTys.size()),
4086 &Ops[0], Ops.size());
4088 // This returns a pair of operands. The first element is the
4089 // return value for the function (if RetTy is not VoidTy). The second
4090 // element is the outgoing token chain.
4092 if (RetTys.size() != 1) {
4093 MVT::ValueType VT = getValueType(RetTy);
4094 if (RetTys.size() == 2) {
4097 // If this value was promoted, truncate it down.
4098 if (ResVal.getValueType() != VT) {
4099 if (VT == MVT::Vector) {
4100 // Insert a VBIT_CONVERT to convert from the packed result type to the
4101 // MVT::Vector type.
4102 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4103 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
4105 // Figure out if there is a Packed type corresponding to this Vector
4106 // type. If so, convert to the vector type.
4107 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
4108 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4109 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
4110 // "N x PTyElementVT" MVT::Vector type.
4111 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
4112 DAG.getConstant(NumElems, MVT::i32),
4113 DAG.getValueType(getValueType(EltTy)));
4117 } else if (MVT::isInteger(VT)) {
4118 unsigned AssertOp = ISD::AssertSext;
4120 AssertOp = ISD::AssertZext;
4121 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4122 DAG.getValueType(VT));
4123 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4125 assert(MVT::isFloatingPoint(VT));
4126 if (getTypeAction(VT) == Expand)
4127 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4129 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
4132 } else if (RetTys.size() == 3) {
4133 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4134 Res.getValue(0), Res.getValue(1));
4137 assert(0 && "Case not handled yet!");
4141 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4144 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4145 assert(0 && "LowerOperation not implemented for this target!");
4150 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4151 SelectionDAG &DAG) {
4152 assert(0 && "CustomPromoteOperation not implemented for this target!");
4157 /// getMemsetValue - Vectorized representation of the memset value
4159 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4160 SelectionDAG &DAG) {
4161 MVT::ValueType CurVT = VT;
4162 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4163 uint64_t Val = C->getValue() & 255;
4165 while (CurVT != MVT::i8) {
4166 Val = (Val << Shift) | Val;
4168 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4170 return DAG.getConstant(Val, VT);
4172 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4174 while (CurVT != MVT::i8) {
4176 DAG.getNode(ISD::OR, VT,
4177 DAG.getNode(ISD::SHL, VT, Value,
4178 DAG.getConstant(Shift, MVT::i8)), Value);
4180 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4187 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4188 /// used when a memcpy is turned into a memset when the source is a constant
4190 static SDOperand getMemsetStringVal(MVT::ValueType VT,
4191 SelectionDAG &DAG, TargetLowering &TLI,
4192 std::string &Str, unsigned Offset) {
4194 unsigned MSB = MVT::getSizeInBits(VT) / 8;
4195 if (TLI.isLittleEndian())
4196 Offset = Offset + MSB - 1;
4197 for (unsigned i = 0; i != MSB; ++i) {
4198 Val = (Val << 8) | (unsigned char)Str[Offset];
4199 Offset += TLI.isLittleEndian() ? -1 : 1;
4201 return DAG.getConstant(Val, VT);
4204 /// getMemBasePlusOffset - Returns base and offset node for the
4205 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4206 SelectionDAG &DAG, TargetLowering &TLI) {
4207 MVT::ValueType VT = Base.getValueType();
4208 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4211 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4212 /// to replace the memset / memcpy is below the threshold. It also returns the
4213 /// types of the sequence of memory ops to perform memset / memcpy.
4214 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4215 unsigned Limit, uint64_t Size,
4216 unsigned Align, TargetLowering &TLI) {
4219 if (TLI.allowsUnalignedMemoryAccesses()) {
4222 switch (Align & 7) {
4238 MVT::ValueType LVT = MVT::i64;
4239 while (!TLI.isTypeLegal(LVT))
4240 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4241 assert(MVT::isInteger(LVT));
4246 unsigned NumMemOps = 0;
4248 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4249 while (VTSize > Size) {
4250 VT = (MVT::ValueType)((unsigned)VT - 1);
4253 assert(MVT::isInteger(VT));
4255 if (++NumMemOps > Limit)
4257 MemOps.push_back(VT);
4264 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4265 SDOperand Op1 = getValue(I.getOperand(1));
4266 SDOperand Op2 = getValue(I.getOperand(2));
4267 SDOperand Op3 = getValue(I.getOperand(3));
4268 SDOperand Op4 = getValue(I.getOperand(4));
4269 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4270 if (Align == 0) Align = 1;
4272 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4273 std::vector<MVT::ValueType> MemOps;
4275 // Expand memset / memcpy to a series of load / store ops
4276 // if the size operand falls below a certain threshold.
4277 SmallVector<SDOperand, 8> OutChains;
4279 default: break; // Do nothing for now.
4281 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4282 Size->getValue(), Align, TLI)) {
4283 unsigned NumMemOps = MemOps.size();
4284 unsigned Offset = 0;
4285 for (unsigned i = 0; i < NumMemOps; i++) {
4286 MVT::ValueType VT = MemOps[i];
4287 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4288 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4289 SDOperand Store = DAG.getStore(getRoot(), Value,
4290 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4291 I.getOperand(1), Offset);
4292 OutChains.push_back(Store);
4299 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4300 Size->getValue(), Align, TLI)) {
4301 unsigned NumMemOps = MemOps.size();
4302 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4303 GlobalAddressSDNode *G = NULL;
4305 bool CopyFromStr = false;
4307 if (Op2.getOpcode() == ISD::GlobalAddress)
4308 G = cast<GlobalAddressSDNode>(Op2);
4309 else if (Op2.getOpcode() == ISD::ADD &&
4310 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4311 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4312 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4313 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4316 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4317 if (GV && GV->isConstant()) {
4318 Str = GV->getStringValue(false);
4326 for (unsigned i = 0; i < NumMemOps; i++) {
4327 MVT::ValueType VT = MemOps[i];
4328 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4329 SDOperand Value, Chain, Store;
4332 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4335 DAG.getStore(Chain, Value,
4336 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4337 I.getOperand(1), DstOff);
4339 Value = DAG.getLoad(VT, getRoot(),
4340 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4341 I.getOperand(2), SrcOff);
4342 Chain = Value.getValue(1);
4344 DAG.getStore(Chain, Value,
4345 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4346 I.getOperand(1), DstOff);
4348 OutChains.push_back(Store);
4357 if (!OutChains.empty()) {
4358 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4359 &OutChains[0], OutChains.size()));
4364 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
4367 //===----------------------------------------------------------------------===//
4368 // SelectionDAGISel code
4369 //===----------------------------------------------------------------------===//
4371 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4372 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4375 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4376 AU.addRequired<AliasAnalysis>();
4377 AU.setPreservesAll();
4382 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4383 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4384 RegMap = MF.getSSARegMap();
4385 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4387 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4389 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4390 SelectBasicBlock(I, MF, FuncInfo);
4392 // Add function live-ins to entry block live-in set.
4393 BasicBlock *EntryBB = &Fn.getEntryBlock();
4394 BB = FuncInfo.MBBMap[EntryBB];
4395 if (!MF.livein_empty())
4396 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4397 E = MF.livein_end(); I != E; ++I)
4398 BB->addLiveIn(I->first);
4403 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4405 SDOperand Op = getValue(V);
4406 assert((Op.getOpcode() != ISD::CopyFromReg ||
4407 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4408 "Copy from a reg to the same reg!");
4410 // If this type is not legal, we must make sure to not create an invalid
4412 MVT::ValueType SrcVT = Op.getValueType();
4413 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
4414 if (SrcVT == DestVT) {
4415 return DAG.getCopyToReg(getRoot(), Reg, Op);
4416 } else if (SrcVT == MVT::Vector) {
4417 // Handle copies from generic vectors to registers.
4418 MVT::ValueType PTyElementVT, PTyLegalElementVT;
4419 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
4420 PTyElementVT, PTyLegalElementVT);
4422 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4423 // MVT::Vector type.
4424 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4425 DAG.getConstant(NE, MVT::i32),
4426 DAG.getValueType(PTyElementVT));
4428 // Loop over all of the elements of the resultant vector,
4429 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4430 // copying them into output registers.
4431 SmallVector<SDOperand, 8> OutChains;
4432 SDOperand Root = getRoot();
4433 for (unsigned i = 0; i != NE; ++i) {
4434 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
4435 Op, DAG.getConstant(i, TLI.getPointerTy()));
4436 if (PTyElementVT == PTyLegalElementVT) {
4437 // Elements are legal.
4438 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4439 } else if (PTyLegalElementVT > PTyElementVT) {
4440 // Elements are promoted.
4441 if (MVT::isFloatingPoint(PTyLegalElementVT))
4442 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4444 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4445 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4447 // Elements are expanded.
4448 // The src value is expanded into multiple registers.
4449 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4450 Elt, DAG.getConstant(0, TLI.getPointerTy()));
4451 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4452 Elt, DAG.getConstant(1, TLI.getPointerTy()));
4453 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4454 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4457 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4458 &OutChains[0], OutChains.size());
4459 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
4460 // The src value is promoted to the register.
4461 if (MVT::isFloatingPoint(SrcVT))
4462 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4464 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
4465 return DAG.getCopyToReg(getRoot(), Reg, Op);
4467 DestVT = TLI.getTypeToExpandTo(SrcVT);
4468 unsigned NumVals = TLI.getNumElements(SrcVT);
4470 return DAG.getCopyToReg(getRoot(), Reg,
4471 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4472 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
4473 // The src value is expanded into multiple registers.
4474 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4475 Op, DAG.getConstant(0, TLI.getPointerTy()));
4476 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4477 Op, DAG.getConstant(1, TLI.getPointerTy()));
4478 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
4479 return DAG.getCopyToReg(Op, Reg+1, Hi);
4483 void SelectionDAGISel::
4484 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4485 std::vector<SDOperand> &UnorderedChains) {
4486 // If this is the entry block, emit arguments.
4487 Function &F = *LLVMBB->getParent();
4488 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4489 SDOperand OldRoot = SDL.DAG.getRoot();
4490 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4493 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4495 if (!AI->use_empty()) {
4496 SDL.setValue(AI, Args[a]);
4498 // If this argument is live outside of the entry block, insert a copy from
4499 // whereever we got it to the vreg that other BB's will reference it as.
4500 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4501 if (VMI != FuncInfo.ValueMap.end()) {
4502 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
4503 UnorderedChains.push_back(Copy);
4507 // Finally, if the target has anything special to do, allow it to do so.
4508 // FIXME: this should insert code into the DAG!
4509 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4512 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4513 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4514 FunctionLoweringInfo &FuncInfo) {
4515 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
4517 std::vector<SDOperand> UnorderedChains;
4519 // Lower any arguments needed in this block if this is the entry block.
4520 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4521 LowerArguments(LLVMBB, SDL, UnorderedChains);
4523 BB = FuncInfo.MBBMap[LLVMBB];
4524 SDL.setCurrentBasicBlock(BB);
4526 // Lower all of the non-terminator instructions.
4527 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4531 // Lower call part of invoke.
4532 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4533 if (Invoke) SDL.visitInvoke(*Invoke, false);
4535 // Ensure that all instructions which are used outside of their defining
4536 // blocks are available as virtual registers.
4537 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4538 if (!I->use_empty() && !isa<PHINode>(I)) {
4539 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4540 if (VMI != FuncInfo.ValueMap.end())
4541 UnorderedChains.push_back(
4542 SDL.CopyValueToVirtualRegister(I, VMI->second));
4545 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4546 // ensure constants are generated when needed. Remember the virtual registers
4547 // that need to be added to the Machine PHI nodes as input. We cannot just
4548 // directly add them, because expansion might result in multiple MBB's for one
4549 // BB. As such, the start of the BB might correspond to a different MBB than
4552 TerminatorInst *TI = LLVMBB->getTerminator();
4554 // Emit constants only once even if used by multiple PHI nodes.
4555 std::map<Constant*, unsigned> ConstantsOut;
4557 // Vector bool would be better, but vector<bool> is really slow.
4558 std::vector<unsigned char> SuccsHandled;
4559 if (TI->getNumSuccessors())
4560 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4562 // Check successor nodes PHI nodes that expect a constant to be available from
4564 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4565 BasicBlock *SuccBB = TI->getSuccessor(succ);
4566 if (!isa<PHINode>(SuccBB->begin())) continue;
4567 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4569 // If this terminator has multiple identical successors (common for
4570 // switches), only handle each succ once.
4571 unsigned SuccMBBNo = SuccMBB->getNumber();
4572 if (SuccsHandled[SuccMBBNo]) continue;
4573 SuccsHandled[SuccMBBNo] = true;
4575 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4578 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4579 // nodes and Machine PHI nodes, but the incoming operands have not been
4581 for (BasicBlock::iterator I = SuccBB->begin();
4582 (PN = dyn_cast<PHINode>(I)); ++I) {
4583 // Ignore dead phi's.
4584 if (PN->use_empty()) continue;
4587 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4589 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4590 unsigned &RegOut = ConstantsOut[C];
4592 RegOut = FuncInfo.CreateRegForValue(C);
4593 UnorderedChains.push_back(
4594 SDL.CopyValueToVirtualRegister(C, RegOut));
4598 Reg = FuncInfo.ValueMap[PHIOp];
4600 assert(isa<AllocaInst>(PHIOp) &&
4601 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4602 "Didn't codegen value into a register!??");
4603 Reg = FuncInfo.CreateRegForValue(PHIOp);
4604 UnorderedChains.push_back(
4605 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4609 // Remember that this register needs to added to the machine PHI node as
4610 // the input for this MBB.
4611 MVT::ValueType VT = TLI.getValueType(PN->getType());
4612 unsigned NumElements;
4613 if (VT != MVT::Vector)
4614 NumElements = TLI.getNumElements(VT);
4616 MVT::ValueType VT1,VT2;
4618 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
4621 for (unsigned i = 0, e = NumElements; i != e; ++i)
4622 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4625 ConstantsOut.clear();
4627 // Turn all of the unordered chains into one factored node.
4628 if (!UnorderedChains.empty()) {
4629 SDOperand Root = SDL.getRoot();
4630 if (Root.getOpcode() != ISD::EntryToken) {
4631 unsigned i = 0, e = UnorderedChains.size();
4632 for (; i != e; ++i) {
4633 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4634 if (UnorderedChains[i].Val->getOperand(0) == Root)
4635 break; // Don't add the root if we already indirectly depend on it.
4639 UnorderedChains.push_back(Root);
4641 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4642 &UnorderedChains[0], UnorderedChains.size()));
4645 // Lower the terminator after the copies are emitted.
4647 // Just the branch part of invoke.
4648 SDL.visitInvoke(*Invoke, true);
4650 SDL.visit(*LLVMBB->getTerminator());
4653 // Copy over any CaseBlock records that may now exist due to SwitchInst
4654 // lowering, as well as any jump table information.
4655 SwitchCases.clear();
4656 SwitchCases = SDL.SwitchCases;
4658 JTCases = SDL.JTCases;
4659 BitTestCases.clear();
4660 BitTestCases = SDL.BitTestCases;
4662 // Make sure the root of the DAG is up-to-date.
4663 DAG.setRoot(SDL.getRoot());
4666 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4667 // Get alias analysis for load/store combining.
4668 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4670 // Run the DAG combiner in pre-legalize mode.
4671 DAG.Combine(false, AA);
4673 DOUT << "Lowered selection DAG:\n";
4676 // Second step, hack on the DAG until it only uses operations and types that
4677 // the target supports.
4680 DOUT << "Legalized selection DAG:\n";
4683 // Run the DAG combiner in post-legalize mode.
4684 DAG.Combine(true, AA);
4686 if (ViewISelDAGs) DAG.viewGraph();
4688 // Third, instruction select all of the operations to machine code, adding the
4689 // code to the MachineBasicBlock.
4690 InstructionSelectBasicBlock(DAG);
4692 DOUT << "Selected machine code:\n";
4696 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4697 FunctionLoweringInfo &FuncInfo) {
4698 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4700 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4703 // First step, lower LLVM code to some DAG. This DAG may use operations and
4704 // types that are not supported by the target.
4705 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4707 // Second step, emit the lowered DAG as machine code.
4708 CodeGenAndEmitDAG(DAG);
4711 DOUT << "Total amount of phi nodes to update: "
4712 << PHINodesToUpdate.size() << "\n";
4713 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4714 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4715 << ", " << PHINodesToUpdate[i].second << ")\n";);
4717 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4718 // PHI nodes in successors.
4719 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4720 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4721 MachineInstr *PHI = PHINodesToUpdate[i].first;
4722 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4723 "This is not a machine PHI node that we are updating!");
4724 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4725 PHI->addMachineBasicBlockOperand(BB);
4730 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4731 // Lower header first, if it wasn't already lowered
4732 if (!BitTestCases[i].Emitted) {
4733 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4735 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4736 // Set the current basic block to the mbb we wish to insert the code into
4737 BB = BitTestCases[i].Parent;
4738 HSDL.setCurrentBasicBlock(BB);
4740 HSDL.visitBitTestHeader(BitTestCases[i]);
4741 HSDAG.setRoot(HSDL.getRoot());
4742 CodeGenAndEmitDAG(HSDAG);
4745 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4746 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4748 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4749 // Set the current basic block to the mbb we wish to insert the code into
4750 BB = BitTestCases[i].Cases[j].ThisBB;
4751 BSDL.setCurrentBasicBlock(BB);
4754 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4755 BitTestCases[i].Reg,
4756 BitTestCases[i].Cases[j]);
4758 BSDL.visitBitTestCase(BitTestCases[i].Default,
4759 BitTestCases[i].Reg,
4760 BitTestCases[i].Cases[j]);
4763 BSDAG.setRoot(BSDL.getRoot());
4764 CodeGenAndEmitDAG(BSDAG);
4768 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4769 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4770 MachineBasicBlock *PHIBB = PHI->getParent();
4771 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4772 "This is not a machine PHI node that we are updating!");
4773 // This is "default" BB. We have two jumps to it. From "header" BB and
4774 // from last "case" BB.
4775 if (PHIBB == BitTestCases[i].Default) {
4776 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4777 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4778 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4779 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4781 // One of "cases" BB.
4782 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4783 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4784 if (cBB->succ_end() !=
4785 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4786 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4787 PHI->addMachineBasicBlockOperand(cBB);
4793 // If the JumpTable record is filled in, then we need to emit a jump table.
4794 // Updating the PHI nodes is tricky in this case, since we need to determine
4795 // whether the PHI is a successor of the range check MBB or the jump table MBB
4796 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4797 // Lower header first, if it wasn't already lowered
4798 if (!JTCases[i].first.Emitted) {
4799 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4801 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4802 // Set the current basic block to the mbb we wish to insert the code into
4803 BB = JTCases[i].first.HeaderBB;
4804 HSDL.setCurrentBasicBlock(BB);
4806 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4807 HSDAG.setRoot(HSDL.getRoot());
4808 CodeGenAndEmitDAG(HSDAG);
4811 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4813 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
4814 // Set the current basic block to the mbb we wish to insert the code into
4815 BB = JTCases[i].second.MBB;
4816 JSDL.setCurrentBasicBlock(BB);
4818 JSDL.visitJumpTable(JTCases[i].second);
4819 JSDAG.setRoot(JSDL.getRoot());
4820 CodeGenAndEmitDAG(JSDAG);
4823 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4824 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4825 MachineBasicBlock *PHIBB = PHI->getParent();
4826 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4827 "This is not a machine PHI node that we are updating!");
4828 // "default" BB. We can go there only from header BB.
4829 if (PHIBB == JTCases[i].second.Default) {
4830 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4831 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
4833 // JT BB. Just iterate over successors here
4834 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4835 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4836 PHI->addMachineBasicBlockOperand(BB);
4841 // If the switch block involved a branch to one of the actual successors, we
4842 // need to update PHI nodes in that block.
4843 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4844 MachineInstr *PHI = PHINodesToUpdate[i].first;
4845 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4846 "This is not a machine PHI node that we are updating!");
4847 if (BB->isSuccessor(PHI->getParent())) {
4848 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4849 PHI->addMachineBasicBlockOperand(BB);
4853 // If we generated any switch lowering information, build and codegen any
4854 // additional DAGs necessary.
4855 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4856 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4858 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4860 // Set the current basic block to the mbb we wish to insert the code into
4861 BB = SwitchCases[i].ThisBB;
4862 SDL.setCurrentBasicBlock(BB);
4865 SDL.visitSwitchCase(SwitchCases[i]);
4866 SDAG.setRoot(SDL.getRoot());
4867 CodeGenAndEmitDAG(SDAG);
4869 // Handle any PHI nodes in successors of this chunk, as if we were coming
4870 // from the original BB before switch expansion. Note that PHI nodes can
4871 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4872 // handle them the right number of times.
4873 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4874 for (MachineBasicBlock::iterator Phi = BB->begin();
4875 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4876 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4877 for (unsigned pn = 0; ; ++pn) {
4878 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4879 if (PHINodesToUpdate[pn].first == Phi) {
4880 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4881 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4887 // Don't process RHS if same block as LHS.
4888 if (BB == SwitchCases[i].FalseBB)
4889 SwitchCases[i].FalseBB = 0;
4891 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4892 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4893 SwitchCases[i].FalseBB = 0;
4895 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4900 //===----------------------------------------------------------------------===//
4901 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4902 /// target node in the graph.
4903 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4904 if (ViewSchedDAGs) DAG.viewGraph();
4906 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4910 RegisterScheduler::setDefault(Ctor);
4913 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4919 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4920 return new HazardRecognizer();
4923 //===----------------------------------------------------------------------===//
4924 // Helper functions used by the generated instruction selector.
4925 //===----------------------------------------------------------------------===//
4926 // Calls to these methods are generated by tblgen.
4928 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4929 /// the dag combiner simplified the 255, we still want to match. RHS is the
4930 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4931 /// specified in the .td file (e.g. 255).
4932 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4933 int64_t DesiredMaskS) {
4934 uint64_t ActualMask = RHS->getValue();
4935 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4937 // If the actual mask exactly matches, success!
4938 if (ActualMask == DesiredMask)
4941 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4942 if (ActualMask & ~DesiredMask)
4945 // Otherwise, the DAG Combiner may have proven that the value coming in is
4946 // either already zero or is not demanded. Check for known zero input bits.
4947 uint64_t NeededMask = DesiredMask & ~ActualMask;
4948 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4951 // TODO: check to see if missing bits are just not demanded.
4953 // Otherwise, this pattern doesn't match.
4957 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4958 /// the dag combiner simplified the 255, we still want to match. RHS is the
4959 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4960 /// specified in the .td file (e.g. 255).
4961 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4962 int64_t DesiredMaskS) {
4963 uint64_t ActualMask = RHS->getValue();
4964 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4966 // If the actual mask exactly matches, success!
4967 if (ActualMask == DesiredMask)
4970 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4971 if (ActualMask & ~DesiredMask)
4974 // Otherwise, the DAG Combiner may have proven that the value coming in is
4975 // either already zero or is not demanded. Check for known zero input bits.
4976 uint64_t NeededMask = DesiredMask & ~ActualMask;
4978 uint64_t KnownZero, KnownOne;
4979 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4981 // If all the missing bits in the or are already known to be set, match!
4982 if ((NeededMask & KnownOne) == NeededMask)
4985 // TODO: check to see if missing bits are just not demanded.
4987 // Otherwise, this pattern doesn't match.
4992 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4993 /// by tblgen. Others should not call it.
4994 void SelectionDAGISel::
4995 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4996 std::vector<SDOperand> InOps;
4997 std::swap(InOps, Ops);
4999 Ops.push_back(InOps[0]); // input chain.
5000 Ops.push_back(InOps[1]); // input asm string.
5002 unsigned i = 2, e = InOps.size();
5003 if (InOps[e-1].getValueType() == MVT::Flag)
5004 --e; // Don't process a flag operand if it is here.
5007 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5008 if ((Flags & 7) != 4 /*MEM*/) {
5009 // Just skip over this operand, copying the operands verbatim.
5010 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5011 i += (Flags >> 3) + 1;
5013 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5014 // Otherwise, this is a memory operand. Ask the target to select it.
5015 std::vector<SDOperand> SelOps;
5016 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5017 cerr << "Could not match memory address. Inline asm failure!\n";
5021 // Add this to the output node.
5022 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5023 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5025 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5030 // Add the flag input back if present.
5031 if (e != InOps.size())
5032 Ops.push_back(InOps.back());
5035 char SelectionDAGISel::ID = 0;