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);
534 // Terminator instructions.
535 void visitRet(ReturnInst &I);
536 void visitBr(BranchInst &I);
537 void visitSwitch(SwitchInst &I);
538 void visitUnreachable(UnreachableInst &I) { /* noop */ }
540 // Helpers for visitSwitch
541 bool handleSmallSwitchRange(CaseRec& CR,
542 CaseRecVector& WorkList,
544 MachineBasicBlock* Default);
545 bool handleJTSwitchCase(CaseRec& CR,
546 CaseRecVector& WorkList,
548 MachineBasicBlock* Default);
549 bool handleBTSplitSwitchCase(CaseRec& CR,
550 CaseRecVector& WorkList,
552 MachineBasicBlock* Default);
553 bool handleBitTestsSwitchCase(CaseRec& CR,
554 CaseRecVector& WorkList,
556 MachineBasicBlock* Default);
557 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
558 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
559 void visitBitTestCase(MachineBasicBlock* NextMBB,
561 SelectionDAGISel::BitTestCase &B);
562 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
563 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
564 SelectionDAGISel::JumpTableHeader &JTH);
566 // These all get lowered before this pass.
567 void visitInvoke(InvokeInst &I);
568 void visitInvoke(InvokeInst &I, bool AsTerminator);
569 void visitUnwind(UnwindInst &I);
571 void visitScalarBinary(User &I, unsigned OpCode);
572 void visitVectorBinary(User &I, unsigned OpCode);
573 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
574 void visitShift(User &I, unsigned Opcode);
575 void visitAdd(User &I) {
576 if (isa<VectorType>(I.getType()))
577 visitVectorBinary(I, ISD::VADD);
578 else if (I.getType()->isFloatingPoint())
579 visitScalarBinary(I, ISD::FADD);
581 visitScalarBinary(I, ISD::ADD);
583 void visitSub(User &I);
584 void visitMul(User &I) {
585 if (isa<VectorType>(I.getType()))
586 visitVectorBinary(I, ISD::VMUL);
587 else if (I.getType()->isFloatingPoint())
588 visitScalarBinary(I, ISD::FMUL);
590 visitScalarBinary(I, ISD::MUL);
592 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
593 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
594 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
595 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
596 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
597 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
598 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
599 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
600 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
601 void visitShl (User &I) { visitShift(I, ISD::SHL); }
602 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
603 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
604 void visitICmp(User &I);
605 void visitFCmp(User &I);
606 // Visit the conversion instructions
607 void visitTrunc(User &I);
608 void visitZExt(User &I);
609 void visitSExt(User &I);
610 void visitFPTrunc(User &I);
611 void visitFPExt(User &I);
612 void visitFPToUI(User &I);
613 void visitFPToSI(User &I);
614 void visitUIToFP(User &I);
615 void visitSIToFP(User &I);
616 void visitPtrToInt(User &I);
617 void visitIntToPtr(User &I);
618 void visitBitCast(User &I);
620 void visitExtractElement(User &I);
621 void visitInsertElement(User &I);
622 void visitShuffleVector(User &I);
624 void visitGetElementPtr(User &I);
625 void visitSelect(User &I);
627 void visitMalloc(MallocInst &I);
628 void visitFree(FreeInst &I);
629 void visitAlloca(AllocaInst &I);
630 void visitLoad(LoadInst &I);
631 void visitStore(StoreInst &I);
632 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
633 void visitCall(CallInst &I);
634 void visitInlineAsm(CallInst &I);
635 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
636 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
638 void visitVAStart(CallInst &I);
639 void visitVAArg(VAArgInst &I);
640 void visitVAEnd(CallInst &I);
641 void visitVACopy(CallInst &I);
643 void visitMemIntrinsic(CallInst &I, unsigned Op);
645 void visitUserOp1(Instruction &I) {
646 assert(0 && "UserOp1 should not exist at instruction selection time!");
649 void visitUserOp2(Instruction &I) {
650 assert(0 && "UserOp2 should not exist at instruction selection time!");
654 } // end namespace llvm
656 SDOperand SelectionDAGLowering::getValue(const Value *V) {
657 SDOperand &N = NodeMap[V];
660 const Type *VTy = V->getType();
661 MVT::ValueType VT = TLI.getValueType(VTy);
662 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
663 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
664 visit(CE->getOpcode(), *CE);
665 SDOperand N1 = NodeMap[V];
666 assert(N1.Val && "visit didn't populate the ValueMap!");
668 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
669 return N = DAG.getGlobalAddress(GV, VT);
670 } else if (isa<ConstantPointerNull>(C)) {
671 return N = DAG.getConstant(0, TLI.getPointerTy());
672 } else if (isa<UndefValue>(C)) {
673 if (!isa<VectorType>(VTy))
674 return N = DAG.getNode(ISD::UNDEF, VT);
676 // Create a VBUILD_VECTOR of undef nodes.
677 const VectorType *PTy = cast<VectorType>(VTy);
678 unsigned NumElements = PTy->getNumElements();
679 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
681 SmallVector<SDOperand, 8> Ops;
682 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
684 // Create a VConstant node with generic Vector type.
685 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
686 Ops.push_back(DAG.getValueType(PVT));
687 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
688 &Ops[0], Ops.size());
689 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
690 return N = DAG.getConstantFP(CFP->getValue(), VT);
691 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
692 unsigned NumElements = PTy->getNumElements();
693 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
695 // Now that we know the number and type of the elements, push a
696 // Constant or ConstantFP node onto the ops list for each element of
697 // the packed constant.
698 SmallVector<SDOperand, 8> Ops;
699 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
700 for (unsigned i = 0; i != NumElements; ++i)
701 Ops.push_back(getValue(CP->getOperand(i)));
703 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
705 if (MVT::isFloatingPoint(PVT))
706 Op = DAG.getConstantFP(0, PVT);
708 Op = DAG.getConstant(0, PVT);
709 Ops.assign(NumElements, Op);
712 // Create a VBUILD_VECTOR node with generic Vector type.
713 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
714 Ops.push_back(DAG.getValueType(PVT));
715 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
718 // Canonicalize all constant ints to be unsigned.
719 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
723 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
724 std::map<const AllocaInst*, int>::iterator SI =
725 FuncInfo.StaticAllocaMap.find(AI);
726 if (SI != FuncInfo.StaticAllocaMap.end())
727 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
730 unsigned InReg = FuncInfo.ValueMap[V];
731 assert(InReg && "Value not in map!");
733 // If this type is not legal, make it so now.
734 if (VT != MVT::Vector) {
735 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
736 // Source must be expanded. This input value is actually coming from the
737 // register pair InReg and InReg+1.
738 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
739 unsigned NumVals = TLI.getNumElements(VT);
740 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
742 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
744 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
745 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
746 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
749 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
750 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
751 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
752 N = MVT::isFloatingPoint(VT)
753 ? DAG.getNode(ISD::FP_ROUND, VT, N)
754 : DAG.getNode(ISD::TRUNCATE, VT, N);
757 // Otherwise, if this is a vector, make it available as a generic vector
759 MVT::ValueType PTyElementVT, PTyLegalElementVT;
760 const VectorType *PTy = cast<VectorType>(VTy);
761 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
764 // Build a VBUILD_VECTOR with the input registers.
765 SmallVector<SDOperand, 8> Ops;
766 if (PTyElementVT == PTyLegalElementVT) {
767 // If the value types are legal, just VBUILD the CopyFromReg nodes.
768 for (unsigned i = 0; i != NE; ++i)
769 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
771 } else if (PTyElementVT < PTyLegalElementVT) {
772 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
773 for (unsigned i = 0; i != NE; ++i) {
774 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
776 if (MVT::isFloatingPoint(PTyElementVT))
777 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
779 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
783 // If the register was expanded, use BUILD_PAIR.
784 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
785 for (unsigned i = 0; i != NE/2; ++i) {
786 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
788 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
790 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
794 Ops.push_back(DAG.getConstant(NE, MVT::i32));
795 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
796 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
798 // Finally, use a VBIT_CONVERT to make this available as the appropriate
800 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
801 DAG.getConstant(PTy->getNumElements(),
803 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
810 void SelectionDAGLowering::visitRet(ReturnInst &I) {
811 if (I.getNumOperands() == 0) {
812 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
815 SmallVector<SDOperand, 8> NewValues;
816 NewValues.push_back(getRoot());
817 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
818 SDOperand RetOp = getValue(I.getOperand(i));
820 // If this is an integer return value, we need to promote it ourselves to
821 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
823 // FIXME: C calling convention requires the return type to be promoted to
824 // at least 32-bit. But this is not necessary for non-C calling conventions.
825 if (MVT::isInteger(RetOp.getValueType()) &&
826 RetOp.getValueType() < MVT::i64) {
827 MVT::ValueType TmpVT;
828 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
829 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
832 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
833 const ParamAttrsList *Attrs = FTy->getParamAttrs();
834 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
835 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
836 ExtendKind = ISD::SIGN_EXTEND;
837 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
838 ExtendKind = ISD::ZERO_EXTEND;
839 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
841 NewValues.push_back(RetOp);
842 NewValues.push_back(DAG.getConstant(false, MVT::i32));
844 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
845 &NewValues[0], NewValues.size()));
848 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
849 /// the current basic block, add it to ValueMap now so that we'll get a
851 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
852 // No need to export constants.
853 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
856 if (FuncInfo.isExportedInst(V)) return;
858 unsigned Reg = FuncInfo.InitializeRegForValue(V);
859 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
862 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
863 const BasicBlock *FromBB) {
864 // The operands of the setcc have to be in this block. We don't know
865 // how to export them from some other block.
866 if (Instruction *VI = dyn_cast<Instruction>(V)) {
867 // Can export from current BB.
868 if (VI->getParent() == FromBB)
871 // Is already exported, noop.
872 return FuncInfo.isExportedInst(V);
875 // If this is an argument, we can export it if the BB is the entry block or
876 // if it is already exported.
877 if (isa<Argument>(V)) {
878 if (FromBB == &FromBB->getParent()->getEntryBlock())
881 // Otherwise, can only export this if it is already exported.
882 return FuncInfo.isExportedInst(V);
885 // Otherwise, constants can always be exported.
889 static bool InBlock(const Value *V, const BasicBlock *BB) {
890 if (const Instruction *I = dyn_cast<Instruction>(V))
891 return I->getParent() == BB;
895 /// FindMergedConditions - If Cond is an expression like
896 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
897 MachineBasicBlock *TBB,
898 MachineBasicBlock *FBB,
899 MachineBasicBlock *CurBB,
901 // If this node is not part of the or/and tree, emit it as a branch.
902 Instruction *BOp = dyn_cast<Instruction>(Cond);
904 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
905 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
906 BOp->getParent() != CurBB->getBasicBlock() ||
907 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
908 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
909 const BasicBlock *BB = CurBB->getBasicBlock();
911 // If the leaf of the tree is a comparison, merge the condition into
913 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
914 // The operands of the cmp have to be in this block. We don't know
915 // how to export them from some other block. If this is the first block
916 // of the sequence, no exporting is needed.
918 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
919 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
920 BOp = cast<Instruction>(Cond);
921 ISD::CondCode Condition;
922 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
923 switch (IC->getPredicate()) {
924 default: assert(0 && "Unknown icmp predicate opcode!");
925 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
926 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
927 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
928 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
929 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
930 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
931 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
932 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
933 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
934 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
936 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
937 ISD::CondCode FPC, FOC;
938 switch (FC->getPredicate()) {
939 default: assert(0 && "Unknown fcmp predicate opcode!");
940 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
941 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
942 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
943 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
944 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
945 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
946 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
947 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
948 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
949 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
950 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
951 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
952 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
953 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
954 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
955 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
957 if (FiniteOnlyFPMath())
962 Condition = ISD::SETEQ; // silence warning.
963 assert(0 && "Unknown compare instruction");
966 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
967 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
968 SwitchCases.push_back(CB);
972 // Create a CaseBlock record representing this branch.
973 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
974 NULL, TBB, FBB, CurBB);
975 SwitchCases.push_back(CB);
980 // Create TmpBB after CurBB.
981 MachineFunction::iterator BBI = CurBB;
982 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
983 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
985 if (Opc == Instruction::Or) {
994 // Emit the LHS condition.
995 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
997 // Emit the RHS condition into TmpBB.
998 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1000 assert(Opc == Instruction::And && "Unknown merge op!");
1001 // Codegen X & Y as:
1008 // This requires creation of TmpBB after CurBB.
1010 // Emit the LHS condition.
1011 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1013 // Emit the RHS condition into TmpBB.
1014 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1018 /// If the set of cases should be emitted as a series of branches, return true.
1019 /// If we should emit this as a bunch of and/or'd together conditions, return
1022 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1023 if (Cases.size() != 2) return true;
1025 // If this is two comparisons of the same values or'd or and'd together, they
1026 // will get folded into a single comparison, so don't emit two blocks.
1027 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1028 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1029 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1030 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1037 void SelectionDAGLowering::visitBr(BranchInst &I) {
1038 // Update machine-CFG edges.
1039 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1041 // Figure out which block is immediately after the current one.
1042 MachineBasicBlock *NextBlock = 0;
1043 MachineFunction::iterator BBI = CurMBB;
1044 if (++BBI != CurMBB->getParent()->end())
1047 if (I.isUnconditional()) {
1048 // If this is not a fall-through branch, emit the branch.
1049 if (Succ0MBB != NextBlock)
1050 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1051 DAG.getBasicBlock(Succ0MBB)));
1053 // Update machine-CFG edges.
1054 CurMBB->addSuccessor(Succ0MBB);
1059 // If this condition is one of the special cases we handle, do special stuff
1061 Value *CondVal = I.getCondition();
1062 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1064 // If this is a series of conditions that are or'd or and'd together, emit
1065 // this as a sequence of branches instead of setcc's with and/or operations.
1066 // For example, instead of something like:
1079 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1080 if (BOp->hasOneUse() &&
1081 (BOp->getOpcode() == Instruction::And ||
1082 BOp->getOpcode() == Instruction::Or)) {
1083 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1084 // If the compares in later blocks need to use values not currently
1085 // exported from this block, export them now. This block should always
1086 // be the first entry.
1087 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1089 // Allow some cases to be rejected.
1090 if (ShouldEmitAsBranches(SwitchCases)) {
1091 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1092 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1093 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1096 // Emit the branch for this block.
1097 visitSwitchCase(SwitchCases[0]);
1098 SwitchCases.erase(SwitchCases.begin());
1102 // Okay, we decided not to do this, remove any inserted MBB's and clear
1104 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1105 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1107 SwitchCases.clear();
1111 // Create a CaseBlock record representing this branch.
1112 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1113 NULL, Succ0MBB, Succ1MBB, CurMBB);
1114 // Use visitSwitchCase to actually insert the fast branch sequence for this
1116 visitSwitchCase(CB);
1119 /// visitSwitchCase - Emits the necessary code to represent a single node in
1120 /// the binary search tree resulting from lowering a switch instruction.
1121 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1123 SDOperand CondLHS = getValue(CB.CmpLHS);
1125 // Build the setcc now.
1126 if (CB.CmpMHS == NULL) {
1127 // Fold "(X == true)" to X and "(X == false)" to !X to
1128 // handle common cases produced by branch lowering.
1129 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1131 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1132 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1133 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1135 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1137 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1139 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1140 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1142 SDOperand CmpOp = getValue(CB.CmpMHS);
1143 MVT::ValueType VT = CmpOp.getValueType();
1145 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1146 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1148 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1149 Cond = DAG.getSetCC(MVT::i1, SUB,
1150 DAG.getConstant(High-Low, VT), ISD::SETULE);
1155 // Set NextBlock to be the MBB immediately after the current one, if any.
1156 // This is used to avoid emitting unnecessary branches to the next block.
1157 MachineBasicBlock *NextBlock = 0;
1158 MachineFunction::iterator BBI = CurMBB;
1159 if (++BBI != CurMBB->getParent()->end())
1162 // If the lhs block is the next block, invert the condition so that we can
1163 // fall through to the lhs instead of the rhs block.
1164 if (CB.TrueBB == NextBlock) {
1165 std::swap(CB.TrueBB, CB.FalseBB);
1166 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1167 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1169 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1170 DAG.getBasicBlock(CB.TrueBB));
1171 if (CB.FalseBB == NextBlock)
1172 DAG.setRoot(BrCond);
1174 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1175 DAG.getBasicBlock(CB.FalseBB)));
1176 // Update successor info
1177 CurMBB->addSuccessor(CB.TrueBB);
1178 CurMBB->addSuccessor(CB.FalseBB);
1181 /// visitJumpTable - Emit JumpTable node in the current MBB
1182 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1183 // Emit the code for the jump table
1184 assert(JT.Reg != -1U && "Should lower JT Header first!");
1185 MVT::ValueType PTy = TLI.getPointerTy();
1186 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1187 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1188 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1193 /// visitJumpTableHeader - This function emits necessary code to produce index
1194 /// in the JumpTable from switch case.
1195 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1196 SelectionDAGISel::JumpTableHeader &JTH) {
1197 // Subtract the lowest switch case value from the value being switched on
1198 // and conditional branch to default mbb if the result is greater than the
1199 // difference between smallest and largest cases.
1200 SDOperand SwitchOp = getValue(JTH.SValue);
1201 MVT::ValueType VT = SwitchOp.getValueType();
1202 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1203 DAG.getConstant(JTH.First, VT));
1205 // The SDNode we just created, which holds the value being switched on
1206 // minus the the smallest case value, needs to be copied to a virtual
1207 // register so it can be used as an index into the jump table in a
1208 // subsequent basic block. This value may be smaller or larger than the
1209 // target's pointer type, and therefore require extension or truncating.
1210 if (VT > TLI.getPointerTy())
1211 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1213 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1215 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1216 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1217 JT.Reg = JumpTableReg;
1219 // Emit the range check for the jump table, and branch to the default
1220 // block for the switch statement if the value being switched on exceeds
1221 // the largest case in the switch.
1222 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1223 DAG.getConstant(JTH.Last-JTH.First,VT),
1226 // Set NextBlock to be the MBB immediately after the current one, if any.
1227 // This is used to avoid emitting unnecessary branches to the next block.
1228 MachineBasicBlock *NextBlock = 0;
1229 MachineFunction::iterator BBI = CurMBB;
1230 if (++BBI != CurMBB->getParent()->end())
1233 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1234 DAG.getBasicBlock(JT.Default));
1236 if (JT.MBB == NextBlock)
1237 DAG.setRoot(BrCond);
1239 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1240 DAG.getBasicBlock(JT.MBB)));
1245 /// visitBitTestHeader - This function emits necessary code to produce value
1246 /// suitable for "bit tests"
1247 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1248 // Subtract the minimum value
1249 SDOperand SwitchOp = getValue(B.SValue);
1250 MVT::ValueType VT = SwitchOp.getValueType();
1251 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1252 DAG.getConstant(B.First, VT));
1255 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1256 DAG.getConstant(B.Range, VT),
1260 if (VT > TLI.getShiftAmountTy())
1261 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1263 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1265 // Make desired shift
1266 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1267 DAG.getConstant(1, TLI.getPointerTy()),
1270 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1271 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1274 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1275 DAG.getBasicBlock(B.Default));
1277 // Set NextBlock to be the MBB immediately after the current one, if any.
1278 // This is used to avoid emitting unnecessary branches to the next block.
1279 MachineBasicBlock *NextBlock = 0;
1280 MachineFunction::iterator BBI = CurMBB;
1281 if (++BBI != CurMBB->getParent()->end())
1284 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1285 if (MBB == NextBlock)
1286 DAG.setRoot(BrRange);
1288 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1289 DAG.getBasicBlock(MBB)));
1291 CurMBB->addSuccessor(B.Default);
1292 CurMBB->addSuccessor(MBB);
1297 /// visitBitTestCase - this function produces one "bit test"
1298 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1300 SelectionDAGISel::BitTestCase &B) {
1301 // Emit bit tests and jumps
1302 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1304 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1306 DAG.getConstant(B.Mask,
1307 TLI.getPointerTy()));
1308 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1309 DAG.getConstant(0, TLI.getPointerTy()),
1311 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1312 AndCmp, DAG.getBasicBlock(B.TargetBB));
1314 // Set NextBlock to be the MBB immediately after the current one, if any.
1315 // This is used to avoid emitting unnecessary branches to the next block.
1316 MachineBasicBlock *NextBlock = 0;
1317 MachineFunction::iterator BBI = CurMBB;
1318 if (++BBI != CurMBB->getParent()->end())
1321 if (NextMBB == NextBlock)
1324 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1325 DAG.getBasicBlock(NextMBB)));
1327 CurMBB->addSuccessor(B.TargetBB);
1328 CurMBB->addSuccessor(NextMBB);
1333 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1334 assert(0 && "Should never be visited directly");
1336 void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
1337 // Retrieve successors.
1338 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1339 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1341 if (!AsTerminator) {
1342 // Mark landing pad so that it doesn't get deleted in branch folding.
1343 LandingPad->setIsLandingPad();
1345 // Insert a label before the invoke call to mark the try range.
1346 // This can be used to detect deletion of the invoke via the
1347 // MachineModuleInfo.
1348 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1349 unsigned BeginLabel = MMI->NextLabelID();
1350 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1351 DAG.getConstant(BeginLabel, MVT::i32)));
1353 LowerCallTo(I, I.getCalledValue()->getType(),
1356 getValue(I.getOperand(0)),
1359 // Insert a label before the invoke call to mark the try range.
1360 // This can be used to detect deletion of the invoke via the
1361 // MachineModuleInfo.
1362 unsigned EndLabel = MMI->NextLabelID();
1363 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1364 DAG.getConstant(EndLabel, MVT::i32)));
1366 // Inform MachineModuleInfo of range.
1367 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1369 // Update successor info
1370 CurMBB->addSuccessor(Return);
1371 CurMBB->addSuccessor(LandingPad);
1373 // Drop into normal successor.
1374 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1375 DAG.getBasicBlock(Return)));
1379 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1382 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1383 /// small case ranges).
1384 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1385 CaseRecVector& WorkList,
1387 MachineBasicBlock* Default) {
1388 Case& BackCase = *(CR.Range.second-1);
1390 // Size is the number of Cases represented by this range.
1391 unsigned Size = CR.Range.second - CR.Range.first;
1395 // Get the MachineFunction which holds the current MBB. This is used when
1396 // inserting any additional MBBs necessary to represent the switch.
1397 MachineFunction *CurMF = CurMBB->getParent();
1399 // Figure out which block is immediately after the current one.
1400 MachineBasicBlock *NextBlock = 0;
1401 MachineFunction::iterator BBI = CR.CaseBB;
1403 if (++BBI != CurMBB->getParent()->end())
1406 // TODO: If any two of the cases has the same destination, and if one value
1407 // is the same as the other, but has one bit unset that the other has set,
1408 // use bit manipulation to do two compares at once. For example:
1409 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1411 // Rearrange the case blocks so that the last one falls through if possible.
1412 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1413 // The last case block won't fall through into 'NextBlock' if we emit the
1414 // branches in this order. See if rearranging a case value would help.
1415 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1416 if (I->BB == NextBlock) {
1417 std::swap(*I, BackCase);
1423 // Create a CaseBlock record representing a conditional branch to
1424 // the Case's target mbb if the value being switched on SV is equal
1426 MachineBasicBlock *CurBlock = CR.CaseBB;
1427 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1428 MachineBasicBlock *FallThrough;
1430 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1431 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1433 // If the last case doesn't match, go to the default block.
1434 FallThrough = Default;
1437 Value *RHS, *LHS, *MHS;
1439 if (I->High == I->Low) {
1440 // This is just small small case range :) containing exactly 1 case
1442 LHS = SV; RHS = I->High; MHS = NULL;
1445 LHS = I->Low; MHS = SV; RHS = I->High;
1447 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1448 I->BB, FallThrough, CurBlock);
1450 // If emitting the first comparison, just call visitSwitchCase to emit the
1451 // code into the current block. Otherwise, push the CaseBlock onto the
1452 // vector to be later processed by SDISel, and insert the node's MBB
1453 // before the next MBB.
1454 if (CurBlock == CurMBB)
1455 visitSwitchCase(CB);
1457 SwitchCases.push_back(CB);
1459 CurBlock = FallThrough;
1465 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1466 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1467 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1470 /// handleJTSwitchCase - Emit jumptable for current switch case range
1471 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1472 CaseRecVector& WorkList,
1474 MachineBasicBlock* Default) {
1475 Case& FrontCase = *CR.Range.first;
1476 Case& BackCase = *(CR.Range.second-1);
1478 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1479 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1482 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1486 if (!areJTsAllowed(TLI) || TSize <= 3)
1489 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1493 DOUT << "Lowering jump table\n"
1494 << "First entry: " << First << ". Last entry: " << Last << "\n"
1495 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1497 // Get the MachineFunction which holds the current MBB. This is used when
1498 // inserting any additional MBBs necessary to represent the switch.
1499 MachineFunction *CurMF = CurMBB->getParent();
1501 // Figure out which block is immediately after the current one.
1502 MachineBasicBlock *NextBlock = 0;
1503 MachineFunction::iterator BBI = CR.CaseBB;
1505 if (++BBI != CurMBB->getParent()->end())
1508 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1510 // Create a new basic block to hold the code for loading the address
1511 // of the jump table, and jumping to it. Update successor information;
1512 // we will either branch to the default case for the switch, or the jump
1514 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1515 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1516 CR.CaseBB->addSuccessor(Default);
1517 CR.CaseBB->addSuccessor(JumpTableBB);
1519 // Build a vector of destination BBs, corresponding to each target
1520 // of the jump table. If the value of the jump table slot corresponds to
1521 // a case statement, push the case's BB onto the vector, otherwise, push
1523 std::vector<MachineBasicBlock*> DestBBs;
1524 int64_t TEI = First;
1525 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1526 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1527 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1529 if ((Low <= TEI) && (TEI <= High)) {
1530 DestBBs.push_back(I->BB);
1534 DestBBs.push_back(Default);
1538 // Update successor info. Add one edge to each unique successor.
1539 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1540 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1541 E = DestBBs.end(); I != E; ++I) {
1542 if (!SuccsHandled[(*I)->getNumber()]) {
1543 SuccsHandled[(*I)->getNumber()] = true;
1544 JumpTableBB->addSuccessor(*I);
1548 // Create a jump table index for this jump table, or return an existing
1550 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1552 // Set the jump table information so that we can codegen it as a second
1553 // MachineBasicBlock
1554 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1555 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1556 (CR.CaseBB == CurMBB));
1557 if (CR.CaseBB == CurMBB)
1558 visitJumpTableHeader(JT, JTH);
1560 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1565 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1567 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1568 CaseRecVector& WorkList,
1570 MachineBasicBlock* Default) {
1571 // Get the MachineFunction which holds the current MBB. This is used when
1572 // inserting any additional MBBs necessary to represent the switch.
1573 MachineFunction *CurMF = CurMBB->getParent();
1575 // Figure out which block is immediately after the current one.
1576 MachineBasicBlock *NextBlock = 0;
1577 MachineFunction::iterator BBI = CR.CaseBB;
1579 if (++BBI != CurMBB->getParent()->end())
1582 Case& FrontCase = *CR.Range.first;
1583 Case& BackCase = *(CR.Range.second-1);
1584 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1586 // Size is the number of Cases represented by this range.
1587 unsigned Size = CR.Range.second - CR.Range.first;
1589 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1590 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1592 CaseItr Pivot = CR.Range.first + Size/2;
1594 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1595 // (heuristically) allow us to emit JumpTable's later.
1597 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1601 uint64_t LSize = FrontCase.size();
1602 uint64_t RSize = TSize-LSize;
1603 DOUT << "Selecting best pivot: \n"
1604 << "First: " << First << ", Last: " << Last <<"\n"
1605 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1606 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1608 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1609 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1610 assert((RBegin-LEnd>=1) && "Invalid case distance");
1611 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1612 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1613 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1614 // Should always split in some non-trivial place
1616 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1617 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1618 << "Metric: " << Metric << "\n";
1619 if (FMetric < Metric) {
1622 DOUT << "Current metric set to: " << FMetric << "\n";
1628 if (areJTsAllowed(TLI)) {
1629 // If our case is dense we *really* should handle it earlier!
1630 assert((FMetric > 0) && "Should handle dense range earlier!");
1632 Pivot = CR.Range.first + Size/2;
1635 CaseRange LHSR(CR.Range.first, Pivot);
1636 CaseRange RHSR(Pivot, CR.Range.second);
1637 Constant *C = Pivot->Low;
1638 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1640 // We know that we branch to the LHS if the Value being switched on is
1641 // less than the Pivot value, C. We use this to optimize our binary
1642 // tree a bit, by recognizing that if SV is greater than or equal to the
1643 // LHS's Case Value, and that Case Value is exactly one less than the
1644 // Pivot's Value, then we can branch directly to the LHS's Target,
1645 // rather than creating a leaf node for it.
1646 if ((LHSR.second - LHSR.first) == 1 &&
1647 LHSR.first->High == CR.GE &&
1648 cast<ConstantInt>(C)->getSExtValue() ==
1649 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1650 TrueBB = LHSR.first->BB;
1652 TrueBB = new MachineBasicBlock(LLVMBB);
1653 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1654 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1657 // Similar to the optimization above, if the Value being switched on is
1658 // known to be less than the Constant CR.LT, and the current Case Value
1659 // is CR.LT - 1, then we can branch directly to the target block for
1660 // the current Case Value, rather than emitting a RHS leaf node for it.
1661 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1662 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1663 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1664 FalseBB = RHSR.first->BB;
1666 FalseBB = new MachineBasicBlock(LLVMBB);
1667 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1668 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1671 // Create a CaseBlock record representing a conditional branch to
1672 // the LHS node if the value being switched on SV is less than C.
1673 // Otherwise, branch to LHS.
1674 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1675 TrueBB, FalseBB, CR.CaseBB);
1677 if (CR.CaseBB == CurMBB)
1678 visitSwitchCase(CB);
1680 SwitchCases.push_back(CB);
1685 /// handleBitTestsSwitchCase - if current case range has few destination and
1686 /// range span less, than machine word bitwidth, encode case range into series
1687 /// of masks and emit bit tests with these masks.
1688 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1689 CaseRecVector& WorkList,
1691 MachineBasicBlock* Default){
1692 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1694 Case& FrontCase = *CR.Range.first;
1695 Case& BackCase = *(CR.Range.second-1);
1697 // Get the MachineFunction which holds the current MBB. This is used when
1698 // inserting any additional MBBs necessary to represent the switch.
1699 MachineFunction *CurMF = CurMBB->getParent();
1701 unsigned numCmps = 0;
1702 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1704 // Single case counts one, case range - two.
1705 if (I->Low == I->High)
1711 // Count unique destinations
1712 SmallSet<MachineBasicBlock*, 4> Dests;
1713 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1714 Dests.insert(I->BB);
1715 if (Dests.size() > 3)
1716 // Don't bother the code below, if there are too much unique destinations
1719 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1720 << "Total number of comparisons: " << numCmps << "\n";
1722 // Compute span of values.
1723 Constant* minValue = FrontCase.Low;
1724 Constant* maxValue = BackCase.High;
1725 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1726 cast<ConstantInt>(minValue)->getSExtValue();
1727 DOUT << "Compare range: " << range << "\n"
1728 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1729 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1731 if (range>=IntPtrBits ||
1732 (!(Dests.size() == 1 && numCmps >= 3) &&
1733 !(Dests.size() == 2 && numCmps >= 5) &&
1734 !(Dests.size() >= 3 && numCmps >= 6)))
1737 DOUT << "Emitting bit tests\n";
1738 int64_t lowBound = 0;
1740 // Optimize the case where all the case values fit in a
1741 // word without having to subtract minValue. In this case,
1742 // we can optimize away the subtraction.
1743 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1744 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1745 range = cast<ConstantInt>(maxValue)->getSExtValue();
1747 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1750 CaseBitsVector CasesBits;
1751 unsigned i, count = 0;
1753 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1754 MachineBasicBlock* Dest = I->BB;
1755 for (i = 0; i < count; ++i)
1756 if (Dest == CasesBits[i].BB)
1760 assert((count < 3) && "Too much destinations to test!");
1761 CasesBits.push_back(CaseBits(0, Dest, 0));
1765 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1766 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1768 for (uint64_t j = lo; j <= hi; j++) {
1769 CasesBits[i].Mask |= 1ULL << j;
1770 CasesBits[i].Bits++;
1774 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1776 SelectionDAGISel::BitTestInfo BTC;
1778 // Figure out which block is immediately after the current one.
1779 MachineFunction::iterator BBI = CR.CaseBB;
1782 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1785 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1786 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1787 << ", BB: " << CasesBits[i].BB << "\n";
1789 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1790 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1791 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1796 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
1797 -1U, (CR.CaseBB == CurMBB),
1798 CR.CaseBB, Default, BTC);
1800 if (CR.CaseBB == CurMBB)
1801 visitBitTestHeader(BTB);
1803 BitTestCases.push_back(BTB);
1809 // Clusterify - Transform simple list of Cases into list of CaseRange's
1810 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1811 const SwitchInst& SI) {
1812 unsigned numCmps = 0;
1814 // Start with "simple" cases
1815 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1816 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1817 Cases.push_back(Case(SI.getSuccessorValue(i),
1818 SI.getSuccessorValue(i),
1821 sort(Cases.begin(), Cases.end(), CaseCmp());
1823 // Merge case into clusters
1824 if (Cases.size()>=2)
1825 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1826 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1827 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1828 MachineBasicBlock* nextBB = J->BB;
1829 MachineBasicBlock* currentBB = I->BB;
1831 // If the two neighboring cases go to the same destination, merge them
1832 // into a single case.
1833 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1841 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1842 if (I->Low != I->High)
1843 // A range counts double, since it requires two compares.
1850 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1851 // Figure out which block is immediately after the current one.
1852 MachineBasicBlock *NextBlock = 0;
1853 MachineFunction::iterator BBI = CurMBB;
1855 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1857 // If there is only the default destination, branch to it if it is not the
1858 // next basic block. Otherwise, just fall through.
1859 if (SI.getNumOperands() == 2) {
1860 // Update machine-CFG edges.
1862 // If this is not a fall-through branch, emit the branch.
1863 if (Default != NextBlock)
1864 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1865 DAG.getBasicBlock(Default)));
1867 CurMBB->addSuccessor(Default);
1871 // If there are any non-default case statements, create a vector of Cases
1872 // representing each one, and sort the vector so that we can efficiently
1873 // create a binary search tree from them.
1875 unsigned numCmps = Clusterify(Cases, SI);
1876 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1877 << ". Total compares: " << numCmps << "\n";
1879 // Get the Value to be switched on and default basic blocks, which will be
1880 // inserted into CaseBlock records, representing basic blocks in the binary
1882 Value *SV = SI.getOperand(0);
1884 // Push the initial CaseRec onto the worklist
1885 CaseRecVector WorkList;
1886 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1888 while (!WorkList.empty()) {
1889 // Grab a record representing a case range to process off the worklist
1890 CaseRec CR = WorkList.back();
1891 WorkList.pop_back();
1893 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1896 // If the range has few cases (two or less) emit a series of specific
1898 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1901 // If the switch has more than 5 blocks, and at least 40% dense, and the
1902 // target supports indirect branches, then emit a jump table rather than
1903 // lowering the switch to a binary tree of conditional branches.
1904 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1907 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1908 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1909 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1914 void SelectionDAGLowering::visitSub(User &I) {
1915 // -0.0 - X --> fneg
1916 const Type *Ty = I.getType();
1917 if (isa<VectorType>(Ty)) {
1918 visitVectorBinary(I, ISD::VSUB);
1919 } else if (Ty->isFloatingPoint()) {
1920 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1921 if (CFP->isExactlyValue(-0.0)) {
1922 SDOperand Op2 = getValue(I.getOperand(1));
1923 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1926 visitScalarBinary(I, ISD::FSUB);
1928 visitScalarBinary(I, ISD::SUB);
1931 void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
1932 SDOperand Op1 = getValue(I.getOperand(0));
1933 SDOperand Op2 = getValue(I.getOperand(1));
1935 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1939 SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1940 assert(isa<VectorType>(I.getType()));
1941 const VectorType *Ty = cast<VectorType>(I.getType());
1942 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
1944 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1945 getValue(I.getOperand(0)),
1946 getValue(I.getOperand(1)),
1947 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1951 void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1952 unsigned VectorOp) {
1953 if (isa<VectorType>(I.getType()))
1954 visitVectorBinary(I, VectorOp);
1956 visitScalarBinary(I, ScalarOp);
1959 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1960 SDOperand Op1 = getValue(I.getOperand(0));
1961 SDOperand Op2 = getValue(I.getOperand(1));
1963 if (TLI.getShiftAmountTy() < Op2.getValueType())
1964 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1965 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1966 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1968 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1971 void SelectionDAGLowering::visitICmp(User &I) {
1972 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1973 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1974 predicate = IC->getPredicate();
1975 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1976 predicate = ICmpInst::Predicate(IC->getPredicate());
1977 SDOperand Op1 = getValue(I.getOperand(0));
1978 SDOperand Op2 = getValue(I.getOperand(1));
1979 ISD::CondCode Opcode;
1980 switch (predicate) {
1981 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1982 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1983 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1984 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1985 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1986 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1987 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1988 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1989 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1990 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1992 assert(!"Invalid ICmp predicate value");
1993 Opcode = ISD::SETEQ;
1996 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1999 void SelectionDAGLowering::visitFCmp(User &I) {
2000 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2001 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2002 predicate = FC->getPredicate();
2003 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2004 predicate = FCmpInst::Predicate(FC->getPredicate());
2005 SDOperand Op1 = getValue(I.getOperand(0));
2006 SDOperand Op2 = getValue(I.getOperand(1));
2007 ISD::CondCode Condition, FOC, FPC;
2008 switch (predicate) {
2009 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2010 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2011 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2012 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2013 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2014 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2015 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2016 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2017 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2018 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2019 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2020 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2021 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2022 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2023 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2024 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2026 assert(!"Invalid FCmp predicate value");
2027 FOC = FPC = ISD::SETFALSE;
2030 if (FiniteOnlyFPMath())
2034 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2037 void SelectionDAGLowering::visitSelect(User &I) {
2038 SDOperand Cond = getValue(I.getOperand(0));
2039 SDOperand TrueVal = getValue(I.getOperand(1));
2040 SDOperand FalseVal = getValue(I.getOperand(2));
2041 if (!isa<VectorType>(I.getType())) {
2042 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2043 TrueVal, FalseVal));
2045 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2046 *(TrueVal.Val->op_end()-2),
2047 *(TrueVal.Val->op_end()-1)));
2052 void SelectionDAGLowering::visitTrunc(User &I) {
2053 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2054 SDOperand N = getValue(I.getOperand(0));
2055 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2056 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2059 void SelectionDAGLowering::visitZExt(User &I) {
2060 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2061 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2062 SDOperand N = getValue(I.getOperand(0));
2063 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2064 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2067 void SelectionDAGLowering::visitSExt(User &I) {
2068 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2069 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2070 SDOperand N = getValue(I.getOperand(0));
2071 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2072 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2075 void SelectionDAGLowering::visitFPTrunc(User &I) {
2076 // FPTrunc is never a no-op cast, no need to check
2077 SDOperand N = getValue(I.getOperand(0));
2078 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2079 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2082 void SelectionDAGLowering::visitFPExt(User &I){
2083 // FPTrunc is never a no-op cast, no need to check
2084 SDOperand N = getValue(I.getOperand(0));
2085 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2086 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2089 void SelectionDAGLowering::visitFPToUI(User &I) {
2090 // FPToUI is never a no-op cast, no need to check
2091 SDOperand N = getValue(I.getOperand(0));
2092 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2093 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2096 void SelectionDAGLowering::visitFPToSI(User &I) {
2097 // FPToSI is never a no-op cast, no need to check
2098 SDOperand N = getValue(I.getOperand(0));
2099 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2100 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2103 void SelectionDAGLowering::visitUIToFP(User &I) {
2104 // UIToFP is never a no-op cast, no need to check
2105 SDOperand N = getValue(I.getOperand(0));
2106 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2107 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2110 void SelectionDAGLowering::visitSIToFP(User &I){
2111 // UIToFP is never a no-op cast, no need to check
2112 SDOperand N = getValue(I.getOperand(0));
2113 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2114 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2117 void SelectionDAGLowering::visitPtrToInt(User &I) {
2118 // What to do depends on the size of the integer and the size of the pointer.
2119 // We can either truncate, zero extend, or no-op, accordingly.
2120 SDOperand N = getValue(I.getOperand(0));
2121 MVT::ValueType SrcVT = N.getValueType();
2122 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2124 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2125 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2127 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2128 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2129 setValue(&I, Result);
2132 void SelectionDAGLowering::visitIntToPtr(User &I) {
2133 // What to do depends on the size of the integer and the size of the pointer.
2134 // We can either truncate, zero extend, or no-op, accordingly.
2135 SDOperand N = getValue(I.getOperand(0));
2136 MVT::ValueType SrcVT = N.getValueType();
2137 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2138 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2139 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2141 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2142 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2145 void SelectionDAGLowering::visitBitCast(User &I) {
2146 SDOperand N = getValue(I.getOperand(0));
2147 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2148 if (DestVT == MVT::Vector) {
2149 // This is a cast to a vector from something else.
2150 // Get information about the output vector.
2151 const VectorType *DestTy = cast<VectorType>(I.getType());
2152 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2153 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2154 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2155 DAG.getValueType(EltVT)));
2158 MVT::ValueType SrcVT = N.getValueType();
2159 if (SrcVT == MVT::Vector) {
2160 // This is a cast from a vctor to something else.
2161 // Get information about the input vector.
2162 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
2166 // BitCast assures us that source and destination are the same size so this
2167 // is either a BIT_CONVERT or a no-op.
2168 if (DestVT != N.getValueType())
2169 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2171 setValue(&I, N); // noop cast.
2174 void SelectionDAGLowering::visitInsertElement(User &I) {
2175 SDOperand InVec = getValue(I.getOperand(0));
2176 SDOperand InVal = getValue(I.getOperand(1));
2177 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2178 getValue(I.getOperand(2)));
2180 SDOperand Num = *(InVec.Val->op_end()-2);
2181 SDOperand Typ = *(InVec.Val->op_end()-1);
2182 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2183 InVec, InVal, InIdx, Num, Typ));
2186 void SelectionDAGLowering::visitExtractElement(User &I) {
2187 SDOperand InVec = getValue(I.getOperand(0));
2188 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2189 getValue(I.getOperand(1)));
2190 SDOperand Typ = *(InVec.Val->op_end()-1);
2191 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2192 TLI.getValueType(I.getType()), InVec, InIdx));
2195 void SelectionDAGLowering::visitShuffleVector(User &I) {
2196 SDOperand V1 = getValue(I.getOperand(0));
2197 SDOperand V2 = getValue(I.getOperand(1));
2198 SDOperand Mask = getValue(I.getOperand(2));
2200 SDOperand Num = *(V1.Val->op_end()-2);
2201 SDOperand Typ = *(V2.Val->op_end()-1);
2202 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2203 V1, V2, Mask, Num, Typ));
2207 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2208 SDOperand N = getValue(I.getOperand(0));
2209 const Type *Ty = I.getOperand(0)->getType();
2211 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2214 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2215 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2218 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2219 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2220 getIntPtrConstant(Offset));
2222 Ty = StTy->getElementType(Field);
2224 Ty = cast<SequentialType>(Ty)->getElementType();
2226 // If this is a constant subscript, handle it quickly.
2227 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2228 if (CI->getZExtValue() == 0) continue;
2230 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2231 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2235 // N = N + Idx * ElementSize;
2236 uint64_t ElementSize = TD->getTypeSize(Ty);
2237 SDOperand IdxN = getValue(Idx);
2239 // If the index is smaller or larger than intptr_t, truncate or extend
2241 if (IdxN.getValueType() < N.getValueType()) {
2242 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2243 } else if (IdxN.getValueType() > N.getValueType())
2244 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2246 // If this is a multiply by a power of two, turn it into a shl
2247 // immediately. This is a very common case.
2248 if (isPowerOf2_64(ElementSize)) {
2249 unsigned Amt = Log2_64(ElementSize);
2250 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2251 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2252 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2256 SDOperand Scale = getIntPtrConstant(ElementSize);
2257 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2258 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2264 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2265 // If this is a fixed sized alloca in the entry block of the function,
2266 // allocate it statically on the stack.
2267 if (FuncInfo.StaticAllocaMap.count(&I))
2268 return; // getValue will auto-populate this.
2270 const Type *Ty = I.getAllocatedType();
2271 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
2273 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2276 SDOperand AllocSize = getValue(I.getArraySize());
2277 MVT::ValueType IntPtr = TLI.getPointerTy();
2278 if (IntPtr < AllocSize.getValueType())
2279 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2280 else if (IntPtr > AllocSize.getValueType())
2281 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2283 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2284 getIntPtrConstant(TySize));
2286 // Handle alignment. If the requested alignment is less than or equal to the
2287 // stack alignment, ignore it and round the size of the allocation up to the
2288 // stack alignment size. If the size is greater than the stack alignment, we
2289 // note this in the DYNAMIC_STACKALLOC node.
2290 unsigned StackAlign =
2291 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2292 if (Align <= StackAlign) {
2294 // Add SA-1 to the size.
2295 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2296 getIntPtrConstant(StackAlign-1));
2297 // Mask out the low bits for alignment purposes.
2298 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2299 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2302 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
2303 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2305 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2307 DAG.setRoot(DSA.getValue(1));
2309 // Inform the Frame Information that we have just allocated a variable-sized
2311 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2314 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2315 SDOperand Ptr = getValue(I.getOperand(0));
2321 // Do not serialize non-volatile loads against each other.
2322 Root = DAG.getRoot();
2325 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2326 Root, I.isVolatile(), I.getAlignment()));
2329 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2330 const Value *SV, SDOperand Root,
2332 unsigned Alignment) {
2334 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
2335 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
2336 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2337 DAG.getSrcValue(SV));
2339 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2340 isVolatile, Alignment);
2344 DAG.setRoot(L.getValue(1));
2346 PendingLoads.push_back(L.getValue(1));
2352 void SelectionDAGLowering::visitStore(StoreInst &I) {
2353 Value *SrcV = I.getOperand(0);
2354 SDOperand Src = getValue(SrcV);
2355 SDOperand Ptr = getValue(I.getOperand(1));
2356 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2357 I.isVolatile(), I.getAlignment()));
2360 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2361 /// access memory and has no other side effects at all.
2362 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2363 #define GET_NO_MEMORY_INTRINSICS
2364 #include "llvm/Intrinsics.gen"
2365 #undef GET_NO_MEMORY_INTRINSICS
2369 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2370 // have any side-effects or if it only reads memory.
2371 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2372 #define GET_SIDE_EFFECT_INFO
2373 #include "llvm/Intrinsics.gen"
2374 #undef GET_SIDE_EFFECT_INFO
2378 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2380 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2381 unsigned Intrinsic) {
2382 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
2383 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
2385 // Build the operand list.
2386 SmallVector<SDOperand, 8> Ops;
2387 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2389 // We don't need to serialize loads against other loads.
2390 Ops.push_back(DAG.getRoot());
2392 Ops.push_back(getRoot());
2396 // Add the intrinsic ID as an integer operand.
2397 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2399 // Add all operands of the call to the operand list.
2400 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2401 SDOperand Op = getValue(I.getOperand(i));
2403 // If this is a vector type, force it to the right vector type.
2404 if (Op.getValueType() == MVT::Vector) {
2405 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
2406 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2408 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2409 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2410 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2413 assert(TLI.isTypeLegal(Op.getValueType()) &&
2414 "Intrinsic uses a non-legal type?");
2418 std::vector<MVT::ValueType> VTs;
2419 if (I.getType() != Type::VoidTy) {
2420 MVT::ValueType VT = TLI.getValueType(I.getType());
2421 if (VT == MVT::Vector) {
2422 const VectorType *DestTy = cast<VectorType>(I.getType());
2423 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2425 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2426 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2429 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2433 VTs.push_back(MVT::Other);
2435 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2440 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2441 &Ops[0], Ops.size());
2442 else if (I.getType() != Type::VoidTy)
2443 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2444 &Ops[0], Ops.size());
2446 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2447 &Ops[0], Ops.size());
2450 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2452 PendingLoads.push_back(Chain);
2456 if (I.getType() != Type::VoidTy) {
2457 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2458 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2459 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2460 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2461 DAG.getValueType(EVT));
2463 setValue(&I, Result);
2467 /// ExtractGlobalVariable - If C is a global variable, or a bitcast of one
2468 /// (possibly constant folded), return it. Otherwise return NULL.
2469 static GlobalVariable *ExtractGlobalVariable (Constant *C) {
2470 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2472 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2473 if (CE->getOpcode() == Instruction::BitCast)
2474 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2475 else if (CE->getOpcode() == Instruction::GetElementPtr) {
2476 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2477 if (!CE->getOperand(i)->isNullValue())
2479 return dyn_cast<GlobalVariable>(CE->getOperand(0));
2485 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2486 /// we want to emit this as a call to a named external function, return the name
2487 /// otherwise lower it and return null.
2489 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2490 switch (Intrinsic) {
2492 // By default, turn this into a target intrinsic node.
2493 visitTargetIntrinsic(I, Intrinsic);
2495 case Intrinsic::vastart: visitVAStart(I); return 0;
2496 case Intrinsic::vaend: visitVAEnd(I); return 0;
2497 case Intrinsic::vacopy: visitVACopy(I); return 0;
2498 case Intrinsic::returnaddress:
2499 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2500 getValue(I.getOperand(1))));
2502 case Intrinsic::frameaddress:
2503 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2504 getValue(I.getOperand(1))));
2506 case Intrinsic::setjmp:
2507 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2509 case Intrinsic::longjmp:
2510 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2512 case Intrinsic::memcpy_i32:
2513 case Intrinsic::memcpy_i64:
2514 visitMemIntrinsic(I, ISD::MEMCPY);
2516 case Intrinsic::memset_i32:
2517 case Intrinsic::memset_i64:
2518 visitMemIntrinsic(I, ISD::MEMSET);
2520 case Intrinsic::memmove_i32:
2521 case Intrinsic::memmove_i64:
2522 visitMemIntrinsic(I, ISD::MEMMOVE);
2525 case Intrinsic::dbg_stoppoint: {
2526 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2527 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2528 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2532 Ops[1] = getValue(SPI.getLineValue());
2533 Ops[2] = getValue(SPI.getColumnValue());
2535 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2536 assert(DD && "Not a debug information descriptor");
2537 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2539 Ops[3] = DAG.getString(CompileUnit->getFileName());
2540 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2542 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2547 case Intrinsic::dbg_region_start: {
2548 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2549 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2550 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2551 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2552 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2553 DAG.getConstant(LabelID, MVT::i32)));
2558 case Intrinsic::dbg_region_end: {
2559 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2560 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2561 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2562 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2563 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2564 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2569 case Intrinsic::dbg_func_start: {
2570 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2571 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2572 if (MMI && FSI.getSubprogram() &&
2573 MMI->Verify(FSI.getSubprogram())) {
2574 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2575 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2576 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2581 case Intrinsic::dbg_declare: {
2582 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2583 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2584 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2585 SDOperand AddressOp = getValue(DI.getAddress());
2586 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2587 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2593 case Intrinsic::eh_exception: {
2594 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2597 // Add a label to mark the beginning of the landing pad. Deletion of the
2598 // landing pad can thus be detected via the MachineModuleInfo.
2599 unsigned LabelID = MMI->addLandingPad(CurMBB);
2600 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2601 DAG.getConstant(LabelID, MVT::i32)));
2603 // Mark exception register as live in.
2604 unsigned Reg = TLI.getExceptionAddressRegister();
2605 if (Reg) CurMBB->addLiveIn(Reg);
2607 // Insert the EXCEPTIONADDR instruction.
2608 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2610 Ops[0] = DAG.getRoot();
2611 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2613 DAG.setRoot(Op.getValue(1));
2615 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2620 case Intrinsic::eh_selector:
2621 case Intrinsic::eh_filter:{
2622 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2625 // Inform the MachineModuleInfo of the personality for this landing pad.
2626 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2627 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2628 isa<Function>(CE->getOperand(0)) &&
2629 "Personality should be a function");
2630 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
2631 if (Intrinsic == Intrinsic::eh_filter)
2632 MMI->setIsFilterLandingPad(CurMBB);
2634 // Gather all the type infos for this landing pad and pass them along to
2635 // MachineModuleInfo.
2636 std::vector<GlobalVariable *> TyInfo;
2637 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2638 Constant *C = cast<Constant>(I.getOperand(i));
2639 GlobalVariable *GV = ExtractGlobalVariable(C);
2640 assert (GV || (isa<ConstantInt>(C) &&
2641 cast<ConstantInt>(C)->isNullValue()) &&
2642 "TypeInfo must be a global variable or NULL");
2643 TyInfo.push_back(GV);
2645 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2647 // Mark exception selector register as live in.
2648 unsigned Reg = TLI.getExceptionSelectorRegister();
2649 if (Reg) CurMBB->addLiveIn(Reg);
2651 // Insert the EHSELECTION instruction.
2652 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2654 Ops[0] = getValue(I.getOperand(1));
2656 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2658 DAG.setRoot(Op.getValue(1));
2660 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2666 case Intrinsic::eh_typeid_for: {
2667 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2670 // Find the type id for the given typeinfo.
2671 Constant *C = cast<Constant>(I.getOperand(1));
2672 GlobalVariable *GV = ExtractGlobalVariable(C);
2673 assert (GV || (isa<ConstantInt>(C) &&
2674 cast<ConstantInt>(C)->isNullValue()) &&
2675 "TypeInfo must be a global variable or NULL");
2677 unsigned TypeID = MMI->getTypeIDFor(GV);
2678 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2680 setValue(&I, DAG.getConstant(0, MVT::i32));
2686 case Intrinsic::sqrt_f32:
2687 case Intrinsic::sqrt_f64:
2688 setValue(&I, DAG.getNode(ISD::FSQRT,
2689 getValue(I.getOperand(1)).getValueType(),
2690 getValue(I.getOperand(1))));
2692 case Intrinsic::powi_f32:
2693 case Intrinsic::powi_f64:
2694 setValue(&I, DAG.getNode(ISD::FPOWI,
2695 getValue(I.getOperand(1)).getValueType(),
2696 getValue(I.getOperand(1)),
2697 getValue(I.getOperand(2))));
2699 case Intrinsic::pcmarker: {
2700 SDOperand Tmp = getValue(I.getOperand(1));
2701 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2704 case Intrinsic::readcyclecounter: {
2705 SDOperand Op = getRoot();
2706 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2707 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2710 DAG.setRoot(Tmp.getValue(1));
2713 case Intrinsic::part_select: {
2714 // Currently not implemented: just abort
2715 assert(0 && "part_select intrinsic not implemented");
2718 case Intrinsic::part_set: {
2719 // Currently not implemented: just abort
2720 assert(0 && "part_set intrinsic not implemented");
2723 case Intrinsic::bswap:
2724 setValue(&I, DAG.getNode(ISD::BSWAP,
2725 getValue(I.getOperand(1)).getValueType(),
2726 getValue(I.getOperand(1))));
2728 case Intrinsic::cttz: {
2729 SDOperand Arg = getValue(I.getOperand(1));
2730 MVT::ValueType Ty = Arg.getValueType();
2731 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2733 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2734 else if (Ty > MVT::i32)
2735 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2736 setValue(&I, result);
2739 case Intrinsic::ctlz: {
2740 SDOperand Arg = getValue(I.getOperand(1));
2741 MVT::ValueType Ty = Arg.getValueType();
2742 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2744 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2745 else if (Ty > MVT::i32)
2746 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2747 setValue(&I, result);
2750 case Intrinsic::ctpop: {
2751 SDOperand Arg = getValue(I.getOperand(1));
2752 MVT::ValueType Ty = Arg.getValueType();
2753 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2755 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2756 else if (Ty > MVT::i32)
2757 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2758 setValue(&I, result);
2761 case Intrinsic::stacksave: {
2762 SDOperand Op = getRoot();
2763 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2764 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2766 DAG.setRoot(Tmp.getValue(1));
2769 case Intrinsic::stackrestore: {
2770 SDOperand Tmp = getValue(I.getOperand(1));
2771 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2774 case Intrinsic::prefetch:
2775 // FIXME: Currently discarding prefetches.
2781 void SelectionDAGLowering::LowerCallTo(Instruction &I,
2782 const Type *CalledValueTy,
2783 unsigned CallingConv,
2785 SDOperand Callee, unsigned OpIdx) {
2786 const PointerType *PT = cast<PointerType>(CalledValueTy);
2787 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2788 const ParamAttrsList *Attrs = FTy->getParamAttrs();
2790 TargetLowering::ArgListTy Args;
2791 TargetLowering::ArgListEntry Entry;
2792 Args.reserve(I.getNumOperands());
2793 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2794 Value *Arg = I.getOperand(i);
2795 SDOperand ArgNode = getValue(Arg);
2796 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2798 unsigned attrInd = i - OpIdx + 1;
2799 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2800 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2801 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2802 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
2803 Args.push_back(Entry);
2806 std::pair<SDOperand,SDOperand> Result =
2807 TLI.LowerCallTo(getRoot(), I.getType(),
2808 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
2809 FTy->isVarArg(), CallingConv, IsTailCall,
2811 if (I.getType() != Type::VoidTy)
2812 setValue(&I, Result.first);
2813 DAG.setRoot(Result.second);
2817 void SelectionDAGLowering::visitCall(CallInst &I) {
2818 const char *RenameFn = 0;
2819 if (Function *F = I.getCalledFunction()) {
2820 if (F->isDeclaration())
2821 if (unsigned IID = F->getIntrinsicID()) {
2822 RenameFn = visitIntrinsicCall(I, IID);
2825 } else { // Not an LLVM intrinsic.
2826 const std::string &Name = F->getName();
2827 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2828 if (I.getNumOperands() == 3 && // Basic sanity checks.
2829 I.getOperand(1)->getType()->isFloatingPoint() &&
2830 I.getType() == I.getOperand(1)->getType() &&
2831 I.getType() == I.getOperand(2)->getType()) {
2832 SDOperand LHS = getValue(I.getOperand(1));
2833 SDOperand RHS = getValue(I.getOperand(2));
2834 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2838 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2839 if (I.getNumOperands() == 2 && // Basic sanity checks.
2840 I.getOperand(1)->getType()->isFloatingPoint() &&
2841 I.getType() == I.getOperand(1)->getType()) {
2842 SDOperand Tmp = getValue(I.getOperand(1));
2843 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2846 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2847 if (I.getNumOperands() == 2 && // Basic sanity checks.
2848 I.getOperand(1)->getType()->isFloatingPoint() &&
2849 I.getType() == I.getOperand(1)->getType()) {
2850 SDOperand Tmp = getValue(I.getOperand(1));
2851 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2854 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2855 if (I.getNumOperands() == 2 && // Basic sanity checks.
2856 I.getOperand(1)->getType()->isFloatingPoint() &&
2857 I.getType() == I.getOperand(1)->getType()) {
2858 SDOperand Tmp = getValue(I.getOperand(1));
2859 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2864 } else if (isa<InlineAsm>(I.getOperand(0))) {
2871 Callee = getValue(I.getOperand(0));
2873 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2875 LowerCallTo(I, I.getCalledValue()->getType(),
2883 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2884 SDOperand &Chain, SDOperand &Flag)const{
2885 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2886 Chain = Val.getValue(1);
2887 Flag = Val.getValue(2);
2889 // If the result was expanded, copy from the top part.
2890 if (Regs.size() > 1) {
2891 assert(Regs.size() == 2 &&
2892 "Cannot expand to more than 2 elts yet!");
2893 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2894 Chain = Hi.getValue(1);
2895 Flag = Hi.getValue(2);
2896 if (DAG.getTargetLoweringInfo().isLittleEndian())
2897 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2899 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2902 // Otherwise, if the return value was promoted or extended, truncate it to the
2903 // appropriate type.
2904 if (RegVT == ValueVT)
2907 if (MVT::isVector(RegVT)) {
2908 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2909 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2910 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2912 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2915 if (MVT::isInteger(RegVT)) {
2916 if (ValueVT < RegVT)
2917 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2919 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2922 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2923 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2926 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2927 /// specified value into the registers specified by this object. This uses
2928 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2929 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2930 SDOperand &Chain, SDOperand &Flag,
2931 MVT::ValueType PtrVT) const {
2932 if (Regs.size() == 1) {
2933 // If there is a single register and the types differ, this must be
2935 if (RegVT != ValueVT) {
2936 if (MVT::isVector(RegVT)) {
2937 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2938 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
2939 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
2940 if (RegVT < ValueVT)
2941 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2943 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2944 } else if (MVT::isFloatingPoint(RegVT) &&
2945 MVT::isFloatingPoint(Val.getValueType())) {
2946 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2947 } else if (MVT::getSizeInBits(RegVT) ==
2948 MVT::getSizeInBits(Val.getValueType())) {
2949 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2951 assert(0 && "Unknown mismatch!");
2954 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2955 Flag = Chain.getValue(1);
2957 std::vector<unsigned> R(Regs);
2958 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2959 std::reverse(R.begin(), R.end());
2961 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2962 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2963 DAG.getConstant(i, PtrVT));
2964 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2965 Flag = Chain.getValue(1);
2970 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2971 /// operand list. This adds the code marker and includes the number of
2972 /// values added into it.
2973 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2974 std::vector<SDOperand> &Ops) const {
2975 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2976 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
2977 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2978 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2981 /// isAllocatableRegister - If the specified register is safe to allocate,
2982 /// i.e. it isn't a stack pointer or some other special register, return the
2983 /// register class for the register. Otherwise, return null.
2984 static const TargetRegisterClass *
2985 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2986 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2987 MVT::ValueType FoundVT = MVT::Other;
2988 const TargetRegisterClass *FoundRC = 0;
2989 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2990 E = MRI->regclass_end(); RCI != E; ++RCI) {
2991 MVT::ValueType ThisVT = MVT::Other;
2993 const TargetRegisterClass *RC = *RCI;
2994 // If none of the the value types for this register class are valid, we
2995 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2996 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2998 if (TLI.isTypeLegal(*I)) {
2999 // If we have already found this register in a different register class,
3000 // choose the one with the largest VT specified. For example, on
3001 // PowerPC, we favor f64 register classes over f32.
3002 if (FoundVT == MVT::Other ||
3003 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3010 if (ThisVT == MVT::Other) continue;
3012 // NOTE: This isn't ideal. In particular, this might allocate the
3013 // frame pointer in functions that need it (due to them not being taken
3014 // out of allocation, because a variable sized allocation hasn't been seen
3015 // yet). This is a slight code pessimization, but should still work.
3016 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3017 E = RC->allocation_order_end(MF); I != E; ++I)
3019 // We found a matching register class. Keep looking at others in case
3020 // we find one with larger registers that this physreg is also in.
3031 /// AsmOperandInfo - This contains information for each constraint that we are
3033 struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3034 /// ConstraintCode - This contains the actual string for the code, like "m".
3035 std::string ConstraintCode;
3037 /// ConstraintType - Information about the constraint code, e.g. Register,
3038 /// RegisterClass, Memory, Other, Unknown.
3039 TargetLowering::ConstraintType ConstraintType;
3041 /// CallOperand/CallOperandval - If this is the result output operand or a
3042 /// clobber, this is null, otherwise it is the incoming operand to the
3043 /// CallInst. This gets modified as the asm is processed.
3044 SDOperand CallOperand;
3045 Value *CallOperandVal;
3047 /// ConstraintVT - The ValueType for the operand value.
3048 MVT::ValueType ConstraintVT;
3050 /// AssignedRegs - If this is a register or register class operand, this
3051 /// contains the set of register corresponding to the operand.
3052 RegsForValue AssignedRegs;
3054 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3055 : InlineAsm::ConstraintInfo(info),
3056 ConstraintType(TargetLowering::C_Unknown),
3057 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3060 void ComputeConstraintToUse(const TargetLowering &TLI);
3062 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3063 /// busy in OutputRegs/InputRegs.
3064 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3065 std::set<unsigned> &OutputRegs,
3066 std::set<unsigned> &InputRegs) const {
3068 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3070 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3073 } // end anon namespace.
3075 /// getConstraintGenerality - Return an integer indicating how general CT is.
3076 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3078 default: assert(0 && "Unknown constraint type!");
3079 case TargetLowering::C_Other:
3080 case TargetLowering::C_Unknown:
3082 case TargetLowering::C_Register:
3084 case TargetLowering::C_RegisterClass:
3086 case TargetLowering::C_Memory:
3091 void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3092 assert(!Codes.empty() && "Must have at least one constraint");
3094 std::string *Current = &Codes[0];
3095 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3096 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3097 ConstraintCode = *Current;
3098 ConstraintType = CurType;
3102 unsigned CurGenerality = getConstraintGenerality(CurType);
3104 // If we have multiple constraints, try to pick the most general one ahead
3105 // of time. This isn't a wonderful solution, but handles common cases.
3106 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3107 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3108 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3109 if (ThisGenerality > CurGenerality) {
3110 // This constraint letter is more general than the previous one,
3113 Current = &Codes[j];
3114 CurGenerality = ThisGenerality;
3118 ConstraintCode = *Current;
3119 ConstraintType = CurType;
3123 void SelectionDAGLowering::
3124 GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
3125 std::set<unsigned> &OutputRegs,
3126 std::set<unsigned> &InputRegs) {
3127 // Compute whether this value requires an input register, an output register,
3129 bool isOutReg = false;
3130 bool isInReg = false;
3131 switch (OpInfo.Type) {
3132 case InlineAsm::isOutput:
3135 // If this is an early-clobber output, or if there is an input
3136 // constraint that matches this, we need to reserve the input register
3137 // so no other inputs allocate to it.
3138 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3140 case InlineAsm::isInput:
3144 case InlineAsm::isClobber:
3151 MachineFunction &MF = DAG.getMachineFunction();
3152 std::vector<unsigned> Regs;
3154 // If this is a constraint for a single physreg, or a constraint for a
3155 // register class, find it.
3156 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3157 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3158 OpInfo.ConstraintVT);
3160 unsigned NumRegs = 1;
3161 if (OpInfo.ConstraintVT != MVT::Other)
3162 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT);
3163 MVT::ValueType RegVT;
3164 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3167 // If this is a constraint for a specific physical register, like {r17},
3169 if (PhysReg.first) {
3170 if (OpInfo.ConstraintVT == MVT::Other)
3171 ValueVT = *PhysReg.second->vt_begin();
3173 // Get the actual register value type. This is important, because the user
3174 // may have asked for (e.g.) the AX register in i32 type. We need to
3175 // remember that AX is actually i16 to get the right extension.
3176 RegVT = *PhysReg.second->vt_begin();
3178 // This is a explicit reference to a physical register.
3179 Regs.push_back(PhysReg.first);
3181 // If this is an expanded reference, add the rest of the regs to Regs.
3183 TargetRegisterClass::iterator I = PhysReg.second->begin();
3184 TargetRegisterClass::iterator E = PhysReg.second->end();
3185 for (; *I != PhysReg.first; ++I)
3186 assert(I != E && "Didn't find reg!");
3188 // Already added the first reg.
3190 for (; NumRegs; --NumRegs, ++I) {
3191 assert(I != E && "Ran out of registers to allocate!");
3195 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3196 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3200 // Otherwise, if this was a reference to an LLVM register class, create vregs
3201 // for this reference.
3202 std::vector<unsigned> RegClassRegs;
3203 if (PhysReg.second) {
3204 // If this is an early clobber or tied register, our regalloc doesn't know
3205 // how to maintain the constraint. If it isn't, go ahead and create vreg
3206 // and let the regalloc do the right thing.
3207 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3208 // If there is some other early clobber and this is an input register,
3209 // then we are forced to pre-allocate the input reg so it doesn't
3210 // conflict with the earlyclobber.
3211 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3212 RegVT = *PhysReg.second->vt_begin();
3214 if (OpInfo.ConstraintVT == MVT::Other)
3217 // Create the appropriate number of virtual registers.
3218 SSARegMap *RegMap = MF.getSSARegMap();
3219 for (; NumRegs; --NumRegs)
3220 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3222 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3223 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3227 // Otherwise, we can't allocate it. Let the code below figure out how to
3228 // maintain these constraints.
3229 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3232 // This is a reference to a register class that doesn't directly correspond
3233 // to an LLVM register class. Allocate NumRegs consecutive, available,
3234 // registers from the class.
3235 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3236 OpInfo.ConstraintVT);
3239 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3240 unsigned NumAllocated = 0;
3241 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3242 unsigned Reg = RegClassRegs[i];
3243 // See if this register is available.
3244 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3245 (isInReg && InputRegs.count(Reg))) { // Already used.
3246 // Make sure we find consecutive registers.
3251 // Check to see if this register is allocatable (i.e. don't give out the
3253 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3255 // Make sure we find consecutive registers.
3260 // Okay, this register is good, we can use it.
3263 // If we allocated enough consecutive registers, succeed.
3264 if (NumAllocated == NumRegs) {
3265 unsigned RegStart = (i-NumAllocated)+1;
3266 unsigned RegEnd = i+1;
3267 // Mark all of the allocated registers used.
3268 for (unsigned i = RegStart; i != RegEnd; ++i)
3269 Regs.push_back(RegClassRegs[i]);
3271 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3272 OpInfo.ConstraintVT);
3273 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3278 // Otherwise, we couldn't allocate enough registers for this.
3283 /// visitInlineAsm - Handle a call to an InlineAsm object.
3285 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3286 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3288 /// ConstraintOperands - Information about all of the constraints.
3289 std::vector<AsmOperandInfo> ConstraintOperands;
3291 SDOperand Chain = getRoot();
3294 std::set<unsigned> OutputRegs, InputRegs;
3296 // Do a prepass over the constraints, canonicalizing them, and building up the
3297 // ConstraintOperands list.
3298 std::vector<InlineAsm::ConstraintInfo>
3299 ConstraintInfos = IA->ParseConstraints();
3301 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3302 // constraint. If so, we can't let the register allocator allocate any input
3303 // registers, because it will not know to avoid the earlyclobbered output reg.
3304 bool SawEarlyClobber = false;
3306 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
3307 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3308 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3309 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3311 MVT::ValueType OpVT = MVT::Other;
3313 // Compute the value type for each operand.
3314 switch (OpInfo.Type) {
3315 case InlineAsm::isOutput:
3316 if (!OpInfo.isIndirect) {
3317 // The return value of the call is this value. As such, there is no
3318 // corresponding argument.
3319 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3320 OpVT = TLI.getValueType(I.getType());
3322 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3325 case InlineAsm::isInput:
3326 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3328 case InlineAsm::isClobber:
3333 // If this is an input or an indirect output, process the call argument.
3334 if (OpInfo.CallOperandVal) {
3335 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3336 const Type *OpTy = OpInfo.CallOperandVal->getType();
3337 // If this is an indirect operand, the operand is a pointer to the
3339 if (OpInfo.isIndirect)
3340 OpTy = cast<PointerType>(OpTy)->getElementType();
3342 // If OpTy is not a first-class value, it may be a struct/union that we
3343 // can tile with integers.
3344 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3345 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3353 OpTy = IntegerType::get(BitSize);
3358 OpVT = TLI.getValueType(OpTy, true);
3361 OpInfo.ConstraintVT = OpVT;
3363 // Compute the constraint code and ConstraintType to use.
3364 OpInfo.ComputeConstraintToUse(TLI);
3366 // Keep track of whether we see an earlyclobber.
3367 SawEarlyClobber |= OpInfo.isEarlyClobber;
3369 // If this is a memory input, and if the operand is not indirect, do what we
3370 // need to to provide an address for the memory input.
3371 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3372 !OpInfo.isIndirect) {
3373 assert(OpInfo.Type == InlineAsm::isInput &&
3374 "Can only indirectify direct input operands!");
3376 // Memory operands really want the address of the value. If we don't have
3377 // an indirect input, put it in the constpool if we can, otherwise spill
3378 // it to a stack slot.
3380 // If the operand is a float, integer, or vector constant, spill to a
3381 // constant pool entry to get its address.
3382 Value *OpVal = OpInfo.CallOperandVal;
3383 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3384 isa<ConstantVector>(OpVal)) {
3385 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3386 TLI.getPointerTy());
3388 // Otherwise, create a stack slot and emit a store to it before the
3390 const Type *Ty = OpVal->getType();
3391 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3392 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3393 MachineFunction &MF = DAG.getMachineFunction();
3394 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3395 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3396 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3397 OpInfo.CallOperand = StackSlot;
3400 // There is no longer a Value* corresponding to this operand.
3401 OpInfo.CallOperandVal = 0;
3402 // It is now an indirect operand.
3403 OpInfo.isIndirect = true;
3406 // If this constraint is for a specific register, allocate it before
3408 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3409 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3411 ConstraintInfos.clear();
3414 // Second pass - Loop over all of the operands, assigning virtual or physregs
3415 // to registerclass operands.
3416 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3417 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3419 // C_Register operands have already been allocated, Other/Memory don't need
3421 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3422 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3425 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3426 std::vector<SDOperand> AsmNodeOperands;
3427 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3428 AsmNodeOperands.push_back(
3429 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3432 // Loop over all of the inputs, copying the operand values into the
3433 // appropriate registers and processing the output regs.
3434 RegsForValue RetValRegs;
3436 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3437 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3439 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3440 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3442 switch (OpInfo.Type) {
3443 case InlineAsm::isOutput: {
3444 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3445 OpInfo.ConstraintType != TargetLowering::C_Register) {
3446 // Memory output, or 'other' output (e.g. 'X' constraint).
3447 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3449 // Add information to the INLINEASM node to know about this output.
3450 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3451 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3452 TLI.getPointerTy()));
3453 AsmNodeOperands.push_back(OpInfo.CallOperand);
3457 // Otherwise, this is a register or register class output.
3459 // Copy the output from the appropriate register. Find a register that
3461 if (OpInfo.AssignedRegs.Regs.empty()) {
3462 cerr << "Couldn't allocate output reg for contraint '"
3463 << OpInfo.ConstraintCode << "'!\n";
3467 if (!OpInfo.isIndirect) {
3468 // This is the result value of the call.
3469 assert(RetValRegs.Regs.empty() &&
3470 "Cannot have multiple output constraints yet!");
3471 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3472 RetValRegs = OpInfo.AssignedRegs;
3474 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3475 OpInfo.CallOperandVal));
3478 // Add information to the INLINEASM node to know that this register is
3480 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3484 case InlineAsm::isInput: {
3485 SDOperand InOperandVal = OpInfo.CallOperand;
3487 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3488 // If this is required to match an output register we have already set,
3489 // just use its register.
3490 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3492 // Scan until we find the definition we already emitted of this operand.
3493 // When we find it, create a RegsForValue operand.
3494 unsigned CurOp = 2; // The first operand.
3495 for (; OperandNo; --OperandNo) {
3496 // Advance to the next operand.
3498 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3499 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3500 (NumOps & 7) == 4 /*MEM*/) &&
3501 "Skipped past definitions?");
3502 CurOp += (NumOps>>3)+1;
3506 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3507 if ((NumOps & 7) == 2 /*REGDEF*/) {
3508 // Add NumOps>>3 registers to MatchedRegs.
3509 RegsForValue MatchedRegs;
3510 MatchedRegs.ValueVT = InOperandVal.getValueType();
3511 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3512 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3514 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3515 MatchedRegs.Regs.push_back(Reg);
3518 // Use the produced MatchedRegs object to
3519 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3520 TLI.getPointerTy());
3521 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3524 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3525 assert(0 && "matching constraints for memory operands unimp");
3529 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
3530 assert(!OpInfo.isIndirect &&
3531 "Don't know how to handle indirect other inputs yet!");
3533 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
3534 OpInfo.ConstraintCode[0],
3536 if (!InOperandVal.Val) {
3537 cerr << "Invalid operand for inline asm constraint '"
3538 << OpInfo.ConstraintCode << "'!\n";
3542 // Add information to the INLINEASM node to know about this input.
3543 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3544 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3545 TLI.getPointerTy()));
3546 AsmNodeOperands.push_back(InOperandVal);
3548 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
3549 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
3550 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3551 "Memory operands expect pointer values");
3553 // Add information to the INLINEASM node to know about this input.
3554 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3555 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3556 TLI.getPointerTy()));
3557 AsmNodeOperands.push_back(InOperandVal);
3561 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3562 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3563 "Unknown constraint type!");
3564 assert(!OpInfo.isIndirect &&
3565 "Don't know how to handle indirect register inputs yet!");
3567 // Copy the input into the appropriate registers.
3568 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3569 "Couldn't allocate input reg!");
3571 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3572 TLI.getPointerTy());
3574 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3578 case InlineAsm::isClobber: {
3579 // Add the clobbered value to the operand list, so that the register
3580 // allocator is aware that the physreg got clobbered.
3581 if (!OpInfo.AssignedRegs.Regs.empty())
3582 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3589 // Finish up input operands.
3590 AsmNodeOperands[0] = Chain;
3591 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3593 Chain = DAG.getNode(ISD::INLINEASM,
3594 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3595 &AsmNodeOperands[0], AsmNodeOperands.size());
3596 Flag = Chain.getValue(1);
3598 // If this asm returns a register value, copy the result from that register
3599 // and set it as the value of the call.
3600 if (!RetValRegs.Regs.empty()) {
3601 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3603 // If the result of the inline asm is a vector, it may have the wrong
3604 // width/num elts. Make sure to convert it to the right type with
3606 if (Val.getValueType() == MVT::Vector) {
3607 const VectorType *VTy = cast<VectorType>(I.getType());
3608 unsigned DesiredNumElts = VTy->getNumElements();
3609 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3611 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3612 DAG.getConstant(DesiredNumElts, MVT::i32),
3613 DAG.getValueType(DesiredEltVT));
3619 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3621 // Process indirect outputs, first output all of the flagged copies out of
3623 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3624 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3625 Value *Ptr = IndirectStoresToEmit[i].second;
3626 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3627 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
3630 // Emit the non-flagged stores from the physregs.
3631 SmallVector<SDOperand, 8> OutChains;
3632 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
3633 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
3634 getValue(StoresToEmit[i].second),
3635 StoresToEmit[i].second, 0));
3636 if (!OutChains.empty())
3637 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3638 &OutChains[0], OutChains.size());
3643 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3644 SDOperand Src = getValue(I.getOperand(0));
3646 MVT::ValueType IntPtr = TLI.getPointerTy();
3648 if (IntPtr < Src.getValueType())
3649 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3650 else if (IntPtr > Src.getValueType())
3651 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
3653 // Scale the source by the type size.
3654 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
3655 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3656 Src, getIntPtrConstant(ElementSize));
3658 TargetLowering::ArgListTy Args;
3659 TargetLowering::ArgListEntry Entry;
3661 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3662 Args.push_back(Entry);
3664 std::pair<SDOperand,SDOperand> Result =
3665 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
3666 DAG.getExternalSymbol("malloc", IntPtr),
3668 setValue(&I, Result.first); // Pointers always fit in registers
3669 DAG.setRoot(Result.second);
3672 void SelectionDAGLowering::visitFree(FreeInst &I) {
3673 TargetLowering::ArgListTy Args;
3674 TargetLowering::ArgListEntry Entry;
3675 Entry.Node = getValue(I.getOperand(0));
3676 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3677 Args.push_back(Entry);
3678 MVT::ValueType IntPtr = TLI.getPointerTy();
3679 std::pair<SDOperand,SDOperand> Result =
3680 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3681 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3682 DAG.setRoot(Result.second);
3685 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
3686 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3687 // instructions are special in various ways, which require special support to
3688 // insert. The specified MachineInstr is created but not inserted into any
3689 // basic blocks, and the scheduler passes ownership of it to this method.
3690 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3691 MachineBasicBlock *MBB) {
3692 cerr << "If a target marks an instruction with "
3693 << "'usesCustomDAGSchedInserter', it must implement "
3694 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3699 void SelectionDAGLowering::visitVAStart(CallInst &I) {
3700 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3701 getValue(I.getOperand(1)),
3702 DAG.getSrcValue(I.getOperand(1))));
3705 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3706 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3707 getValue(I.getOperand(0)),
3708 DAG.getSrcValue(I.getOperand(0)));
3710 DAG.setRoot(V.getValue(1));
3713 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3714 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3715 getValue(I.getOperand(1)),
3716 DAG.getSrcValue(I.getOperand(1))));
3719 void SelectionDAGLowering::visitVACopy(CallInst &I) {
3720 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3721 getValue(I.getOperand(1)),
3722 getValue(I.getOperand(2)),
3723 DAG.getSrcValue(I.getOperand(1)),
3724 DAG.getSrcValue(I.getOperand(2))));
3727 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3728 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3729 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3730 unsigned &i, SelectionDAG &DAG,
3731 TargetLowering &TLI) {
3732 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3733 return SDOperand(Arg, i++);
3735 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3736 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3738 return DAG.getNode(ISD::BIT_CONVERT, VT,
3739 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3740 } else if (NumVals == 2) {
3741 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3742 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3743 if (!TLI.isLittleEndian())
3745 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3747 // Value scalarized into many values. Unimp for now.
3748 assert(0 && "Cannot expand i64 -> i16 yet!");
3753 /// TargetLowering::LowerArguments - This is the default LowerArguments
3754 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3755 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3756 /// integrated into SDISel.
3757 std::vector<SDOperand>
3758 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3759 const FunctionType *FTy = F.getFunctionType();
3760 const ParamAttrsList *Attrs = FTy->getParamAttrs();
3761 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3762 std::vector<SDOperand> Ops;
3763 Ops.push_back(DAG.getRoot());
3764 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3765 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3767 // Add one result value for each formal argument.
3768 std::vector<MVT::ValueType> RetVals;
3770 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3772 MVT::ValueType VT = getValueType(I->getType());
3773 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3774 unsigned OriginalAlignment =
3775 getTargetData()->getABITypeAlignment(I->getType());
3777 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3778 // that is zero extended!
3779 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
3780 Flags &= ~(ISD::ParamFlags::SExt);
3781 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
3782 Flags |= ISD::ParamFlags::SExt;
3783 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
3784 Flags |= ISD::ParamFlags::InReg;
3785 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
3786 Flags |= ISD::ParamFlags::StructReturn;
3787 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
3789 switch (getTypeAction(VT)) {
3790 default: assert(0 && "Unknown type action!");
3792 RetVals.push_back(VT);
3793 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3796 RetVals.push_back(getTypeToTransformTo(VT));
3797 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3800 if (VT != MVT::Vector) {
3801 // If this is a large integer, it needs to be broken up into small
3802 // integers. Figure out what the destination type is and how many small
3803 // integers it turns into.
3804 MVT::ValueType NVT = getTypeToExpandTo(VT);
3805 unsigned NumVals = getNumElements(VT);
3806 for (unsigned i = 0; i != NumVals; ++i) {
3807 RetVals.push_back(NVT);
3808 // if it isn't first piece, alignment must be 1
3810 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3811 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3812 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3815 // Otherwise, this is a vector type. We only support legal vectors
3817 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3818 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
3820 // Figure out if there is a Packed type corresponding to this Vector
3821 // type. If so, convert to the vector type.
3822 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3823 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3824 RetVals.push_back(TVT);
3825 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3827 assert(0 && "Don't support illegal by-val vector arguments yet!");
3834 RetVals.push_back(MVT::Other);
3837 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3838 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3839 &Ops[0], Ops.size()).Val;
3841 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
3843 // Set up the return result vector.
3847 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3849 MVT::ValueType VT = getValueType(I->getType());
3851 switch (getTypeAction(VT)) {
3852 default: assert(0 && "Unknown type action!");
3854 Ops.push_back(SDOperand(Result, i++));
3857 SDOperand Op(Result, i++);
3858 if (MVT::isInteger(VT)) {
3859 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
3860 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3861 DAG.getValueType(VT));
3862 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
3863 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3864 DAG.getValueType(VT));
3865 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3867 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3868 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3874 if (VT != MVT::Vector) {
3875 // If this is a large integer or a floating point node that needs to be
3876 // expanded, it needs to be reassembled from small integers. Figure out
3877 // what the source elt type is and how many small integers it is.
3878 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
3880 // Otherwise, this is a vector type. We only support legal vectors
3882 const VectorType *PTy = cast<VectorType>(I->getType());
3883 unsigned NumElems = PTy->getNumElements();
3884 const Type *EltTy = PTy->getElementType();
3886 // Figure out if there is a Packed type corresponding to this Vector
3887 // type. If so, convert to the vector type.
3888 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3889 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3890 SDOperand N = SDOperand(Result, i++);
3891 // Handle copies from generic vectors to registers.
3892 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3893 DAG.getConstant(NumElems, MVT::i32),
3894 DAG.getValueType(getValueType(EltTy)));
3897 assert(0 && "Don't support illegal by-val vector arguments yet!");
3908 /// ExpandScalarCallArgs - Recursively expand call argument node by
3909 /// bit_converting it or extract a pair of elements from the larger node.
3910 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3912 SmallVector<SDOperand, 32> &Ops,
3914 TargetLowering &TLI,
3915 bool isFirst = true) {
3917 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3918 // if it isn't first piece, alignment must be 1
3920 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3921 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3923 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3927 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3928 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3930 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3931 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
3932 } else if (NumVals == 2) {
3933 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3934 DAG.getConstant(0, TLI.getPointerTy()));
3935 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3936 DAG.getConstant(1, TLI.getPointerTy()));
3937 if (!TLI.isLittleEndian())
3939 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3940 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
3942 // Value scalarized into many values. Unimp for now.
3943 assert(0 && "Cannot expand i64 -> i16 yet!");
3947 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3948 /// implementation, which just inserts an ISD::CALL node, which is later custom
3949 /// lowered by the target to something concrete. FIXME: When all targets are
3950 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3951 std::pair<SDOperand, SDOperand>
3952 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3953 bool RetTyIsSigned, bool isVarArg,
3954 unsigned CallingConv, bool isTailCall,
3956 ArgListTy &Args, SelectionDAG &DAG) {
3957 SmallVector<SDOperand, 32> Ops;
3958 Ops.push_back(Chain); // Op#0 - Chain
3959 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3960 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3961 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3962 Ops.push_back(Callee);
3964 // Handle all of the outgoing arguments.
3965 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3966 MVT::ValueType VT = getValueType(Args[i].Ty);
3967 SDOperand Op = Args[i].Node;
3968 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3969 unsigned OriginalAlignment =
3970 getTargetData()->getABITypeAlignment(Args[i].Ty);
3973 Flags |= ISD::ParamFlags::SExt;
3975 Flags |= ISD::ParamFlags::ZExt;
3976 if (Args[i].isInReg)
3977 Flags |= ISD::ParamFlags::InReg;
3979 Flags |= ISD::ParamFlags::StructReturn;
3980 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
3982 switch (getTypeAction(VT)) {
3983 default: assert(0 && "Unknown type action!");
3986 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3989 if (MVT::isInteger(VT)) {
3992 ExtOp = ISD::SIGN_EXTEND;
3993 else if (Args[i].isZExt)
3994 ExtOp = ISD::ZERO_EXTEND;
3996 ExtOp = ISD::ANY_EXTEND;
3997 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3999 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
4000 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
4003 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4006 if (VT != MVT::Vector) {
4007 // If this is a large integer, it needs to be broken down into small
4008 // integers. Figure out what the source elt type is and how many small
4010 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
4012 // Otherwise, this is a vector type. We only support legal vectors
4014 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
4015 unsigned NumElems = PTy->getNumElements();
4016 const Type *EltTy = PTy->getElementType();
4018 // Figure out if there is a Packed type corresponding to this Vector
4019 // type. If so, convert to the vector type.
4020 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4021 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4022 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
4023 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
4025 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4027 assert(0 && "Don't support illegal by-val vector call args yet!");
4035 // Figure out the result value types.
4036 SmallVector<MVT::ValueType, 4> RetTys;
4038 if (RetTy != Type::VoidTy) {
4039 MVT::ValueType VT = getValueType(RetTy);
4040 switch (getTypeAction(VT)) {
4041 default: assert(0 && "Unknown type action!");
4043 RetTys.push_back(VT);
4046 RetTys.push_back(getTypeToTransformTo(VT));
4049 if (VT != MVT::Vector) {
4050 // If this is a large integer, it needs to be reassembled from small
4051 // integers. Figure out what the source elt type is and how many small
4053 MVT::ValueType NVT = getTypeToExpandTo(VT);
4054 unsigned NumVals = getNumElements(VT);
4055 for (unsigned i = 0; i != NumVals; ++i)
4056 RetTys.push_back(NVT);
4058 // Otherwise, this is a vector type. We only support legal vectors
4060 const VectorType *PTy = cast<VectorType>(RetTy);
4061 unsigned NumElems = PTy->getNumElements();
4062 const Type *EltTy = PTy->getElementType();
4064 // Figure out if there is a Packed type corresponding to this Vector
4065 // type. If so, convert to the vector type.
4066 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4067 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4068 RetTys.push_back(TVT);
4070 assert(0 && "Don't support illegal by-val vector call results yet!");
4077 RetTys.push_back(MVT::Other); // Always has a chain.
4079 // Finally, create the CALL node.
4080 SDOperand Res = DAG.getNode(ISD::CALL,
4081 DAG.getVTList(&RetTys[0], RetTys.size()),
4082 &Ops[0], Ops.size());
4084 // This returns a pair of operands. The first element is the
4085 // return value for the function (if RetTy is not VoidTy). The second
4086 // element is the outgoing token chain.
4088 if (RetTys.size() != 1) {
4089 MVT::ValueType VT = getValueType(RetTy);
4090 if (RetTys.size() == 2) {
4093 // If this value was promoted, truncate it down.
4094 if (ResVal.getValueType() != VT) {
4095 if (VT == MVT::Vector) {
4096 // Insert a VBIT_CONVERT to convert from the packed result type to the
4097 // MVT::Vector type.
4098 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4099 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
4101 // Figure out if there is a Packed type corresponding to this Vector
4102 // type. If so, convert to the vector type.
4103 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
4104 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4105 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
4106 // "N x PTyElementVT" MVT::Vector type.
4107 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
4108 DAG.getConstant(NumElems, MVT::i32),
4109 DAG.getValueType(getValueType(EltTy)));
4113 } else if (MVT::isInteger(VT)) {
4114 unsigned AssertOp = ISD::AssertSext;
4116 AssertOp = ISD::AssertZext;
4117 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4118 DAG.getValueType(VT));
4119 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4121 assert(MVT::isFloatingPoint(VT));
4122 if (getTypeAction(VT) == Expand)
4123 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4125 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
4128 } else if (RetTys.size() == 3) {
4129 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4130 Res.getValue(0), Res.getValue(1));
4133 assert(0 && "Case not handled yet!");
4137 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4140 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4141 assert(0 && "LowerOperation not implemented for this target!");
4146 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4147 SelectionDAG &DAG) {
4148 assert(0 && "CustomPromoteOperation not implemented for this target!");
4153 /// getMemsetValue - Vectorized representation of the memset value
4155 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4156 SelectionDAG &DAG) {
4157 MVT::ValueType CurVT = VT;
4158 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4159 uint64_t Val = C->getValue() & 255;
4161 while (CurVT != MVT::i8) {
4162 Val = (Val << Shift) | Val;
4164 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4166 return DAG.getConstant(Val, VT);
4168 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4170 while (CurVT != MVT::i8) {
4172 DAG.getNode(ISD::OR, VT,
4173 DAG.getNode(ISD::SHL, VT, Value,
4174 DAG.getConstant(Shift, MVT::i8)), Value);
4176 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4183 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4184 /// used when a memcpy is turned into a memset when the source is a constant
4186 static SDOperand getMemsetStringVal(MVT::ValueType VT,
4187 SelectionDAG &DAG, TargetLowering &TLI,
4188 std::string &Str, unsigned Offset) {
4190 unsigned MSB = MVT::getSizeInBits(VT) / 8;
4191 if (TLI.isLittleEndian())
4192 Offset = Offset + MSB - 1;
4193 for (unsigned i = 0; i != MSB; ++i) {
4194 Val = (Val << 8) | (unsigned char)Str[Offset];
4195 Offset += TLI.isLittleEndian() ? -1 : 1;
4197 return DAG.getConstant(Val, VT);
4200 /// getMemBasePlusOffset - Returns base and offset node for the
4201 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4202 SelectionDAG &DAG, TargetLowering &TLI) {
4203 MVT::ValueType VT = Base.getValueType();
4204 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4207 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4208 /// to replace the memset / memcpy is below the threshold. It also returns the
4209 /// types of the sequence of memory ops to perform memset / memcpy.
4210 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4211 unsigned Limit, uint64_t Size,
4212 unsigned Align, TargetLowering &TLI) {
4215 if (TLI.allowsUnalignedMemoryAccesses()) {
4218 switch (Align & 7) {
4234 MVT::ValueType LVT = MVT::i64;
4235 while (!TLI.isTypeLegal(LVT))
4236 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4237 assert(MVT::isInteger(LVT));
4242 unsigned NumMemOps = 0;
4244 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4245 while (VTSize > Size) {
4246 VT = (MVT::ValueType)((unsigned)VT - 1);
4249 assert(MVT::isInteger(VT));
4251 if (++NumMemOps > Limit)
4253 MemOps.push_back(VT);
4260 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4261 SDOperand Op1 = getValue(I.getOperand(1));
4262 SDOperand Op2 = getValue(I.getOperand(2));
4263 SDOperand Op3 = getValue(I.getOperand(3));
4264 SDOperand Op4 = getValue(I.getOperand(4));
4265 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4266 if (Align == 0) Align = 1;
4268 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4269 std::vector<MVT::ValueType> MemOps;
4271 // Expand memset / memcpy to a series of load / store ops
4272 // if the size operand falls below a certain threshold.
4273 SmallVector<SDOperand, 8> OutChains;
4275 default: break; // Do nothing for now.
4277 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4278 Size->getValue(), Align, TLI)) {
4279 unsigned NumMemOps = MemOps.size();
4280 unsigned Offset = 0;
4281 for (unsigned i = 0; i < NumMemOps; i++) {
4282 MVT::ValueType VT = MemOps[i];
4283 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4284 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4285 SDOperand Store = DAG.getStore(getRoot(), Value,
4286 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4287 I.getOperand(1), Offset);
4288 OutChains.push_back(Store);
4295 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4296 Size->getValue(), Align, TLI)) {
4297 unsigned NumMemOps = MemOps.size();
4298 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4299 GlobalAddressSDNode *G = NULL;
4301 bool CopyFromStr = false;
4303 if (Op2.getOpcode() == ISD::GlobalAddress)
4304 G = cast<GlobalAddressSDNode>(Op2);
4305 else if (Op2.getOpcode() == ISD::ADD &&
4306 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4307 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4308 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4309 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4312 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4313 if (GV && GV->isConstant()) {
4314 Str = GV->getStringValue(false);
4322 for (unsigned i = 0; i < NumMemOps; i++) {
4323 MVT::ValueType VT = MemOps[i];
4324 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4325 SDOperand Value, Chain, Store;
4328 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4331 DAG.getStore(Chain, Value,
4332 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4333 I.getOperand(1), DstOff);
4335 Value = DAG.getLoad(VT, getRoot(),
4336 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4337 I.getOperand(2), SrcOff);
4338 Chain = Value.getValue(1);
4340 DAG.getStore(Chain, Value,
4341 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4342 I.getOperand(1), DstOff);
4344 OutChains.push_back(Store);
4353 if (!OutChains.empty()) {
4354 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4355 &OutChains[0], OutChains.size()));
4360 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
4363 //===----------------------------------------------------------------------===//
4364 // SelectionDAGISel code
4365 //===----------------------------------------------------------------------===//
4367 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4368 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4371 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4372 AU.addRequired<AliasAnalysis>();
4373 AU.setPreservesAll();
4378 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4379 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4380 RegMap = MF.getSSARegMap();
4381 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4383 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4385 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4386 SelectBasicBlock(I, MF, FuncInfo);
4388 // Add function live-ins to entry block live-in set.
4389 BasicBlock *EntryBB = &Fn.getEntryBlock();
4390 BB = FuncInfo.MBBMap[EntryBB];
4391 if (!MF.livein_empty())
4392 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4393 E = MF.livein_end(); I != E; ++I)
4394 BB->addLiveIn(I->first);
4399 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4401 SDOperand Op = getValue(V);
4402 assert((Op.getOpcode() != ISD::CopyFromReg ||
4403 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4404 "Copy from a reg to the same reg!");
4406 // If this type is not legal, we must make sure to not create an invalid
4408 MVT::ValueType SrcVT = Op.getValueType();
4409 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
4410 if (SrcVT == DestVT) {
4411 return DAG.getCopyToReg(getRoot(), Reg, Op);
4412 } else if (SrcVT == MVT::Vector) {
4413 // Handle copies from generic vectors to registers.
4414 MVT::ValueType PTyElementVT, PTyLegalElementVT;
4415 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
4416 PTyElementVT, PTyLegalElementVT);
4418 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4419 // MVT::Vector type.
4420 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4421 DAG.getConstant(NE, MVT::i32),
4422 DAG.getValueType(PTyElementVT));
4424 // Loop over all of the elements of the resultant vector,
4425 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4426 // copying them into output registers.
4427 SmallVector<SDOperand, 8> OutChains;
4428 SDOperand Root = getRoot();
4429 for (unsigned i = 0; i != NE; ++i) {
4430 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
4431 Op, DAG.getConstant(i, TLI.getPointerTy()));
4432 if (PTyElementVT == PTyLegalElementVT) {
4433 // Elements are legal.
4434 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4435 } else if (PTyLegalElementVT > PTyElementVT) {
4436 // Elements are promoted.
4437 if (MVT::isFloatingPoint(PTyLegalElementVT))
4438 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4440 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4441 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4443 // Elements are expanded.
4444 // The src value is expanded into multiple registers.
4445 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4446 Elt, DAG.getConstant(0, TLI.getPointerTy()));
4447 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4448 Elt, DAG.getConstant(1, TLI.getPointerTy()));
4449 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4450 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4453 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4454 &OutChains[0], OutChains.size());
4455 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
4456 // The src value is promoted to the register.
4457 if (MVT::isFloatingPoint(SrcVT))
4458 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4460 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
4461 return DAG.getCopyToReg(getRoot(), Reg, Op);
4463 DestVT = TLI.getTypeToExpandTo(SrcVT);
4464 unsigned NumVals = TLI.getNumElements(SrcVT);
4466 return DAG.getCopyToReg(getRoot(), Reg,
4467 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4468 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
4469 // The src value is expanded into multiple registers.
4470 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4471 Op, DAG.getConstant(0, TLI.getPointerTy()));
4472 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4473 Op, DAG.getConstant(1, TLI.getPointerTy()));
4474 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
4475 return DAG.getCopyToReg(Op, Reg+1, Hi);
4479 void SelectionDAGISel::
4480 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4481 std::vector<SDOperand> &UnorderedChains) {
4482 // If this is the entry block, emit arguments.
4483 Function &F = *LLVMBB->getParent();
4484 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4485 SDOperand OldRoot = SDL.DAG.getRoot();
4486 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4489 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4491 if (!AI->use_empty()) {
4492 SDL.setValue(AI, Args[a]);
4494 // If this argument is live outside of the entry block, insert a copy from
4495 // whereever we got it to the vreg that other BB's will reference it as.
4496 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4497 if (VMI != FuncInfo.ValueMap.end()) {
4498 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
4499 UnorderedChains.push_back(Copy);
4503 // Finally, if the target has anything special to do, allow it to do so.
4504 // FIXME: this should insert code into the DAG!
4505 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4508 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4509 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4510 FunctionLoweringInfo &FuncInfo) {
4511 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
4513 std::vector<SDOperand> UnorderedChains;
4515 // Lower any arguments needed in this block if this is the entry block.
4516 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4517 LowerArguments(LLVMBB, SDL, UnorderedChains);
4519 BB = FuncInfo.MBBMap[LLVMBB];
4520 SDL.setCurrentBasicBlock(BB);
4522 // Lower all of the non-terminator instructions.
4523 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4527 // Lower call part of invoke.
4528 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4529 if (Invoke) SDL.visitInvoke(*Invoke, false);
4531 // Ensure that all instructions which are used outside of their defining
4532 // blocks are available as virtual registers.
4533 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4534 if (!I->use_empty() && !isa<PHINode>(I)) {
4535 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4536 if (VMI != FuncInfo.ValueMap.end())
4537 UnorderedChains.push_back(
4538 SDL.CopyValueToVirtualRegister(I, VMI->second));
4541 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4542 // ensure constants are generated when needed. Remember the virtual registers
4543 // that need to be added to the Machine PHI nodes as input. We cannot just
4544 // directly add them, because expansion might result in multiple MBB's for one
4545 // BB. As such, the start of the BB might correspond to a different MBB than
4548 TerminatorInst *TI = LLVMBB->getTerminator();
4550 // Emit constants only once even if used by multiple PHI nodes.
4551 std::map<Constant*, unsigned> ConstantsOut;
4553 // Vector bool would be better, but vector<bool> is really slow.
4554 std::vector<unsigned char> SuccsHandled;
4555 if (TI->getNumSuccessors())
4556 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4558 // Check successor nodes PHI nodes that expect a constant to be available from
4560 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4561 BasicBlock *SuccBB = TI->getSuccessor(succ);
4562 if (!isa<PHINode>(SuccBB->begin())) continue;
4563 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4565 // If this terminator has multiple identical successors (common for
4566 // switches), only handle each succ once.
4567 unsigned SuccMBBNo = SuccMBB->getNumber();
4568 if (SuccsHandled[SuccMBBNo]) continue;
4569 SuccsHandled[SuccMBBNo] = true;
4571 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4574 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4575 // nodes and Machine PHI nodes, but the incoming operands have not been
4577 for (BasicBlock::iterator I = SuccBB->begin();
4578 (PN = dyn_cast<PHINode>(I)); ++I) {
4579 // Ignore dead phi's.
4580 if (PN->use_empty()) continue;
4583 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4585 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4586 unsigned &RegOut = ConstantsOut[C];
4588 RegOut = FuncInfo.CreateRegForValue(C);
4589 UnorderedChains.push_back(
4590 SDL.CopyValueToVirtualRegister(C, RegOut));
4594 Reg = FuncInfo.ValueMap[PHIOp];
4596 assert(isa<AllocaInst>(PHIOp) &&
4597 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4598 "Didn't codegen value into a register!??");
4599 Reg = FuncInfo.CreateRegForValue(PHIOp);
4600 UnorderedChains.push_back(
4601 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4605 // Remember that this register needs to added to the machine PHI node as
4606 // the input for this MBB.
4607 MVT::ValueType VT = TLI.getValueType(PN->getType());
4608 unsigned NumElements;
4609 if (VT != MVT::Vector)
4610 NumElements = TLI.getNumElements(VT);
4612 MVT::ValueType VT1,VT2;
4614 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
4617 for (unsigned i = 0, e = NumElements; i != e; ++i)
4618 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4621 ConstantsOut.clear();
4623 // Turn all of the unordered chains into one factored node.
4624 if (!UnorderedChains.empty()) {
4625 SDOperand Root = SDL.getRoot();
4626 if (Root.getOpcode() != ISD::EntryToken) {
4627 unsigned i = 0, e = UnorderedChains.size();
4628 for (; i != e; ++i) {
4629 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4630 if (UnorderedChains[i].Val->getOperand(0) == Root)
4631 break; // Don't add the root if we already indirectly depend on it.
4635 UnorderedChains.push_back(Root);
4637 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4638 &UnorderedChains[0], UnorderedChains.size()));
4641 // Lower the terminator after the copies are emitted.
4643 // Just the branch part of invoke.
4644 SDL.visitInvoke(*Invoke, true);
4646 SDL.visit(*LLVMBB->getTerminator());
4649 // Copy over any CaseBlock records that may now exist due to SwitchInst
4650 // lowering, as well as any jump table information.
4651 SwitchCases.clear();
4652 SwitchCases = SDL.SwitchCases;
4654 JTCases = SDL.JTCases;
4655 BitTestCases.clear();
4656 BitTestCases = SDL.BitTestCases;
4658 // Make sure the root of the DAG is up-to-date.
4659 DAG.setRoot(SDL.getRoot());
4662 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4663 // Get alias analysis for load/store combining.
4664 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4666 // Run the DAG combiner in pre-legalize mode.
4667 DAG.Combine(false, AA);
4669 DOUT << "Lowered selection DAG:\n";
4672 // Second step, hack on the DAG until it only uses operations and types that
4673 // the target supports.
4676 DOUT << "Legalized selection DAG:\n";
4679 // Run the DAG combiner in post-legalize mode.
4680 DAG.Combine(true, AA);
4682 if (ViewISelDAGs) DAG.viewGraph();
4684 // Third, instruction select all of the operations to machine code, adding the
4685 // code to the MachineBasicBlock.
4686 InstructionSelectBasicBlock(DAG);
4688 DOUT << "Selected machine code:\n";
4692 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4693 FunctionLoweringInfo &FuncInfo) {
4694 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4696 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4699 // First step, lower LLVM code to some DAG. This DAG may use operations and
4700 // types that are not supported by the target.
4701 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4703 // Second step, emit the lowered DAG as machine code.
4704 CodeGenAndEmitDAG(DAG);
4707 DOUT << "Total amount of phi nodes to update: "
4708 << PHINodesToUpdate.size() << "\n";
4709 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4710 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4711 << ", " << PHINodesToUpdate[i].second << ")\n";);
4713 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4714 // PHI nodes in successors.
4715 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4716 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4717 MachineInstr *PHI = PHINodesToUpdate[i].first;
4718 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4719 "This is not a machine PHI node that we are updating!");
4720 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4721 PHI->addMachineBasicBlockOperand(BB);
4726 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4727 // Lower header first, if it wasn't already lowered
4728 if (!BitTestCases[i].Emitted) {
4729 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4731 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4732 // Set the current basic block to the mbb we wish to insert the code into
4733 BB = BitTestCases[i].Parent;
4734 HSDL.setCurrentBasicBlock(BB);
4736 HSDL.visitBitTestHeader(BitTestCases[i]);
4737 HSDAG.setRoot(HSDL.getRoot());
4738 CodeGenAndEmitDAG(HSDAG);
4741 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4742 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4744 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4745 // Set the current basic block to the mbb we wish to insert the code into
4746 BB = BitTestCases[i].Cases[j].ThisBB;
4747 BSDL.setCurrentBasicBlock(BB);
4750 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4751 BitTestCases[i].Reg,
4752 BitTestCases[i].Cases[j]);
4754 BSDL.visitBitTestCase(BitTestCases[i].Default,
4755 BitTestCases[i].Reg,
4756 BitTestCases[i].Cases[j]);
4759 BSDAG.setRoot(BSDL.getRoot());
4760 CodeGenAndEmitDAG(BSDAG);
4764 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4765 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4766 MachineBasicBlock *PHIBB = PHI->getParent();
4767 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4768 "This is not a machine PHI node that we are updating!");
4769 // This is "default" BB. We have two jumps to it. From "header" BB and
4770 // from last "case" BB.
4771 if (PHIBB == BitTestCases[i].Default) {
4772 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4773 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4774 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4775 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4777 // One of "cases" BB.
4778 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4779 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4780 if (cBB->succ_end() !=
4781 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4782 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4783 PHI->addMachineBasicBlockOperand(cBB);
4789 // If the JumpTable record is filled in, then we need to emit a jump table.
4790 // Updating the PHI nodes is tricky in this case, since we need to determine
4791 // whether the PHI is a successor of the range check MBB or the jump table MBB
4792 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4793 // Lower header first, if it wasn't already lowered
4794 if (!JTCases[i].first.Emitted) {
4795 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4797 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4798 // Set the current basic block to the mbb we wish to insert the code into
4799 BB = JTCases[i].first.HeaderBB;
4800 HSDL.setCurrentBasicBlock(BB);
4802 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4803 HSDAG.setRoot(HSDL.getRoot());
4804 CodeGenAndEmitDAG(HSDAG);
4807 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4809 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
4810 // Set the current basic block to the mbb we wish to insert the code into
4811 BB = JTCases[i].second.MBB;
4812 JSDL.setCurrentBasicBlock(BB);
4814 JSDL.visitJumpTable(JTCases[i].second);
4815 JSDAG.setRoot(JSDL.getRoot());
4816 CodeGenAndEmitDAG(JSDAG);
4819 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4820 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4821 MachineBasicBlock *PHIBB = PHI->getParent();
4822 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4823 "This is not a machine PHI node that we are updating!");
4824 // "default" BB. We can go there only from header BB.
4825 if (PHIBB == JTCases[i].second.Default) {
4826 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4827 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
4829 // JT BB. Just iterate over successors here
4830 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4831 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4832 PHI->addMachineBasicBlockOperand(BB);
4837 // If the switch block involved a branch to one of the actual successors, we
4838 // need to update PHI nodes in that block.
4839 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4840 MachineInstr *PHI = PHINodesToUpdate[i].first;
4841 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4842 "This is not a machine PHI node that we are updating!");
4843 if (BB->isSuccessor(PHI->getParent())) {
4844 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4845 PHI->addMachineBasicBlockOperand(BB);
4849 // If we generated any switch lowering information, build and codegen any
4850 // additional DAGs necessary.
4851 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4852 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4854 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4856 // Set the current basic block to the mbb we wish to insert the code into
4857 BB = SwitchCases[i].ThisBB;
4858 SDL.setCurrentBasicBlock(BB);
4861 SDL.visitSwitchCase(SwitchCases[i]);
4862 SDAG.setRoot(SDL.getRoot());
4863 CodeGenAndEmitDAG(SDAG);
4865 // Handle any PHI nodes in successors of this chunk, as if we were coming
4866 // from the original BB before switch expansion. Note that PHI nodes can
4867 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4868 // handle them the right number of times.
4869 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4870 for (MachineBasicBlock::iterator Phi = BB->begin();
4871 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4872 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4873 for (unsigned pn = 0; ; ++pn) {
4874 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4875 if (PHINodesToUpdate[pn].first == Phi) {
4876 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4877 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4883 // Don't process RHS if same block as LHS.
4884 if (BB == SwitchCases[i].FalseBB)
4885 SwitchCases[i].FalseBB = 0;
4887 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4888 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4889 SwitchCases[i].FalseBB = 0;
4891 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4896 //===----------------------------------------------------------------------===//
4897 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4898 /// target node in the graph.
4899 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4900 if (ViewSchedDAGs) DAG.viewGraph();
4902 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4906 RegisterScheduler::setDefault(Ctor);
4909 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4915 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4916 return new HazardRecognizer();
4919 //===----------------------------------------------------------------------===//
4920 // Helper functions used by the generated instruction selector.
4921 //===----------------------------------------------------------------------===//
4922 // Calls to these methods are generated by tblgen.
4924 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4925 /// the dag combiner simplified the 255, we still want to match. RHS is the
4926 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4927 /// specified in the .td file (e.g. 255).
4928 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4929 int64_t DesiredMaskS) {
4930 uint64_t ActualMask = RHS->getValue();
4931 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4933 // If the actual mask exactly matches, success!
4934 if (ActualMask == DesiredMask)
4937 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4938 if (ActualMask & ~DesiredMask)
4941 // Otherwise, the DAG Combiner may have proven that the value coming in is
4942 // either already zero or is not demanded. Check for known zero input bits.
4943 uint64_t NeededMask = DesiredMask & ~ActualMask;
4944 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4947 // TODO: check to see if missing bits are just not demanded.
4949 // Otherwise, this pattern doesn't match.
4953 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4954 /// the dag combiner simplified the 255, we still want to match. RHS is the
4955 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4956 /// specified in the .td file (e.g. 255).
4957 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4958 int64_t DesiredMaskS) {
4959 uint64_t ActualMask = RHS->getValue();
4960 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4962 // If the actual mask exactly matches, success!
4963 if (ActualMask == DesiredMask)
4966 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4967 if (ActualMask & ~DesiredMask)
4970 // Otherwise, the DAG Combiner may have proven that the value coming in is
4971 // either already zero or is not demanded. Check for known zero input bits.
4972 uint64_t NeededMask = DesiredMask & ~ActualMask;
4974 uint64_t KnownZero, KnownOne;
4975 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4977 // If all the missing bits in the or are already known to be set, match!
4978 if ((NeededMask & KnownOne) == NeededMask)
4981 // TODO: check to see if missing bits are just not demanded.
4983 // Otherwise, this pattern doesn't match.
4988 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4989 /// by tblgen. Others should not call it.
4990 void SelectionDAGISel::
4991 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4992 std::vector<SDOperand> InOps;
4993 std::swap(InOps, Ops);
4995 Ops.push_back(InOps[0]); // input chain.
4996 Ops.push_back(InOps[1]); // input asm string.
4998 unsigned i = 2, e = InOps.size();
4999 if (InOps[e-1].getValueType() == MVT::Flag)
5000 --e; // Don't process a flag operand if it is here.
5003 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5004 if ((Flags & 7) != 4 /*MEM*/) {
5005 // Just skip over this operand, copying the operands verbatim.
5006 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5007 i += (Flags >> 3) + 1;
5009 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5010 // Otherwise, this is a memory operand. Ask the target to select it.
5011 std::vector<SDOperand> SelOps;
5012 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5013 cerr << "Could not match memory address. Inline asm failure!\n";
5017 // Add this to the output node.
5018 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5019 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5021 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5026 // Add the flag input back if present.
5027 if (e != InOps.size())
5028 Ops.push_back(InOps.back());
5031 char SelectionDAGISel::ID = 0;