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/Analysis/AliasAnalysis.h"
16 #include "llvm/CodeGen/SelectionDAGISel.h"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SchedulerRegistry.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Target/MRegisterInfo.h"
36 #include "llvm/Target/TargetAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetFrameInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.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;
62 //===---------------------------------------------------------------------===//
64 /// RegisterScheduler class - Track the registration of instruction schedulers.
66 //===---------------------------------------------------------------------===//
67 MachinePassRegistry RegisterScheduler::Registry;
69 //===---------------------------------------------------------------------===//
71 /// ISHeuristic command line option for instruction schedulers.
73 //===---------------------------------------------------------------------===//
75 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
78 cl::init(&createDefaultScheduler),
79 cl::desc("Instruction schedulers available:"));
81 static RegisterScheduler
82 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
91 struct VISIBILITY_HIDDEN RegsForValue {
92 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
95 std::vector<unsigned> Regs;
97 /// RegVT - The value type of each register.
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
111 RegsForValue(const std::vector<unsigned> ®s,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
120 SDOperand &Chain, SDOperand &Flag) const;
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
133 std::vector<SDOperand> &Ops) const;
138 //===--------------------------------------------------------------------===//
139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
156 //===--------------------------------------------------------------------===//
157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
159 class FunctionLoweringInfo {
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 DenseMap<const Value*, unsigned> ValueMap;
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
191 unsigned CreateRegForValue(const Value *V);
193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
201 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
202 /// PHI nodes or outside of the basic block that defines it, or used by a
203 /// switch instruction, which may expand to multiple basic blocks.
204 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
209 // FIXME: Remove switchinst special case.
210 isa<SwitchInst>(*UI))
215 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
216 /// entry block, return true. This includes arguments used by switches, since
217 /// the switch may expand into multiple basic blocks.
218 static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
222 return false; // Use not in entry block.
226 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
227 Function &fn, MachineFunction &mf)
228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
240 Function::iterator BB = Fn.begin(), EB = Fn.end();
241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
244 const Type *Ty = AI->getAllocatedType();
245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
247 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
250 TySize *= CUI->getZExtValue(); // Get total allocated size.
251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
252 StaticAllocaMap[AI] =
253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
269 MF.getBasicBlockList().push_back(MBB);
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
282 MVT::ValueType VT1,VT2;
284 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
290 for (unsigned i = 0; i != NumElements; ++i)
291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
296 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
297 /// the correctly promoted or expanded types. Assign these registers
298 /// consecutive vreg numbers and return the first assigned number.
299 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
306 // If this is a vector type, figure out what type it will decompose into
307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
309 const VectorType *PTy = cast<VectorType>(V->getType());
310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
322 VT = getVectorType(EltTy, NumElts);
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
348 //===----------------------------------------------------------------------===//
349 /// SelectionDAGLowering - This is the common target-independent lowering
350 /// implementation that is parameterized by a TargetLowering object.
351 /// Also, targets can overload any lowering method.
354 class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
357 DenseMap<const Value*, SDOperand> NodeMap;
359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
363 std::vector<SDOperand> PendingLoads;
365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
388 /// The comparison function for sorting Case values.
390 bool operator () (const Case& C1, const Case& C2) {
391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
403 const TargetData *TD;
405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
408 SelectionDAGISel::JumpTable JT;
410 /// FuncInfo - Information about the function as a whole.
412 FunctionLoweringInfo &FuncInfo;
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
415 FunctionLoweringInfo &funcinfo)
416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
417 JT(0,0,0,0), FuncInfo(funcinfo) {
420 /// getRoot - Return the current virtual root of the Selection DAG.
422 SDOperand getRoot() {
423 if (PendingLoads.empty())
424 return DAG.getRoot();
426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
429 PendingLoads.clear();
433 // Otherwise, we have to make a token factor node.
434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
436 PendingLoads.clear();
441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
445 void visit(unsigned Opcode, User &I) {
446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
449 default: assert(0 && "Unknown instruction type encountered!");
451 // Build the switch statement using the Instruction.def file.
452 #define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454 #include "llvm/Instruction.def"
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
461 const Value *SV, SDOperand Root,
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
468 SDOperand getValue(const Value *V);
470 void setValue(const Value *V, SDOperand NewN) {
471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
486 void ExportFromCurrentBlock(Value *V);
487 void LowerCallTo(Instruction &I,
488 const Type *CalledValueTy, unsigned CallingConv,
489 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
491 // Terminator instructions.
492 void visitRet(ReturnInst &I);
493 void visitBr(BranchInst &I);
494 void visitSwitch(SwitchInst &I);
495 void visitUnreachable(UnreachableInst &I) { /* noop */ }
497 // Helper for visitSwitch
498 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
499 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
501 // These all get lowered before this pass.
502 void visitInvoke(InvokeInst &I);
503 void visitUnwind(UnwindInst &I);
505 void visitScalarBinary(User &I, unsigned OpCode);
506 void visitVectorBinary(User &I, unsigned OpCode);
507 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
508 void visitShift(User &I, unsigned Opcode);
509 void visitAdd(User &I) {
510 if (isa<VectorType>(I.getType()))
511 visitVectorBinary(I, ISD::VADD);
512 else if (I.getType()->isFloatingPoint())
513 visitScalarBinary(I, ISD::FADD);
515 visitScalarBinary(I, ISD::ADD);
517 void visitSub(User &I);
518 void visitMul(User &I) {
519 if (isa<VectorType>(I.getType()))
520 visitVectorBinary(I, ISD::VMUL);
521 else if (I.getType()->isFloatingPoint())
522 visitScalarBinary(I, ISD::FMUL);
524 visitScalarBinary(I, ISD::MUL);
526 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
527 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
528 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
529 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
530 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
531 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
532 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
533 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
534 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
535 void visitShl (User &I) { visitShift(I, ISD::SHL); }
536 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
537 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
538 void visitICmp(User &I);
539 void visitFCmp(User &I);
540 // Visit the conversion instructions
541 void visitTrunc(User &I);
542 void visitZExt(User &I);
543 void visitSExt(User &I);
544 void visitFPTrunc(User &I);
545 void visitFPExt(User &I);
546 void visitFPToUI(User &I);
547 void visitFPToSI(User &I);
548 void visitUIToFP(User &I);
549 void visitSIToFP(User &I);
550 void visitPtrToInt(User &I);
551 void visitIntToPtr(User &I);
552 void visitBitCast(User &I);
554 void visitExtractElement(User &I);
555 void visitInsertElement(User &I);
556 void visitShuffleVector(User &I);
558 void visitGetElementPtr(User &I);
559 void visitSelect(User &I);
561 void visitMalloc(MallocInst &I);
562 void visitFree(FreeInst &I);
563 void visitAlloca(AllocaInst &I);
564 void visitLoad(LoadInst &I);
565 void visitStore(StoreInst &I);
566 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
567 void visitCall(CallInst &I);
568 void visitInlineAsm(CallInst &I);
569 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
570 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
572 void visitVAStart(CallInst &I);
573 void visitVAArg(VAArgInst &I);
574 void visitVAEnd(CallInst &I);
575 void visitVACopy(CallInst &I);
577 void visitMemIntrinsic(CallInst &I, unsigned Op);
579 void visitUserOp1(Instruction &I) {
580 assert(0 && "UserOp1 should not exist at instruction selection time!");
583 void visitUserOp2(Instruction &I) {
584 assert(0 && "UserOp2 should not exist at instruction selection time!");
588 } // end namespace llvm
590 SDOperand SelectionDAGLowering::getValue(const Value *V) {
591 SDOperand &N = NodeMap[V];
594 const Type *VTy = V->getType();
595 MVT::ValueType VT = TLI.getValueType(VTy);
596 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
597 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
598 visit(CE->getOpcode(), *CE);
599 SDOperand N1 = NodeMap[V];
600 assert(N1.Val && "visit didn't populate the ValueMap!");
602 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
603 return N = DAG.getGlobalAddress(GV, VT);
604 } else if (isa<ConstantPointerNull>(C)) {
605 return N = DAG.getConstant(0, TLI.getPointerTy());
606 } else if (isa<UndefValue>(C)) {
607 if (!isa<VectorType>(VTy))
608 return N = DAG.getNode(ISD::UNDEF, VT);
610 // Create a VBUILD_VECTOR of undef nodes.
611 const VectorType *PTy = cast<VectorType>(VTy);
612 unsigned NumElements = PTy->getNumElements();
613 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
615 SmallVector<SDOperand, 8> Ops;
616 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
618 // Create a VConstant node with generic Vector type.
619 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
620 Ops.push_back(DAG.getValueType(PVT));
621 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
622 &Ops[0], Ops.size());
623 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
624 return N = DAG.getConstantFP(CFP->getValue(), VT);
625 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
626 unsigned NumElements = PTy->getNumElements();
627 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
629 // Now that we know the number and type of the elements, push a
630 // Constant or ConstantFP node onto the ops list for each element of
631 // the packed constant.
632 SmallVector<SDOperand, 8> Ops;
633 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
634 for (unsigned i = 0; i != NumElements; ++i)
635 Ops.push_back(getValue(CP->getOperand(i)));
637 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
639 if (MVT::isFloatingPoint(PVT))
640 Op = DAG.getConstantFP(0, PVT);
642 Op = DAG.getConstant(0, PVT);
643 Ops.assign(NumElements, Op);
646 // Create a VBUILD_VECTOR node with generic Vector type.
647 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
648 Ops.push_back(DAG.getValueType(PVT));
649 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
652 // Canonicalize all constant ints to be unsigned.
653 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
657 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
658 std::map<const AllocaInst*, int>::iterator SI =
659 FuncInfo.StaticAllocaMap.find(AI);
660 if (SI != FuncInfo.StaticAllocaMap.end())
661 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
664 DenseMap<const Value*, unsigned>::iterator VMI =
665 FuncInfo.ValueMap.find(V);
666 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
668 unsigned InReg = VMI->second;
670 // If this type is not legal, make it so now.
671 if (VT != MVT::Vector) {
672 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
673 // Source must be expanded. This input value is actually coming from the
674 // register pair VMI->second and VMI->second+1.
675 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
676 unsigned NumVals = TLI.getNumElements(VT);
677 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
679 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
681 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
682 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
683 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
686 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
687 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
688 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
689 N = MVT::isFloatingPoint(VT)
690 ? DAG.getNode(ISD::FP_ROUND, VT, N)
691 : DAG.getNode(ISD::TRUNCATE, VT, N);
694 // Otherwise, if this is a vector, make it available as a generic vector
696 MVT::ValueType PTyElementVT, PTyLegalElementVT;
697 const VectorType *PTy = cast<VectorType>(VTy);
698 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
701 // Build a VBUILD_VECTOR with the input registers.
702 SmallVector<SDOperand, 8> Ops;
703 if (PTyElementVT == PTyLegalElementVT) {
704 // If the value types are legal, just VBUILD the CopyFromReg nodes.
705 for (unsigned i = 0; i != NE; ++i)
706 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
708 } else if (PTyElementVT < PTyLegalElementVT) {
709 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
710 for (unsigned i = 0; i != NE; ++i) {
711 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
713 if (MVT::isFloatingPoint(PTyElementVT))
714 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
716 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
720 // If the register was expanded, use BUILD_PAIR.
721 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
722 for (unsigned i = 0; i != NE/2; ++i) {
723 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
725 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
727 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
731 Ops.push_back(DAG.getConstant(NE, MVT::i32));
732 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
733 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
735 // Finally, use a VBIT_CONVERT to make this available as the appropriate
737 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
738 DAG.getConstant(PTy->getNumElements(),
740 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
747 void SelectionDAGLowering::visitRet(ReturnInst &I) {
748 if (I.getNumOperands() == 0) {
749 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
752 SmallVector<SDOperand, 8> NewValues;
753 NewValues.push_back(getRoot());
754 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
755 SDOperand RetOp = getValue(I.getOperand(i));
757 // If this is an integer return value, we need to promote it ourselves to
758 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
760 // FIXME: C calling convention requires the return type to be promoted to
761 // at least 32-bit. But this is not necessary for non-C calling conventions.
762 if (MVT::isInteger(RetOp.getValueType()) &&
763 RetOp.getValueType() < MVT::i64) {
764 MVT::ValueType TmpVT;
765 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
766 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
769 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
770 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
771 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
772 ExtendKind = ISD::SIGN_EXTEND;
773 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
774 ExtendKind = ISD::ZERO_EXTEND;
775 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
777 NewValues.push_back(RetOp);
778 NewValues.push_back(DAG.getConstant(false, MVT::i32));
780 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
781 &NewValues[0], NewValues.size()));
784 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
785 /// the current basic block, add it to ValueMap now so that we'll get a
787 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
788 // No need to export constants.
789 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
792 if (FuncInfo.isExportedInst(V)) return;
794 unsigned Reg = FuncInfo.InitializeRegForValue(V);
795 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
798 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
799 const BasicBlock *FromBB) {
800 // The operands of the setcc have to be in this block. We don't know
801 // how to export them from some other block.
802 if (Instruction *VI = dyn_cast<Instruction>(V)) {
803 // Can export from current BB.
804 if (VI->getParent() == FromBB)
807 // Is already exported, noop.
808 return FuncInfo.isExportedInst(V);
811 // If this is an argument, we can export it if the BB is the entry block or
812 // if it is already exported.
813 if (isa<Argument>(V)) {
814 if (FromBB == &FromBB->getParent()->getEntryBlock())
817 // Otherwise, can only export this if it is already exported.
818 return FuncInfo.isExportedInst(V);
821 // Otherwise, constants can always be exported.
825 static bool InBlock(const Value *V, const BasicBlock *BB) {
826 if (const Instruction *I = dyn_cast<Instruction>(V))
827 return I->getParent() == BB;
831 /// FindMergedConditions - If Cond is an expression like
832 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
833 MachineBasicBlock *TBB,
834 MachineBasicBlock *FBB,
835 MachineBasicBlock *CurBB,
837 // If this node is not part of the or/and tree, emit it as a branch.
838 Instruction *BOp = dyn_cast<Instruction>(Cond);
840 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
841 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
842 BOp->getParent() != CurBB->getBasicBlock() ||
843 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
844 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
845 const BasicBlock *BB = CurBB->getBasicBlock();
847 // If the leaf of the tree is a comparison, merge the condition into
849 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
850 // The operands of the cmp have to be in this block. We don't know
851 // how to export them from some other block. If this is the first block
852 // of the sequence, no exporting is needed.
854 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
855 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
856 BOp = cast<Instruction>(Cond);
857 ISD::CondCode Condition;
858 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
859 switch (IC->getPredicate()) {
860 default: assert(0 && "Unknown icmp predicate opcode!");
861 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
862 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
863 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
864 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
865 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
866 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
867 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
868 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
869 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
870 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
872 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
873 ISD::CondCode FPC, FOC;
874 switch (FC->getPredicate()) {
875 default: assert(0 && "Unknown fcmp predicate opcode!");
876 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
877 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
878 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
879 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
880 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
881 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
882 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
883 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
884 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
885 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
886 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
887 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
888 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
889 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
890 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
891 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
893 if (FiniteOnlyFPMath())
898 Condition = ISD::SETEQ; // silence warning.
899 assert(0 && "Unknown compare instruction");
902 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
903 BOp->getOperand(1), TBB, FBB, CurBB);
904 SwitchCases.push_back(CB);
908 // Create a CaseBlock record representing this branch.
909 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
911 SwitchCases.push_back(CB);
916 // Create TmpBB after CurBB.
917 MachineFunction::iterator BBI = CurBB;
918 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
919 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
921 if (Opc == Instruction::Or) {
930 // Emit the LHS condition.
931 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
933 // Emit the RHS condition into TmpBB.
934 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
936 assert(Opc == Instruction::And && "Unknown merge op!");
944 // This requires creation of TmpBB after CurBB.
946 // Emit the LHS condition.
947 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
949 // Emit the RHS condition into TmpBB.
950 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
954 /// If the set of cases should be emitted as a series of branches, return true.
955 /// If we should emit this as a bunch of and/or'd together conditions, return
958 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
959 if (Cases.size() != 2) return true;
961 // If this is two comparisons of the same values or'd or and'd together, they
962 // will get folded into a single comparison, so don't emit two blocks.
963 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
964 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
965 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
966 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
973 void SelectionDAGLowering::visitBr(BranchInst &I) {
974 // Update machine-CFG edges.
975 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
977 // Figure out which block is immediately after the current one.
978 MachineBasicBlock *NextBlock = 0;
979 MachineFunction::iterator BBI = CurMBB;
980 if (++BBI != CurMBB->getParent()->end())
983 if (I.isUnconditional()) {
984 // If this is not a fall-through branch, emit the branch.
985 if (Succ0MBB != NextBlock)
986 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
987 DAG.getBasicBlock(Succ0MBB)));
989 // Update machine-CFG edges.
990 CurMBB->addSuccessor(Succ0MBB);
995 // If this condition is one of the special cases we handle, do special stuff
997 Value *CondVal = I.getCondition();
998 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1000 // If this is a series of conditions that are or'd or and'd together, emit
1001 // this as a sequence of branches instead of setcc's with and/or operations.
1002 // For example, instead of something like:
1015 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1016 if (BOp->hasOneUse() &&
1017 (BOp->getOpcode() == Instruction::And ||
1018 BOp->getOpcode() == Instruction::Or)) {
1019 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1020 // If the compares in later blocks need to use values not currently
1021 // exported from this block, export them now. This block should always
1022 // be the first entry.
1023 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1025 // Allow some cases to be rejected.
1026 if (ShouldEmitAsBranches(SwitchCases)) {
1027 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1028 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1029 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1032 // Emit the branch for this block.
1033 visitSwitchCase(SwitchCases[0]);
1034 SwitchCases.erase(SwitchCases.begin());
1038 // Okay, we decided not to do this, remove any inserted MBB's and clear
1040 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1041 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1043 SwitchCases.clear();
1047 // Create a CaseBlock record representing this branch.
1048 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1049 Succ0MBB, Succ1MBB, CurMBB);
1050 // Use visitSwitchCase to actually insert the fast branch sequence for this
1052 visitSwitchCase(CB);
1055 /// visitSwitchCase - Emits the necessary code to represent a single node in
1056 /// the binary search tree resulting from lowering a switch instruction.
1057 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1059 SDOperand CondLHS = getValue(CB.CmpLHS);
1061 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1062 // handle common cases produced by branch lowering.
1063 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1065 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1066 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1067 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1069 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1071 // Set NextBlock to be the MBB immediately after the current one, if any.
1072 // This is used to avoid emitting unnecessary branches to the next block.
1073 MachineBasicBlock *NextBlock = 0;
1074 MachineFunction::iterator BBI = CurMBB;
1075 if (++BBI != CurMBB->getParent()->end())
1078 // If the lhs block is the next block, invert the condition so that we can
1079 // fall through to the lhs instead of the rhs block.
1080 if (CB.TrueBB == NextBlock) {
1081 std::swap(CB.TrueBB, CB.FalseBB);
1082 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1083 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1085 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1086 DAG.getBasicBlock(CB.TrueBB));
1087 if (CB.FalseBB == NextBlock)
1088 DAG.setRoot(BrCond);
1090 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1091 DAG.getBasicBlock(CB.FalseBB)));
1092 // Update successor info
1093 CurMBB->addSuccessor(CB.TrueBB);
1094 CurMBB->addSuccessor(CB.FalseBB);
1097 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1098 // Emit the code for the jump table
1099 MVT::ValueType PTy = TLI.getPointerTy();
1100 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1101 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1102 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1107 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1108 // Retrieve successors.
1109 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1110 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1112 // Mark landing pad so that it doesn't get deleted in branch folding.
1113 LandingPad->setIsLandingPad();
1115 // Insert a label before the invoke call to mark the try range.
1116 // This can be used to detect deletion of the invoke via the
1117 // MachineModuleInfo.
1118 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1119 unsigned BeginLabel = MMI->NextLabelID();
1120 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1121 DAG.getConstant(BeginLabel, MVT::i32)));
1123 LowerCallTo(I, I.getCalledValue()->getType(),
1126 getValue(I.getOperand(0)),
1129 // Insert a label before the invoke call to mark the try range.
1130 // This can be used to detect deletion of the invoke via the
1131 // MachineModuleInfo.
1132 unsigned EndLabel = MMI->NextLabelID();
1133 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1134 DAG.getConstant(EndLabel, MVT::i32)));
1136 // Inform MachineModuleInfo of range.
1137 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1139 // Drop into normal successor.
1140 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1141 DAG.getBasicBlock(Return)));
1143 // Update successor info
1144 CurMBB->addSuccessor(Return);
1145 CurMBB->addSuccessor(LandingPad);
1148 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1151 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1152 // Figure out which block is immediately after the current one.
1153 MachineBasicBlock *NextBlock = 0;
1154 MachineFunction::iterator BBI = CurMBB;
1156 if (++BBI != CurMBB->getParent()->end())
1159 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1161 // If there is only the default destination, branch to it if it is not the
1162 // next basic block. Otherwise, just fall through.
1163 if (I.getNumOperands() == 2) {
1164 // Update machine-CFG edges.
1166 // If this is not a fall-through branch, emit the branch.
1167 if (Default != NextBlock)
1168 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1169 DAG.getBasicBlock(Default)));
1171 CurMBB->addSuccessor(Default);
1175 // If there are any non-default case statements, create a vector of Cases
1176 // representing each one, and sort the vector so that we can efficiently
1177 // create a binary search tree from them.
1178 std::vector<Case> Cases;
1180 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1181 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1182 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1185 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1187 // Get the Value to be switched on and default basic blocks, which will be
1188 // inserted into CaseBlock records, representing basic blocks in the binary
1190 Value *SV = I.getOperand(0);
1192 // Get the MachineFunction which holds the current MBB. This is used during
1193 // emission of jump tables, and when inserting any additional MBBs necessary
1194 // to represent the switch.
1195 MachineFunction *CurMF = CurMBB->getParent();
1196 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1198 // If the switch has few cases (two or less) emit a series of specific
1200 if (Cases.size() < 3) {
1201 // TODO: If any two of the cases has the same destination, and if one value
1202 // is the same as the other, but has one bit unset that the other has set,
1203 // use bit manipulation to do two compares at once. For example:
1204 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1206 // Rearrange the case blocks so that the last one falls through if possible.
1207 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1208 // The last case block won't fall through into 'NextBlock' if we emit the
1209 // branches in this order. See if rearranging a case value would help.
1210 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1211 if (Cases[i].second == NextBlock) {
1212 std::swap(Cases[i], Cases.back());
1218 // Create a CaseBlock record representing a conditional branch to
1219 // the Case's target mbb if the value being switched on SV is equal
1221 MachineBasicBlock *CurBlock = CurMBB;
1222 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1223 MachineBasicBlock *FallThrough;
1225 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1226 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1228 // If the last case doesn't match, go to the default block.
1229 FallThrough = Default;
1232 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1233 Cases[i].second, FallThrough, CurBlock);
1235 // If emitting the first comparison, just call visitSwitchCase to emit the
1236 // code into the current block. Otherwise, push the CaseBlock onto the
1237 // vector to be later processed by SDISel, and insert the node's MBB
1238 // before the next MBB.
1239 if (CurBlock == CurMBB)
1240 visitSwitchCase(CB);
1242 SwitchCases.push_back(CB);
1244 CurBlock = FallThrough;
1249 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1250 // target supports indirect branches, then emit a jump table rather than
1251 // lowering the switch to a binary tree of conditional branches.
1252 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1253 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1255 uint64_t First =cast<ConstantInt>(Cases.front().first)->getSExtValue();
1256 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getSExtValue();
1257 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1259 if (Density >= 0.3125) {
1260 // Create a new basic block to hold the code for loading the address
1261 // of the jump table, and jumping to it. Update successor information;
1262 // we will either branch to the default case for the switch, or the jump
1264 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1265 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1266 CurMBB->addSuccessor(Default);
1267 CurMBB->addSuccessor(JumpTableBB);
1269 // Subtract the lowest switch case value from the value being switched on
1270 // and conditional branch to default mbb if the result is greater than the
1271 // difference between smallest and largest cases.
1272 SDOperand SwitchOp = getValue(SV);
1273 MVT::ValueType VT = SwitchOp.getValueType();
1274 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1275 DAG.getConstant(First, VT));
1277 // The SDNode we just created, which holds the value being switched on
1278 // minus the the smallest case value, needs to be copied to a virtual
1279 // register so it can be used as an index into the jump table in a
1280 // subsequent basic block. This value may be smaller or larger than the
1281 // target's pointer type, and therefore require extension or truncating.
1282 if (VT > TLI.getPointerTy())
1283 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1285 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1287 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1288 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1290 // Emit the range check for the jump table, and branch to the default
1291 // block for the switch statement if the value being switched on exceeds
1292 // the largest case in the switch.
1293 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1294 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1295 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1296 DAG.getBasicBlock(Default)));
1298 // Build a vector of destination BBs, corresponding to each target
1299 // of the jump table. If the value of the jump table slot corresponds to
1300 // a case statement, push the case's BB onto the vector, otherwise, push
1302 std::vector<MachineBasicBlock*> DestBBs;
1303 int64_t TEI = First;
1304 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1305 if (cast<ConstantInt>(ii->first)->getSExtValue() == TEI) {
1306 DestBBs.push_back(ii->second);
1309 DestBBs.push_back(Default);
1312 // Update successor info. Add one edge to each unique successor.
1313 // Vector bool would be better, but vector<bool> is really slow.
1314 std::vector<unsigned char> SuccsHandled;
1315 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1317 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1318 E = DestBBs.end(); I != E; ++I) {
1319 if (!SuccsHandled[(*I)->getNumber()]) {
1320 SuccsHandled[(*I)->getNumber()] = true;
1321 JumpTableBB->addSuccessor(*I);
1325 // Create a jump table index for this jump table, or return an existing
1327 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1329 // Set the jump table information so that we can codegen it as a second
1330 // MachineBasicBlock
1331 JT.Reg = JumpTableReg;
1333 JT.MBB = JumpTableBB;
1334 JT.Default = Default;
1339 // Push the initial CaseRec onto the worklist
1340 std::vector<CaseRec> CaseVec;
1341 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1343 while (!CaseVec.empty()) {
1344 // Grab a record representing a case range to process off the worklist
1345 CaseRec CR = CaseVec.back();
1348 // Size is the number of Cases represented by this range. If Size is 1,
1349 // then we are processing a leaf of the binary search tree. Otherwise,
1350 // we need to pick a pivot, and push left and right ranges onto the
1352 unsigned Size = CR.Range.second - CR.Range.first;
1355 // Create a CaseBlock record representing a conditional branch to
1356 // the Case's target mbb if the value being switched on SV is equal
1357 // to C. Otherwise, branch to default.
1358 Constant *C = CR.Range.first->first;
1359 MachineBasicBlock *Target = CR.Range.first->second;
1360 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1363 // If the MBB representing the leaf node is the current MBB, then just
1364 // call visitSwitchCase to emit the code into the current block.
1365 // Otherwise, push the CaseBlock onto the vector to be later processed
1366 // by SDISel, and insert the node's MBB before the next MBB.
1367 if (CR.CaseBB == CurMBB)
1368 visitSwitchCase(CB);
1370 SwitchCases.push_back(CB);
1372 // split case range at pivot
1373 CaseItr Pivot = CR.Range.first + (Size / 2);
1374 CaseRange LHSR(CR.Range.first, Pivot);
1375 CaseRange RHSR(Pivot, CR.Range.second);
1376 Constant *C = Pivot->first;
1377 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1379 // We know that we branch to the LHS if the Value being switched on is
1380 // less than the Pivot value, C. We use this to optimize our binary
1381 // tree a bit, by recognizing that if SV is greater than or equal to the
1382 // LHS's Case Value, and that Case Value is exactly one less than the
1383 // Pivot's Value, then we can branch directly to the LHS's Target,
1384 // rather than creating a leaf node for it.
1385 if ((LHSR.second - LHSR.first) == 1 &&
1386 LHSR.first->first == CR.GE &&
1387 cast<ConstantInt>(C)->getZExtValue() ==
1388 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
1389 TrueBB = LHSR.first->second;
1391 TrueBB = new MachineBasicBlock(LLVMBB);
1392 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1393 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1396 // Similar to the optimization above, if the Value being switched on is
1397 // known to be less than the Constant CR.LT, and the current Case Value
1398 // is CR.LT - 1, then we can branch directly to the target block for
1399 // the current Case Value, rather than emitting a RHS leaf node for it.
1400 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1401 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1402 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
1403 FalseBB = RHSR.first->second;
1405 FalseBB = new MachineBasicBlock(LLVMBB);
1406 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1407 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1410 // Create a CaseBlock record representing a conditional branch to
1411 // the LHS node if the value being switched on SV is less than C.
1412 // Otherwise, branch to LHS.
1413 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1416 if (CR.CaseBB == CurMBB)
1417 visitSwitchCase(CB);
1419 SwitchCases.push_back(CB);
1424 void SelectionDAGLowering::visitSub(User &I) {
1425 // -0.0 - X --> fneg
1426 const Type *Ty = I.getType();
1427 if (isa<VectorType>(Ty)) {
1428 visitVectorBinary(I, ISD::VSUB);
1429 } else if (Ty->isFloatingPoint()) {
1430 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1431 if (CFP->isExactlyValue(-0.0)) {
1432 SDOperand Op2 = getValue(I.getOperand(1));
1433 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1436 visitScalarBinary(I, ISD::FSUB);
1438 visitScalarBinary(I, ISD::SUB);
1441 void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
1442 SDOperand Op1 = getValue(I.getOperand(0));
1443 SDOperand Op2 = getValue(I.getOperand(1));
1445 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1449 SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1450 assert(isa<VectorType>(I.getType()));
1451 const VectorType *Ty = cast<VectorType>(I.getType());
1452 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
1454 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1455 getValue(I.getOperand(0)),
1456 getValue(I.getOperand(1)),
1457 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1461 void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1462 unsigned VectorOp) {
1463 if (isa<VectorType>(I.getType()))
1464 visitVectorBinary(I, VectorOp);
1466 visitScalarBinary(I, ScalarOp);
1469 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1470 SDOperand Op1 = getValue(I.getOperand(0));
1471 SDOperand Op2 = getValue(I.getOperand(1));
1473 if (TLI.getShiftAmountTy() < Op2.getValueType())
1474 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1475 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1476 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1478 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1481 void SelectionDAGLowering::visitICmp(User &I) {
1482 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1483 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1484 predicate = IC->getPredicate();
1485 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1486 predicate = ICmpInst::Predicate(IC->getPredicate());
1487 SDOperand Op1 = getValue(I.getOperand(0));
1488 SDOperand Op2 = getValue(I.getOperand(1));
1489 ISD::CondCode Opcode;
1490 switch (predicate) {
1491 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1492 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1493 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1494 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1495 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1496 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1497 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1498 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1499 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1500 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1502 assert(!"Invalid ICmp predicate value");
1503 Opcode = ISD::SETEQ;
1506 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1509 void SelectionDAGLowering::visitFCmp(User &I) {
1510 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1511 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1512 predicate = FC->getPredicate();
1513 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1514 predicate = FCmpInst::Predicate(FC->getPredicate());
1515 SDOperand Op1 = getValue(I.getOperand(0));
1516 SDOperand Op2 = getValue(I.getOperand(1));
1517 ISD::CondCode Condition, FOC, FPC;
1518 switch (predicate) {
1519 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1520 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1521 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1522 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1523 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1524 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1525 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1526 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1527 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1528 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1529 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1530 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1531 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1532 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1533 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1534 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1536 assert(!"Invalid FCmp predicate value");
1537 FOC = FPC = ISD::SETFALSE;
1540 if (FiniteOnlyFPMath())
1544 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
1547 void SelectionDAGLowering::visitSelect(User &I) {
1548 SDOperand Cond = getValue(I.getOperand(0));
1549 SDOperand TrueVal = getValue(I.getOperand(1));
1550 SDOperand FalseVal = getValue(I.getOperand(2));
1551 if (!isa<VectorType>(I.getType())) {
1552 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1553 TrueVal, FalseVal));
1555 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1556 *(TrueVal.Val->op_end()-2),
1557 *(TrueVal.Val->op_end()-1)));
1562 void SelectionDAGLowering::visitTrunc(User &I) {
1563 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1564 SDOperand N = getValue(I.getOperand(0));
1565 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1566 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1569 void SelectionDAGLowering::visitZExt(User &I) {
1570 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1571 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1572 SDOperand N = getValue(I.getOperand(0));
1573 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1574 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1577 void SelectionDAGLowering::visitSExt(User &I) {
1578 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1579 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1580 SDOperand N = getValue(I.getOperand(0));
1581 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1582 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1585 void SelectionDAGLowering::visitFPTrunc(User &I) {
1586 // FPTrunc is never a no-op cast, no need to check
1587 SDOperand N = getValue(I.getOperand(0));
1588 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1589 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1592 void SelectionDAGLowering::visitFPExt(User &I){
1593 // FPTrunc is never a no-op cast, no need to check
1594 SDOperand N = getValue(I.getOperand(0));
1595 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1596 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1599 void SelectionDAGLowering::visitFPToUI(User &I) {
1600 // FPToUI is never a no-op cast, no need to check
1601 SDOperand N = getValue(I.getOperand(0));
1602 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1603 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1606 void SelectionDAGLowering::visitFPToSI(User &I) {
1607 // FPToSI is never a no-op cast, no need to check
1608 SDOperand N = getValue(I.getOperand(0));
1609 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1610 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1613 void SelectionDAGLowering::visitUIToFP(User &I) {
1614 // UIToFP is never a no-op cast, no need to check
1615 SDOperand N = getValue(I.getOperand(0));
1616 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1617 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1620 void SelectionDAGLowering::visitSIToFP(User &I){
1621 // UIToFP is never a no-op cast, no need to check
1622 SDOperand N = getValue(I.getOperand(0));
1623 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1624 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1627 void SelectionDAGLowering::visitPtrToInt(User &I) {
1628 // What to do depends on the size of the integer and the size of the pointer.
1629 // We can either truncate, zero extend, or no-op, accordingly.
1630 SDOperand N = getValue(I.getOperand(0));
1631 MVT::ValueType SrcVT = N.getValueType();
1632 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1634 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1635 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1637 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1638 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1639 setValue(&I, Result);
1642 void SelectionDAGLowering::visitIntToPtr(User &I) {
1643 // What to do depends on the size of the integer and the size of the pointer.
1644 // We can either truncate, zero extend, or no-op, accordingly.
1645 SDOperand N = getValue(I.getOperand(0));
1646 MVT::ValueType SrcVT = N.getValueType();
1647 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1648 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1649 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1651 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1652 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1655 void SelectionDAGLowering::visitBitCast(User &I) {
1656 SDOperand N = getValue(I.getOperand(0));
1657 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1658 if (DestVT == MVT::Vector) {
1659 // This is a cast to a vector from something else.
1660 // Get information about the output vector.
1661 const VectorType *DestTy = cast<VectorType>(I.getType());
1662 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1663 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1664 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1665 DAG.getValueType(EltVT)));
1668 MVT::ValueType SrcVT = N.getValueType();
1669 if (SrcVT == MVT::Vector) {
1670 // This is a cast from a vctor to something else.
1671 // Get information about the input vector.
1672 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1676 // BitCast assures us that source and destination are the same size so this
1677 // is either a BIT_CONVERT or a no-op.
1678 if (DestVT != N.getValueType())
1679 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1681 setValue(&I, N); // noop cast.
1684 void SelectionDAGLowering::visitInsertElement(User &I) {
1685 SDOperand InVec = getValue(I.getOperand(0));
1686 SDOperand InVal = getValue(I.getOperand(1));
1687 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1688 getValue(I.getOperand(2)));
1690 SDOperand Num = *(InVec.Val->op_end()-2);
1691 SDOperand Typ = *(InVec.Val->op_end()-1);
1692 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1693 InVec, InVal, InIdx, Num, Typ));
1696 void SelectionDAGLowering::visitExtractElement(User &I) {
1697 SDOperand InVec = getValue(I.getOperand(0));
1698 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1699 getValue(I.getOperand(1)));
1700 SDOperand Typ = *(InVec.Val->op_end()-1);
1701 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1702 TLI.getValueType(I.getType()), InVec, InIdx));
1705 void SelectionDAGLowering::visitShuffleVector(User &I) {
1706 SDOperand V1 = getValue(I.getOperand(0));
1707 SDOperand V2 = getValue(I.getOperand(1));
1708 SDOperand Mask = getValue(I.getOperand(2));
1710 SDOperand Num = *(V1.Val->op_end()-2);
1711 SDOperand Typ = *(V2.Val->op_end()-1);
1712 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1713 V1, V2, Mask, Num, Typ));
1717 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1718 SDOperand N = getValue(I.getOperand(0));
1719 const Type *Ty = I.getOperand(0)->getType();
1721 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1724 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1725 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1728 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
1729 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1730 getIntPtrConstant(Offset));
1732 Ty = StTy->getElementType(Field);
1734 Ty = cast<SequentialType>(Ty)->getElementType();
1736 // If this is a constant subscript, handle it quickly.
1737 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1738 if (CI->getZExtValue() == 0) continue;
1740 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1741 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1745 // N = N + Idx * ElementSize;
1746 uint64_t ElementSize = TD->getTypeSize(Ty);
1747 SDOperand IdxN = getValue(Idx);
1749 // If the index is smaller or larger than intptr_t, truncate or extend
1751 if (IdxN.getValueType() < N.getValueType()) {
1752 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1753 } else if (IdxN.getValueType() > N.getValueType())
1754 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1756 // If this is a multiply by a power of two, turn it into a shl
1757 // immediately. This is a very common case.
1758 if (isPowerOf2_64(ElementSize)) {
1759 unsigned Amt = Log2_64(ElementSize);
1760 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1761 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1762 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1766 SDOperand Scale = getIntPtrConstant(ElementSize);
1767 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1768 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1774 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1775 // If this is a fixed sized alloca in the entry block of the function,
1776 // allocate it statically on the stack.
1777 if (FuncInfo.StaticAllocaMap.count(&I))
1778 return; // getValue will auto-populate this.
1780 const Type *Ty = I.getAllocatedType();
1781 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1783 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
1786 SDOperand AllocSize = getValue(I.getArraySize());
1787 MVT::ValueType IntPtr = TLI.getPointerTy();
1788 if (IntPtr < AllocSize.getValueType())
1789 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1790 else if (IntPtr > AllocSize.getValueType())
1791 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1793 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1794 getIntPtrConstant(TySize));
1796 // Handle alignment. If the requested alignment is less than or equal to the
1797 // stack alignment, ignore it and round the size of the allocation up to the
1798 // stack alignment size. If the size is greater than the stack alignment, we
1799 // note this in the DYNAMIC_STACKALLOC node.
1800 unsigned StackAlign =
1801 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1802 if (Align <= StackAlign) {
1804 // Add SA-1 to the size.
1805 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1806 getIntPtrConstant(StackAlign-1));
1807 // Mask out the low bits for alignment purposes.
1808 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1809 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1812 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1813 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1815 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1817 DAG.setRoot(DSA.getValue(1));
1819 // Inform the Frame Information that we have just allocated a variable-sized
1821 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1824 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1825 SDOperand Ptr = getValue(I.getOperand(0));
1831 // Do not serialize non-volatile loads against each other.
1832 Root = DAG.getRoot();
1835 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1836 Root, I.isVolatile()));
1839 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1840 const Value *SV, SDOperand Root,
1843 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
1844 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1845 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1846 DAG.getSrcValue(SV));
1848 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
1852 DAG.setRoot(L.getValue(1));
1854 PendingLoads.push_back(L.getValue(1));
1860 void SelectionDAGLowering::visitStore(StoreInst &I) {
1861 Value *SrcV = I.getOperand(0);
1862 SDOperand Src = getValue(SrcV);
1863 SDOperand Ptr = getValue(I.getOperand(1));
1864 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
1868 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1869 /// access memory and has no other side effects at all.
1870 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1871 #define GET_NO_MEMORY_INTRINSICS
1872 #include "llvm/Intrinsics.gen"
1873 #undef GET_NO_MEMORY_INTRINSICS
1877 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1878 // have any side-effects or if it only reads memory.
1879 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1880 #define GET_SIDE_EFFECT_INFO
1881 #include "llvm/Intrinsics.gen"
1882 #undef GET_SIDE_EFFECT_INFO
1886 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1888 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1889 unsigned Intrinsic) {
1890 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1891 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1893 // Build the operand list.
1894 SmallVector<SDOperand, 8> Ops;
1895 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1897 // We don't need to serialize loads against other loads.
1898 Ops.push_back(DAG.getRoot());
1900 Ops.push_back(getRoot());
1904 // Add the intrinsic ID as an integer operand.
1905 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1907 // Add all operands of the call to the operand list.
1908 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1909 SDOperand Op = getValue(I.getOperand(i));
1911 // If this is a vector type, force it to the right vector type.
1912 if (Op.getValueType() == MVT::Vector) {
1913 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
1914 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1916 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1917 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1918 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1921 assert(TLI.isTypeLegal(Op.getValueType()) &&
1922 "Intrinsic uses a non-legal type?");
1926 std::vector<MVT::ValueType> VTs;
1927 if (I.getType() != Type::VoidTy) {
1928 MVT::ValueType VT = TLI.getValueType(I.getType());
1929 if (VT == MVT::Vector) {
1930 const VectorType *DestTy = cast<VectorType>(I.getType());
1931 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1933 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1934 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1937 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1941 VTs.push_back(MVT::Other);
1943 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1948 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1949 &Ops[0], Ops.size());
1950 else if (I.getType() != Type::VoidTy)
1951 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1952 &Ops[0], Ops.size());
1954 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1955 &Ops[0], Ops.size());
1958 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1960 PendingLoads.push_back(Chain);
1964 if (I.getType() != Type::VoidTy) {
1965 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
1966 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1967 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1968 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1969 DAG.getValueType(EVT));
1971 setValue(&I, Result);
1975 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1976 /// we want to emit this as a call to a named external function, return the name
1977 /// otherwise lower it and return null.
1979 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1980 switch (Intrinsic) {
1982 // By default, turn this into a target intrinsic node.
1983 visitTargetIntrinsic(I, Intrinsic);
1985 case Intrinsic::vastart: visitVAStart(I); return 0;
1986 case Intrinsic::vaend: visitVAEnd(I); return 0;
1987 case Intrinsic::vacopy: visitVACopy(I); return 0;
1988 case Intrinsic::returnaddress:
1989 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1990 getValue(I.getOperand(1))));
1992 case Intrinsic::frameaddress:
1993 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
1994 getValue(I.getOperand(1))));
1996 case Intrinsic::setjmp:
1997 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
1999 case Intrinsic::longjmp:
2000 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2002 case Intrinsic::memcpy_i32:
2003 case Intrinsic::memcpy_i64:
2004 visitMemIntrinsic(I, ISD::MEMCPY);
2006 case Intrinsic::memset_i32:
2007 case Intrinsic::memset_i64:
2008 visitMemIntrinsic(I, ISD::MEMSET);
2010 case Intrinsic::memmove_i32:
2011 case Intrinsic::memmove_i64:
2012 visitMemIntrinsic(I, ISD::MEMMOVE);
2015 case Intrinsic::dbg_stoppoint: {
2016 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2017 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2018 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2022 Ops[1] = getValue(SPI.getLineValue());
2023 Ops[2] = getValue(SPI.getColumnValue());
2025 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2026 assert(DD && "Not a debug information descriptor");
2027 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2029 Ops[3] = DAG.getString(CompileUnit->getFileName());
2030 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2032 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2037 case Intrinsic::dbg_region_start: {
2038 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2039 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2040 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2041 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2042 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2043 DAG.getConstant(LabelID, MVT::i32)));
2048 case Intrinsic::dbg_region_end: {
2049 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2050 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2051 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2052 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2053 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2054 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2059 case Intrinsic::dbg_func_start: {
2060 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2061 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2062 if (MMI && FSI.getSubprogram() &&
2063 MMI->Verify(FSI.getSubprogram())) {
2064 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2065 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2066 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2071 case Intrinsic::dbg_declare: {
2072 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2073 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2074 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2075 SDOperand AddressOp = getValue(DI.getAddress());
2076 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2077 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2083 case Intrinsic::eh_exception: {
2084 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2087 // Add a label to mark the beginning of the landing pad. Deletion of the
2088 // landing pad can thus be detected via the MachineModuleInfo.
2089 unsigned LabelID = MMI->addLandingPad(CurMBB);
2090 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2091 DAG.getConstant(LabelID, MVT::i32)));
2093 // Mark exception register as live in.
2094 unsigned Reg = TLI.getExceptionAddressRegister();
2095 if (Reg) CurMBB->addLiveIn(Reg);
2097 // Insert the EXCEPTIONADDR instruction.
2098 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2100 Ops[0] = DAG.getRoot();
2101 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2103 DAG.setRoot(Op.getValue(1));
2105 SDOperand Op = DAG.getNode(ISD::MERGE_VALUES, TLI.getPointerTy(),
2106 DAG.getConstant(0, TLI.getPointerTy()),
2109 DAG.setRoot(Op.getValue(1));
2114 case Intrinsic::eh_handlers: {
2115 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2118 // Inform the MachineModuleInfo of the personality for this landing pad.
2119 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2120 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2121 isa<Function>(CE->getOperand(0)) &&
2122 "Personality should be a function");
2123 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
2125 // Gather all the type infos for this landing pad and pass them along to
2126 // MachineModuleInfo.
2127 std::vector<GlobalVariable *> TyInfo;
2128 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
2129 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2130 if (CE && CE->getOpcode() == Instruction::BitCast &&
2131 isa<GlobalVariable>(CE->getOperand(0))) {
2132 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2134 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2135 assert(CI && CI->getZExtValue() == 0 &&
2136 "TypeInfo must be a global variable typeinfo or NULL");
2137 TyInfo.push_back(NULL);
2140 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2142 // Mark exception selector register as live in.
2143 unsigned Reg = TLI.getExceptionSelectorRegister();
2144 if (Reg) CurMBB->addLiveIn(Reg);
2146 // Insert the EHSELECTION instruction.
2147 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2149 Ops[0] = getValue(I.getOperand(1));
2151 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2153 DAG.setRoot(Op.getValue(1));
2155 SDOperand Op = DAG.getNode(ISD::MERGE_VALUES, TLI.getPointerTy(),
2156 DAG.getConstant(0, TLI.getPointerTy()),
2157 getValue(I.getOperand(1)));
2159 DAG.setRoot(Op.getValue(1));
2165 case Intrinsic::eh_typeid_for: {
2166 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2169 // Find the type id for the given typeinfo.
2170 GlobalVariable *GV = NULL;
2171 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2172 if (CE && CE->getOpcode() == Instruction::BitCast &&
2173 isa<GlobalVariable>(CE->getOperand(0))) {
2174 GV = cast<GlobalVariable>(CE->getOperand(0));
2176 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2177 assert(CI && CI->getZExtValue() == 0 &&
2178 "TypeInfo must be a global variable typeinfo or NULL");
2182 unsigned TypeID = MMI->getTypeIDFor(GV);
2183 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2185 setValue(&I, DAG.getConstant(0, MVT::i32));
2191 case Intrinsic::sqrt_f32:
2192 case Intrinsic::sqrt_f64:
2193 setValue(&I, DAG.getNode(ISD::FSQRT,
2194 getValue(I.getOperand(1)).getValueType(),
2195 getValue(I.getOperand(1))));
2197 case Intrinsic::powi_f32:
2198 case Intrinsic::powi_f64:
2199 setValue(&I, DAG.getNode(ISD::FPOWI,
2200 getValue(I.getOperand(1)).getValueType(),
2201 getValue(I.getOperand(1)),
2202 getValue(I.getOperand(2))));
2204 case Intrinsic::pcmarker: {
2205 SDOperand Tmp = getValue(I.getOperand(1));
2206 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2209 case Intrinsic::readcyclecounter: {
2210 SDOperand Op = getRoot();
2211 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2212 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2215 DAG.setRoot(Tmp.getValue(1));
2218 case Intrinsic::bswap_i16:
2219 case Intrinsic::bswap_i32:
2220 case Intrinsic::bswap_i64:
2221 setValue(&I, DAG.getNode(ISD::BSWAP,
2222 getValue(I.getOperand(1)).getValueType(),
2223 getValue(I.getOperand(1))));
2225 case Intrinsic::cttz_i8:
2226 case Intrinsic::cttz_i16:
2227 case Intrinsic::cttz_i32:
2228 case Intrinsic::cttz_i64:
2229 setValue(&I, DAG.getNode(ISD::CTTZ,
2230 getValue(I.getOperand(1)).getValueType(),
2231 getValue(I.getOperand(1))));
2233 case Intrinsic::ctlz_i8:
2234 case Intrinsic::ctlz_i16:
2235 case Intrinsic::ctlz_i32:
2236 case Intrinsic::ctlz_i64:
2237 setValue(&I, DAG.getNode(ISD::CTLZ,
2238 getValue(I.getOperand(1)).getValueType(),
2239 getValue(I.getOperand(1))));
2241 case Intrinsic::ctpop_i8:
2242 case Intrinsic::ctpop_i16:
2243 case Intrinsic::ctpop_i32:
2244 case Intrinsic::ctpop_i64:
2245 setValue(&I, DAG.getNode(ISD::CTPOP,
2246 getValue(I.getOperand(1)).getValueType(),
2247 getValue(I.getOperand(1))));
2249 case Intrinsic::stacksave: {
2250 SDOperand Op = getRoot();
2251 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2252 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2254 DAG.setRoot(Tmp.getValue(1));
2257 case Intrinsic::stackrestore: {
2258 SDOperand Tmp = getValue(I.getOperand(1));
2259 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2262 case Intrinsic::prefetch:
2263 // FIXME: Currently discarding prefetches.
2269 void SelectionDAGLowering::LowerCallTo(Instruction &I,
2270 const Type *CalledValueTy,
2271 unsigned CallingConv,
2273 SDOperand Callee, unsigned OpIdx) {
2274 const PointerType *PT = cast<PointerType>(CalledValueTy);
2275 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2277 TargetLowering::ArgListTy Args;
2278 TargetLowering::ArgListEntry Entry;
2279 Args.reserve(I.getNumOperands());
2280 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2281 Value *Arg = I.getOperand(i);
2282 SDOperand ArgNode = getValue(Arg);
2283 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2284 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2285 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2286 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2287 Args.push_back(Entry);
2290 std::pair<SDOperand,SDOperand> Result =
2291 TLI.LowerCallTo(getRoot(), I.getType(),
2292 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2293 FTy->isVarArg(), CallingConv, IsTailCall,
2295 if (I.getType() != Type::VoidTy)
2296 setValue(&I, Result.first);
2297 DAG.setRoot(Result.second);
2301 void SelectionDAGLowering::visitCall(CallInst &I) {
2302 const char *RenameFn = 0;
2303 if (Function *F = I.getCalledFunction()) {
2304 if (F->isDeclaration())
2305 if (unsigned IID = F->getIntrinsicID()) {
2306 RenameFn = visitIntrinsicCall(I, IID);
2309 } else { // Not an LLVM intrinsic.
2310 const std::string &Name = F->getName();
2311 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2312 if (I.getNumOperands() == 3 && // Basic sanity checks.
2313 I.getOperand(1)->getType()->isFloatingPoint() &&
2314 I.getType() == I.getOperand(1)->getType() &&
2315 I.getType() == I.getOperand(2)->getType()) {
2316 SDOperand LHS = getValue(I.getOperand(1));
2317 SDOperand RHS = getValue(I.getOperand(2));
2318 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2322 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2323 if (I.getNumOperands() == 2 && // Basic sanity checks.
2324 I.getOperand(1)->getType()->isFloatingPoint() &&
2325 I.getType() == I.getOperand(1)->getType()) {
2326 SDOperand Tmp = getValue(I.getOperand(1));
2327 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2330 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2331 if (I.getNumOperands() == 2 && // Basic sanity checks.
2332 I.getOperand(1)->getType()->isFloatingPoint() &&
2333 I.getType() == I.getOperand(1)->getType()) {
2334 SDOperand Tmp = getValue(I.getOperand(1));
2335 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2338 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2339 if (I.getNumOperands() == 2 && // Basic sanity checks.
2340 I.getOperand(1)->getType()->isFloatingPoint() &&
2341 I.getType() == I.getOperand(1)->getType()) {
2342 SDOperand Tmp = getValue(I.getOperand(1));
2343 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2348 } else if (isa<InlineAsm>(I.getOperand(0))) {
2355 Callee = getValue(I.getOperand(0));
2357 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2359 LowerCallTo(I, I.getCalledValue()->getType(),
2367 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2368 SDOperand &Chain, SDOperand &Flag)const{
2369 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2370 Chain = Val.getValue(1);
2371 Flag = Val.getValue(2);
2373 // If the result was expanded, copy from the top part.
2374 if (Regs.size() > 1) {
2375 assert(Regs.size() == 2 &&
2376 "Cannot expand to more than 2 elts yet!");
2377 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2378 Chain = Hi.getValue(1);
2379 Flag = Hi.getValue(2);
2380 if (DAG.getTargetLoweringInfo().isLittleEndian())
2381 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2383 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2386 // Otherwise, if the return value was promoted or extended, truncate it to the
2387 // appropriate type.
2388 if (RegVT == ValueVT)
2391 if (MVT::isInteger(RegVT)) {
2392 if (ValueVT < RegVT)
2393 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2395 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2397 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2401 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2402 /// specified value into the registers specified by this object. This uses
2403 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2404 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2405 SDOperand &Chain, SDOperand &Flag,
2406 MVT::ValueType PtrVT) const {
2407 if (Regs.size() == 1) {
2408 // If there is a single register and the types differ, this must be
2410 if (RegVT != ValueVT) {
2411 if (MVT::isInteger(RegVT)) {
2412 if (RegVT < ValueVT)
2413 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2415 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2417 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2419 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2420 Flag = Chain.getValue(1);
2422 std::vector<unsigned> R(Regs);
2423 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2424 std::reverse(R.begin(), R.end());
2426 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2427 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2428 DAG.getConstant(i, PtrVT));
2429 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2430 Flag = Chain.getValue(1);
2435 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2436 /// operand list. This adds the code marker and includes the number of
2437 /// values added into it.
2438 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2439 std::vector<SDOperand> &Ops) const {
2440 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2441 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2442 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2445 /// isAllocatableRegister - If the specified register is safe to allocate,
2446 /// i.e. it isn't a stack pointer or some other special register, return the
2447 /// register class for the register. Otherwise, return null.
2448 static const TargetRegisterClass *
2449 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2450 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2451 MVT::ValueType FoundVT = MVT::Other;
2452 const TargetRegisterClass *FoundRC = 0;
2453 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2454 E = MRI->regclass_end(); RCI != E; ++RCI) {
2455 MVT::ValueType ThisVT = MVT::Other;
2457 const TargetRegisterClass *RC = *RCI;
2458 // If none of the the value types for this register class are valid, we
2459 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2460 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2462 if (TLI.isTypeLegal(*I)) {
2463 // If we have already found this register in a different register class,
2464 // choose the one with the largest VT specified. For example, on
2465 // PowerPC, we favor f64 register classes over f32.
2466 if (FoundVT == MVT::Other ||
2467 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2474 if (ThisVT == MVT::Other) continue;
2476 // NOTE: This isn't ideal. In particular, this might allocate the
2477 // frame pointer in functions that need it (due to them not being taken
2478 // out of allocation, because a variable sized allocation hasn't been seen
2479 // yet). This is a slight code pessimization, but should still work.
2480 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2481 E = RC->allocation_order_end(MF); I != E; ++I)
2483 // We found a matching register class. Keep looking at others in case
2484 // we find one with larger registers that this physreg is also in.
2493 RegsForValue SelectionDAGLowering::
2494 GetRegistersForValue(const std::string &ConstrCode,
2495 MVT::ValueType VT, bool isOutReg, bool isInReg,
2496 std::set<unsigned> &OutputRegs,
2497 std::set<unsigned> &InputRegs) {
2498 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2499 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2500 std::vector<unsigned> Regs;
2502 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2503 MVT::ValueType RegVT;
2504 MVT::ValueType ValueVT = VT;
2506 // If this is a constraint for a specific physical register, like {r17},
2508 if (PhysReg.first) {
2509 if (VT == MVT::Other)
2510 ValueVT = *PhysReg.second->vt_begin();
2512 // Get the actual register value type. This is important, because the user
2513 // may have asked for (e.g.) the AX register in i32 type. We need to
2514 // remember that AX is actually i16 to get the right extension.
2515 RegVT = *PhysReg.second->vt_begin();
2517 // This is a explicit reference to a physical register.
2518 Regs.push_back(PhysReg.first);
2520 // If this is an expanded reference, add the rest of the regs to Regs.
2522 TargetRegisterClass::iterator I = PhysReg.second->begin();
2523 TargetRegisterClass::iterator E = PhysReg.second->end();
2524 for (; *I != PhysReg.first; ++I)
2525 assert(I != E && "Didn't find reg!");
2527 // Already added the first reg.
2529 for (; NumRegs; --NumRegs, ++I) {
2530 assert(I != E && "Ran out of registers to allocate!");
2534 return RegsForValue(Regs, RegVT, ValueVT);
2537 // Otherwise, if this was a reference to an LLVM register class, create vregs
2538 // for this reference.
2539 std::vector<unsigned> RegClassRegs;
2540 if (PhysReg.second) {
2541 // If this is an early clobber or tied register, our regalloc doesn't know
2542 // how to maintain the constraint. If it isn't, go ahead and create vreg
2543 // and let the regalloc do the right thing.
2544 if (!isOutReg || !isInReg) {
2545 if (VT == MVT::Other)
2546 ValueVT = *PhysReg.second->vt_begin();
2547 RegVT = *PhysReg.second->vt_begin();
2549 // Create the appropriate number of virtual registers.
2550 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2551 for (; NumRegs; --NumRegs)
2552 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2554 return RegsForValue(Regs, RegVT, ValueVT);
2557 // Otherwise, we can't allocate it. Let the code below figure out how to
2558 // maintain these constraints.
2559 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2562 // This is a reference to a register class that doesn't directly correspond
2563 // to an LLVM register class. Allocate NumRegs consecutive, available,
2564 // registers from the class.
2565 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2568 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2569 MachineFunction &MF = *CurMBB->getParent();
2570 unsigned NumAllocated = 0;
2571 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2572 unsigned Reg = RegClassRegs[i];
2573 // See if this register is available.
2574 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2575 (isInReg && InputRegs.count(Reg))) { // Already used.
2576 // Make sure we find consecutive registers.
2581 // Check to see if this register is allocatable (i.e. don't give out the
2583 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2585 // Make sure we find consecutive registers.
2590 // Okay, this register is good, we can use it.
2593 // If we allocated enough consecutive
2594 if (NumAllocated == NumRegs) {
2595 unsigned RegStart = (i-NumAllocated)+1;
2596 unsigned RegEnd = i+1;
2597 // Mark all of the allocated registers used.
2598 for (unsigned i = RegStart; i != RegEnd; ++i) {
2599 unsigned Reg = RegClassRegs[i];
2600 Regs.push_back(Reg);
2601 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2602 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2605 return RegsForValue(Regs, *RC->vt_begin(), VT);
2609 // Otherwise, we couldn't allocate enough registers for this.
2610 return RegsForValue();
2613 /// getConstraintGenerality - Return an integer indicating how general CT is.
2614 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2616 default: assert(0 && "Unknown constraint type!");
2617 case TargetLowering::C_Other:
2618 case TargetLowering::C_Unknown:
2620 case TargetLowering::C_Register:
2622 case TargetLowering::C_RegisterClass:
2624 case TargetLowering::C_Memory:
2629 static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2630 const TargetLowering &TLI) {
2631 assert(!C.empty() && "Must have at least one constraint");
2632 if (C.size() == 1) return C[0];
2634 std::string *Current = &C[0];
2635 // If we have multiple constraints, try to pick the most general one ahead
2636 // of time. This isn't a wonderful solution, but handles common cases.
2637 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2638 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2639 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2640 if (getConstraintGenerality(ThisFlavor) >
2641 getConstraintGenerality(Flavor)) {
2642 // This constraint letter is more general than the previous one,
2644 Flavor = ThisFlavor;
2652 /// visitInlineAsm - Handle a call to an InlineAsm object.
2654 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2655 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2657 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2660 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2661 std::vector<MVT::ValueType> ConstraintVTs;
2663 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2664 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2665 /// if it is a def of that register.
2666 std::vector<SDOperand> AsmNodeOperands;
2667 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2668 AsmNodeOperands.push_back(AsmStr);
2670 SDOperand Chain = getRoot();
2673 // We fully assign registers here at isel time. This is not optimal, but
2674 // should work. For register classes that correspond to LLVM classes, we
2675 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2676 // over the constraints, collecting fixed registers that we know we can't use.
2677 std::set<unsigned> OutputRegs, InputRegs;
2679 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2680 std::string ConstraintCode =
2681 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
2683 MVT::ValueType OpVT;
2685 // Compute the value type for each operand and add it to ConstraintVTs.
2686 switch (Constraints[i].Type) {
2687 case InlineAsm::isOutput:
2688 if (!Constraints[i].isIndirectOutput) {
2689 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2690 OpVT = TLI.getValueType(I.getType());
2692 const Type *OpTy = I.getOperand(OpNum)->getType();
2693 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2694 OpNum++; // Consumes a call operand.
2697 case InlineAsm::isInput:
2698 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2699 OpNum++; // Consumes a call operand.
2701 case InlineAsm::isClobber:
2706 ConstraintVTs.push_back(OpVT);
2708 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2709 continue; // Not assigned a fixed reg.
2711 // Build a list of regs that this operand uses. This always has a single
2712 // element for promoted/expanded operands.
2713 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2715 OutputRegs, InputRegs);
2717 switch (Constraints[i].Type) {
2718 case InlineAsm::isOutput:
2719 // We can't assign any other output to this register.
2720 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2721 // If this is an early-clobber output, it cannot be assigned to the same
2722 // value as the input reg.
2723 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2724 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2726 case InlineAsm::isInput:
2727 // We can't assign any other input to this register.
2728 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2730 case InlineAsm::isClobber:
2731 // Clobbered regs cannot be used as inputs or outputs.
2732 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2733 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2738 // Loop over all of the inputs, copying the operand values into the
2739 // appropriate registers and processing the output regs.
2740 RegsForValue RetValRegs;
2741 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2744 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2745 std::string ConstraintCode =
2746 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
2748 switch (Constraints[i].Type) {
2749 case InlineAsm::isOutput: {
2750 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2751 if (ConstraintCode.size() == 1) // not a physreg name.
2752 CTy = TLI.getConstraintType(ConstraintCode[0]);
2754 if (CTy == TargetLowering::C_Memory) {
2756 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2758 // Check that the operand (the address to store to) isn't a float.
2759 if (!MVT::isInteger(InOperandVal.getValueType()))
2760 assert(0 && "MATCH FAIL!");
2762 if (!Constraints[i].isIndirectOutput)
2763 assert(0 && "MATCH FAIL!");
2765 OpNum++; // Consumes a call operand.
2767 // Extend/truncate to the right pointer type if needed.
2768 MVT::ValueType PtrType = TLI.getPointerTy();
2769 if (InOperandVal.getValueType() < PtrType)
2770 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2771 else if (InOperandVal.getValueType() > PtrType)
2772 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2774 // Add information to the INLINEASM node to know about this output.
2775 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2776 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2777 AsmNodeOperands.push_back(InOperandVal);
2781 // Otherwise, this is a register output.
2782 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2784 // If this is an early-clobber output, or if there is an input
2785 // constraint that matches this, we need to reserve the input register
2786 // so no other inputs allocate to it.
2787 bool UsesInputRegister = false;
2788 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2789 UsesInputRegister = true;
2791 // Copy the output from the appropriate register. Find a register that
2794 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2795 true, UsesInputRegister,
2796 OutputRegs, InputRegs);
2797 if (Regs.Regs.empty()) {
2798 cerr << "Couldn't allocate output reg for contraint '"
2799 << ConstraintCode << "'!\n";
2803 if (!Constraints[i].isIndirectOutput) {
2804 assert(RetValRegs.Regs.empty() &&
2805 "Cannot have multiple output constraints yet!");
2806 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2809 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2810 I.getOperand(OpNum)));
2811 OpNum++; // Consumes a call operand.
2814 // Add information to the INLINEASM node to know that this register is
2816 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2819 case InlineAsm::isInput: {
2820 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2821 OpNum++; // Consumes a call operand.
2823 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2824 // If this is required to match an output register we have already set,
2825 // just use its register.
2826 unsigned OperandNo = atoi(ConstraintCode.c_str());
2828 // Scan until we find the definition we already emitted of this operand.
2829 // When we find it, create a RegsForValue operand.
2830 unsigned CurOp = 2; // The first operand.
2831 for (; OperandNo; --OperandNo) {
2832 // Advance to the next operand.
2834 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2835 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2836 (NumOps & 7) == 4 /*MEM*/) &&
2837 "Skipped past definitions?");
2838 CurOp += (NumOps>>3)+1;
2842 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2843 if ((NumOps & 7) == 2 /*REGDEF*/) {
2844 // Add NumOps>>3 registers to MatchedRegs.
2845 RegsForValue MatchedRegs;
2846 MatchedRegs.ValueVT = InOperandVal.getValueType();
2847 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2848 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2850 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2851 MatchedRegs.Regs.push_back(Reg);
2854 // Use the produced MatchedRegs object to
2855 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2856 TLI.getPointerTy());
2857 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2860 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2861 assert(0 && "matching constraints for memory operands unimp");
2865 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2866 if (ConstraintCode.size() == 1) // not a physreg name.
2867 CTy = TLI.getConstraintType(ConstraintCode[0]);
2869 if (CTy == TargetLowering::C_Other) {
2870 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2871 ConstraintCode[0], DAG);
2872 if (!InOperandVal.Val) {
2873 cerr << "Invalid operand for inline asm constraint '"
2874 << ConstraintCode << "'!\n";
2878 // Add information to the INLINEASM node to know about this input.
2879 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2880 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2881 AsmNodeOperands.push_back(InOperandVal);
2883 } else if (CTy == TargetLowering::C_Memory) {
2886 // Check that the operand isn't a float.
2887 if (!MVT::isInteger(InOperandVal.getValueType()))
2888 assert(0 && "MATCH FAIL!");
2890 // Extend/truncate to the right pointer type if needed.
2891 MVT::ValueType PtrType = TLI.getPointerTy();
2892 if (InOperandVal.getValueType() < PtrType)
2893 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2894 else if (InOperandVal.getValueType() > PtrType)
2895 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2897 // Add information to the INLINEASM node to know about this input.
2898 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2899 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2900 AsmNodeOperands.push_back(InOperandVal);
2904 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2906 // Copy the input into the appropriate registers.
2907 RegsForValue InRegs =
2908 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2909 false, true, OutputRegs, InputRegs);
2910 // FIXME: should be match fail.
2911 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2913 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2915 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2918 case InlineAsm::isClobber: {
2919 RegsForValue ClobberedRegs =
2920 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2921 OutputRegs, InputRegs);
2922 // Add the clobbered value to the operand list, so that the register
2923 // allocator is aware that the physreg got clobbered.
2924 if (!ClobberedRegs.Regs.empty())
2925 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2931 // Finish up input operands.
2932 AsmNodeOperands[0] = Chain;
2933 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2935 Chain = DAG.getNode(ISD::INLINEASM,
2936 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2937 &AsmNodeOperands[0], AsmNodeOperands.size());
2938 Flag = Chain.getValue(1);
2940 // If this asm returns a register value, copy the result from that register
2941 // and set it as the value of the call.
2942 if (!RetValRegs.Regs.empty())
2943 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2945 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2947 // Process indirect outputs, first output all of the flagged copies out of
2949 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2950 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2951 Value *Ptr = IndirectStoresToEmit[i].second;
2952 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2953 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2956 // Emit the non-flagged stores from the physregs.
2957 SmallVector<SDOperand, 8> OutChains;
2958 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2959 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
2960 getValue(StoresToEmit[i].second),
2961 StoresToEmit[i].second, 0));
2962 if (!OutChains.empty())
2963 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2964 &OutChains[0], OutChains.size());
2969 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2970 SDOperand Src = getValue(I.getOperand(0));
2972 MVT::ValueType IntPtr = TLI.getPointerTy();
2974 if (IntPtr < Src.getValueType())
2975 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2976 else if (IntPtr > Src.getValueType())
2977 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2979 // Scale the source by the type size.
2980 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2981 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2982 Src, getIntPtrConstant(ElementSize));
2984 TargetLowering::ArgListTy Args;
2985 TargetLowering::ArgListEntry Entry;
2987 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2988 Entry.isSigned = false;
2989 Entry.isInReg = false;
2990 Entry.isSRet = false;
2991 Args.push_back(Entry);
2993 std::pair<SDOperand,SDOperand> Result =
2994 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
2995 DAG.getExternalSymbol("malloc", IntPtr),
2997 setValue(&I, Result.first); // Pointers always fit in registers
2998 DAG.setRoot(Result.second);
3001 void SelectionDAGLowering::visitFree(FreeInst &I) {
3002 TargetLowering::ArgListTy Args;
3003 TargetLowering::ArgListEntry Entry;
3004 Entry.Node = getValue(I.getOperand(0));
3005 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3006 Entry.isSigned = false;
3007 Entry.isInReg = false;
3008 Entry.isSRet = false;
3009 Args.push_back(Entry);
3010 MVT::ValueType IntPtr = TLI.getPointerTy();
3011 std::pair<SDOperand,SDOperand> Result =
3012 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3013 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3014 DAG.setRoot(Result.second);
3017 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
3018 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3019 // instructions are special in various ways, which require special support to
3020 // insert. The specified MachineInstr is created but not inserted into any
3021 // basic blocks, and the scheduler passes ownership of it to this method.
3022 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3023 MachineBasicBlock *MBB) {
3024 cerr << "If a target marks an instruction with "
3025 << "'usesCustomDAGSchedInserter', it must implement "
3026 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3031 void SelectionDAGLowering::visitVAStart(CallInst &I) {
3032 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3033 getValue(I.getOperand(1)),
3034 DAG.getSrcValue(I.getOperand(1))));
3037 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3038 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3039 getValue(I.getOperand(0)),
3040 DAG.getSrcValue(I.getOperand(0)));
3042 DAG.setRoot(V.getValue(1));
3045 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3046 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3047 getValue(I.getOperand(1)),
3048 DAG.getSrcValue(I.getOperand(1))));
3051 void SelectionDAGLowering::visitVACopy(CallInst &I) {
3052 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3053 getValue(I.getOperand(1)),
3054 getValue(I.getOperand(2)),
3055 DAG.getSrcValue(I.getOperand(1)),
3056 DAG.getSrcValue(I.getOperand(2))));
3059 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3060 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3061 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3062 unsigned &i, SelectionDAG &DAG,
3063 TargetLowering &TLI) {
3064 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3065 return SDOperand(Arg, i++);
3067 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3068 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3070 return DAG.getNode(ISD::BIT_CONVERT, VT,
3071 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3072 } else if (NumVals == 2) {
3073 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3074 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3075 if (!TLI.isLittleEndian())
3077 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3079 // Value scalarized into many values. Unimp for now.
3080 assert(0 && "Cannot expand i64 -> i16 yet!");
3085 /// TargetLowering::LowerArguments - This is the default LowerArguments
3086 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3087 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3088 /// integrated into SDISel.
3089 std::vector<SDOperand>
3090 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3091 const FunctionType *FTy = F.getFunctionType();
3092 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3093 std::vector<SDOperand> Ops;
3094 Ops.push_back(DAG.getRoot());
3095 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3096 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3098 // Add one result value for each formal argument.
3099 std::vector<MVT::ValueType> RetVals;
3101 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3103 MVT::ValueType VT = getValueType(I->getType());
3104 bool isInReg = FTy->paramHasAttr(j, FunctionType::InRegAttribute);
3105 bool isSRet = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
3106 unsigned OriginalAlignment =
3107 getTargetData()->getABITypeAlignment(I->getType());
3108 // Flags[31:27] -> OriginalAlignment
3109 // Flags[2] -> isSRet
3110 // Flags[1] -> isInReg
3111 unsigned Flags = (isInReg << 1) | (isSRet << 2) | (OriginalAlignment << 27);
3113 switch (getTypeAction(VT)) {
3114 default: assert(0 && "Unknown type action!");
3116 RetVals.push_back(VT);
3117 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3120 RetVals.push_back(getTypeToTransformTo(VT));
3121 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3124 if (VT != MVT::Vector) {
3125 // If this is a large integer, it needs to be broken up into small
3126 // integers. Figure out what the destination type is and how many small
3127 // integers it turns into.
3128 MVT::ValueType NVT = getTypeToExpandTo(VT);
3129 unsigned NumVals = getNumElements(VT);
3130 for (unsigned i = 0; i != NumVals; ++i) {
3131 RetVals.push_back(NVT);
3132 // if it isn't first piece, alignment must be 1
3133 if (i == 1) Flags = (Flags & 0x07ffffff) | (1 << 27);
3134 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3137 // Otherwise, this is a vector type. We only support legal vectors
3139 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3140 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
3142 // Figure out if there is a Packed type corresponding to this Vector
3143 // type. If so, convert to the vector type.
3144 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3145 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3146 RetVals.push_back(TVT);
3147 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3149 assert(0 && "Don't support illegal by-val vector arguments yet!");
3156 RetVals.push_back(MVT::Other);
3159 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3160 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3161 &Ops[0], Ops.size()).Val;
3163 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
3165 // Set up the return result vector.
3169 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3171 MVT::ValueType VT = getValueType(I->getType());
3173 switch (getTypeAction(VT)) {
3174 default: assert(0 && "Unknown type action!");
3176 Ops.push_back(SDOperand(Result, i++));
3179 SDOperand Op(Result, i++);
3180 if (MVT::isInteger(VT)) {
3181 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3182 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3183 DAG.getValueType(VT));
3184 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3185 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3186 DAG.getValueType(VT));
3187 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3189 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3190 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3196 if (VT != MVT::Vector) {
3197 // If this is a large integer or a floating point node that needs to be
3198 // expanded, it needs to be reassembled from small integers. Figure out
3199 // what the source elt type is and how many small integers it is.
3200 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
3202 // Otherwise, this is a vector type. We only support legal vectors
3204 const VectorType *PTy = cast<VectorType>(I->getType());
3205 unsigned NumElems = PTy->getNumElements();
3206 const Type *EltTy = PTy->getElementType();
3208 // Figure out if there is a Packed type corresponding to this Vector
3209 // type. If so, convert to the vector type.
3210 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3211 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3212 SDOperand N = SDOperand(Result, i++);
3213 // Handle copies from generic vectors to registers.
3214 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3215 DAG.getConstant(NumElems, MVT::i32),
3216 DAG.getValueType(getValueType(EltTy)));
3219 assert(0 && "Don't support illegal by-val vector arguments yet!");
3230 /// ExpandScalarCallArgs - Recursively expand call argument node by
3231 /// bit_converting it or extract a pair of elements from the larger node.
3232 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3234 SmallVector<SDOperand, 32> &Ops,
3236 TargetLowering &TLI,
3237 bool isFirst = true) {
3239 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3240 // if it isn't first piece, alignment must be 1
3242 Flags = (Flags & 0x07ffffff) | (1 << 27);
3244 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3248 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3249 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3251 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3252 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
3253 } else if (NumVals == 2) {
3254 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3255 DAG.getConstant(0, TLI.getPointerTy()));
3256 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3257 DAG.getConstant(1, TLI.getPointerTy()));
3258 if (!TLI.isLittleEndian())
3260 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3261 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
3263 // Value scalarized into many values. Unimp for now.
3264 assert(0 && "Cannot expand i64 -> i16 yet!");
3268 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3269 /// implementation, which just inserts an ISD::CALL node, which is later custom
3270 /// lowered by the target to something concrete. FIXME: When all targets are
3271 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3272 std::pair<SDOperand, SDOperand>
3273 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3274 bool RetTyIsSigned, bool isVarArg,
3275 unsigned CallingConv, bool isTailCall,
3277 ArgListTy &Args, SelectionDAG &DAG) {
3278 SmallVector<SDOperand, 32> Ops;
3279 Ops.push_back(Chain); // Op#0 - Chain
3280 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3281 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3282 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3283 Ops.push_back(Callee);
3285 // Handle all of the outgoing arguments.
3286 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3287 MVT::ValueType VT = getValueType(Args[i].Ty);
3288 SDOperand Op = Args[i].Node;
3289 bool isSigned = Args[i].isSigned;
3290 bool isInReg = Args[i].isInReg;
3291 bool isSRet = Args[i].isSRet;
3292 unsigned OriginalAlignment =
3293 getTargetData()->getABITypeAlignment(Args[i].Ty);
3294 // Flags[31:27] -> OriginalAlignment
3295 // Flags[2] -> isSRet
3296 // Flags[1] -> isInReg
3297 // Flags[0] -> isSigned
3298 unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned |
3299 (OriginalAlignment << 27);
3301 switch (getTypeAction(VT)) {
3302 default: assert(0 && "Unknown type action!");
3305 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3308 if (MVT::isInteger(VT)) {
3309 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3310 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3312 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3313 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3316 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3319 if (VT != MVT::Vector) {
3320 // If this is a large integer, it needs to be broken down into small
3321 // integers. Figure out what the source elt type is and how many small
3323 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
3325 // Otherwise, this is a vector type. We only support legal vectors
3327 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
3328 unsigned NumElems = PTy->getNumElements();
3329 const Type *EltTy = PTy->getElementType();
3331 // Figure out if there is a Packed type corresponding to this Vector
3332 // type. If so, convert to the vector type.
3333 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3334 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3335 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
3336 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3338 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3340 assert(0 && "Don't support illegal by-val vector call args yet!");
3348 // Figure out the result value types.
3349 SmallVector<MVT::ValueType, 4> RetTys;
3351 if (RetTy != Type::VoidTy) {
3352 MVT::ValueType VT = getValueType(RetTy);
3353 switch (getTypeAction(VT)) {
3354 default: assert(0 && "Unknown type action!");
3356 RetTys.push_back(VT);
3359 RetTys.push_back(getTypeToTransformTo(VT));
3362 if (VT != MVT::Vector) {
3363 // If this is a large integer, it needs to be reassembled from small
3364 // integers. Figure out what the source elt type is and how many small
3366 MVT::ValueType NVT = getTypeToExpandTo(VT);
3367 unsigned NumVals = getNumElements(VT);
3368 for (unsigned i = 0; i != NumVals; ++i)
3369 RetTys.push_back(NVT);
3371 // Otherwise, this is a vector type. We only support legal vectors
3373 const VectorType *PTy = cast<VectorType>(RetTy);
3374 unsigned NumElems = PTy->getNumElements();
3375 const Type *EltTy = PTy->getElementType();
3377 // Figure out if there is a Packed type corresponding to this Vector
3378 // type. If so, convert to the vector type.
3379 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3380 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3381 RetTys.push_back(TVT);
3383 assert(0 && "Don't support illegal by-val vector call results yet!");
3390 RetTys.push_back(MVT::Other); // Always has a chain.
3392 // Finally, create the CALL node.
3393 SDOperand Res = DAG.getNode(ISD::CALL,
3394 DAG.getVTList(&RetTys[0], RetTys.size()),
3395 &Ops[0], Ops.size());
3397 // This returns a pair of operands. The first element is the
3398 // return value for the function (if RetTy is not VoidTy). The second
3399 // element is the outgoing token chain.
3401 if (RetTys.size() != 1) {
3402 MVT::ValueType VT = getValueType(RetTy);
3403 if (RetTys.size() == 2) {
3406 // If this value was promoted, truncate it down.
3407 if (ResVal.getValueType() != VT) {
3408 if (VT == MVT::Vector) {
3409 // Insert a VBITCONVERT to convert from the packed result type to the
3410 // MVT::Vector type.
3411 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3412 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
3414 // Figure out if there is a Packed type corresponding to this Vector
3415 // type. If so, convert to the vector type.
3416 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
3417 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3418 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3419 // "N x PTyElementVT" MVT::Vector type.
3420 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3421 DAG.getConstant(NumElems, MVT::i32),
3422 DAG.getValueType(getValueType(EltTy)));
3426 } else if (MVT::isInteger(VT)) {
3427 unsigned AssertOp = ISD::AssertSext;
3429 AssertOp = ISD::AssertZext;
3430 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3431 DAG.getValueType(VT));
3432 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3434 assert(MVT::isFloatingPoint(VT));
3435 if (getTypeAction(VT) == Expand)
3436 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3438 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3441 } else if (RetTys.size() == 3) {
3442 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3443 Res.getValue(0), Res.getValue(1));
3446 assert(0 && "Case not handled yet!");
3450 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3453 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3454 assert(0 && "LowerOperation not implemented for this target!");
3459 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3460 SelectionDAG &DAG) {
3461 assert(0 && "CustomPromoteOperation not implemented for this target!");
3466 /// getMemsetValue - Vectorized representation of the memset value
3468 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3469 SelectionDAG &DAG) {
3470 MVT::ValueType CurVT = VT;
3471 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3472 uint64_t Val = C->getValue() & 255;
3474 while (CurVT != MVT::i8) {
3475 Val = (Val << Shift) | Val;
3477 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3479 return DAG.getConstant(Val, VT);
3481 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3483 while (CurVT != MVT::i8) {
3485 DAG.getNode(ISD::OR, VT,
3486 DAG.getNode(ISD::SHL, VT, Value,
3487 DAG.getConstant(Shift, MVT::i8)), Value);
3489 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3496 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3497 /// used when a memcpy is turned into a memset when the source is a constant
3499 static SDOperand getMemsetStringVal(MVT::ValueType VT,
3500 SelectionDAG &DAG, TargetLowering &TLI,
3501 std::string &Str, unsigned Offset) {
3503 unsigned MSB = getSizeInBits(VT) / 8;
3504 if (TLI.isLittleEndian())
3505 Offset = Offset + MSB - 1;
3506 for (unsigned i = 0; i != MSB; ++i) {
3507 Val = (Val << 8) | (unsigned char)Str[Offset];
3508 Offset += TLI.isLittleEndian() ? -1 : 1;
3510 return DAG.getConstant(Val, VT);
3513 /// getMemBasePlusOffset - Returns base and offset node for the
3514 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3515 SelectionDAG &DAG, TargetLowering &TLI) {
3516 MVT::ValueType VT = Base.getValueType();
3517 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3520 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3521 /// to replace the memset / memcpy is below the threshold. It also returns the
3522 /// types of the sequence of memory ops to perform memset / memcpy.
3523 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3524 unsigned Limit, uint64_t Size,
3525 unsigned Align, TargetLowering &TLI) {
3528 if (TLI.allowsUnalignedMemoryAccesses()) {
3531 switch (Align & 7) {
3547 MVT::ValueType LVT = MVT::i64;
3548 while (!TLI.isTypeLegal(LVT))
3549 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3550 assert(MVT::isInteger(LVT));
3555 unsigned NumMemOps = 0;
3557 unsigned VTSize = getSizeInBits(VT) / 8;
3558 while (VTSize > Size) {
3559 VT = (MVT::ValueType)((unsigned)VT - 1);
3562 assert(MVT::isInteger(VT));
3564 if (++NumMemOps > Limit)
3566 MemOps.push_back(VT);
3573 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3574 SDOperand Op1 = getValue(I.getOperand(1));
3575 SDOperand Op2 = getValue(I.getOperand(2));
3576 SDOperand Op3 = getValue(I.getOperand(3));
3577 SDOperand Op4 = getValue(I.getOperand(4));
3578 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3579 if (Align == 0) Align = 1;
3581 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3582 std::vector<MVT::ValueType> MemOps;
3584 // Expand memset / memcpy to a series of load / store ops
3585 // if the size operand falls below a certain threshold.
3586 SmallVector<SDOperand, 8> OutChains;
3588 default: break; // Do nothing for now.
3590 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3591 Size->getValue(), Align, TLI)) {
3592 unsigned NumMemOps = MemOps.size();
3593 unsigned Offset = 0;
3594 for (unsigned i = 0; i < NumMemOps; i++) {
3595 MVT::ValueType VT = MemOps[i];
3596 unsigned VTSize = getSizeInBits(VT) / 8;
3597 SDOperand Value = getMemsetValue(Op2, VT, DAG);
3598 SDOperand Store = DAG.getStore(getRoot(), Value,
3599 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3600 I.getOperand(1), Offset);
3601 OutChains.push_back(Store);
3608 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3609 Size->getValue(), Align, TLI)) {
3610 unsigned NumMemOps = MemOps.size();
3611 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3612 GlobalAddressSDNode *G = NULL;
3614 bool CopyFromStr = false;
3616 if (Op2.getOpcode() == ISD::GlobalAddress)
3617 G = cast<GlobalAddressSDNode>(Op2);
3618 else if (Op2.getOpcode() == ISD::ADD &&
3619 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3620 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3621 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3622 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3625 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3626 if (GV && GV->isConstant()) {
3627 Str = GV->getStringValue(false);
3635 for (unsigned i = 0; i < NumMemOps; i++) {
3636 MVT::ValueType VT = MemOps[i];
3637 unsigned VTSize = getSizeInBits(VT) / 8;
3638 SDOperand Value, Chain, Store;
3641 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3644 DAG.getStore(Chain, Value,
3645 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3646 I.getOperand(1), DstOff);
3648 Value = DAG.getLoad(VT, getRoot(),
3649 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3650 I.getOperand(2), SrcOff);
3651 Chain = Value.getValue(1);
3653 DAG.getStore(Chain, Value,
3654 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3655 I.getOperand(1), DstOff);
3657 OutChains.push_back(Store);
3666 if (!OutChains.empty()) {
3667 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3668 &OutChains[0], OutChains.size()));
3673 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3676 //===----------------------------------------------------------------------===//
3677 // SelectionDAGISel code
3678 //===----------------------------------------------------------------------===//
3680 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3681 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3684 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3685 // FIXME: we only modify the CFG to split critical edges. This
3686 // updates dom and loop info.
3687 AU.addRequired<AliasAnalysis>();
3691 /// OptimizeNoopCopyExpression - We have determined that the specified cast
3692 /// instruction is a noop copy (e.g. it's casting from one pointer type to
3693 /// another, int->uint, or int->sbyte on PPC.
3695 /// Return true if any changes are made.
3696 static bool OptimizeNoopCopyExpression(CastInst *CI) {
3697 BasicBlock *DefBB = CI->getParent();
3699 /// InsertedCasts - Only insert a cast in each block once.
3700 std::map<BasicBlock*, CastInst*> InsertedCasts;
3702 bool MadeChange = false;
3703 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3705 Use &TheUse = UI.getUse();
3706 Instruction *User = cast<Instruction>(*UI);
3708 // Figure out which BB this cast is used in. For PHI's this is the
3709 // appropriate predecessor block.
3710 BasicBlock *UserBB = User->getParent();
3711 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3712 unsigned OpVal = UI.getOperandNo()/2;
3713 UserBB = PN->getIncomingBlock(OpVal);
3716 // Preincrement use iterator so we don't invalidate it.
3719 // If this user is in the same block as the cast, don't change the cast.
3720 if (UserBB == DefBB) continue;
3722 // If we have already inserted a cast into this block, use it.
3723 CastInst *&InsertedCast = InsertedCasts[UserBB];
3725 if (!InsertedCast) {
3726 BasicBlock::iterator InsertPt = UserBB->begin();
3727 while (isa<PHINode>(InsertPt)) ++InsertPt;
3730 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3735 // Replace a use of the cast with a use of the new casat.
3736 TheUse = InsertedCast;
3739 // If we removed all uses, nuke the cast.
3740 if (CI->use_empty())
3741 CI->eraseFromParent();
3746 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3747 /// casting to the type of GEPI.
3748 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3749 Instruction *GEPI, Value *Ptr,
3751 if (V) return V; // Already computed.
3753 // Figure out the insertion point
3754 BasicBlock::iterator InsertPt;
3755 if (BB == GEPI->getParent()) {
3756 // If GEP is already inserted into BB, insert right after the GEP.
3760 // Otherwise, insert at the top of BB, after any PHI nodes
3761 InsertPt = BB->begin();
3762 while (isa<PHINode>(InsertPt)) ++InsertPt;
3765 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3766 // BB so that there is only one value live across basic blocks (the cast
3768 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3769 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3770 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3773 // Add the offset, cast it to the right type.
3774 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3775 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3776 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3780 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3781 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3782 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3783 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3784 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3785 /// the constant add into a load or store instruction. Additionally, if a user
3786 /// is a pointer-pointer cast, we look through it to find its users.
3787 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3788 Constant *PtrOffset, BasicBlock *DefBB,
3789 GetElementPtrInst *GEPI,
3790 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3791 while (!RepPtr->use_empty()) {
3792 Instruction *User = cast<Instruction>(RepPtr->use_back());
3794 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3795 // used for a Pointer-Pointer cast.
3796 if (isa<BitCastInst>(User)) {
3797 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3799 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3800 // could invalidate an iterator.
3801 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3805 // If this is a load of the pointer, or a store through the pointer, emit
3806 // the increment into the load/store block.
3807 Instruction *NewVal;
3808 if (isa<LoadInst>(User) ||
3809 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3810 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3811 User->getParent(), GEPI,
3814 // If this use is not foldable into the addressing mode, use a version
3815 // emitted in the GEP block.
3816 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3820 if (GEPI->getType() != RepPtr->getType()) {
3821 BasicBlock::iterator IP = NewVal;
3823 // NewVal must be a GEP which must be pointer type, so BitCast
3824 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
3826 User->replaceUsesOfWith(RepPtr, NewVal);
3831 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3832 /// selection, we want to be a bit careful about some things. In particular, if
3833 /// we have a GEP instruction that is used in a different block than it is
3834 /// defined, the addressing expression of the GEP cannot be folded into loads or
3835 /// stores that use it. In this case, decompose the GEP and move constant
3836 /// indices into blocks that use it.
3837 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3838 const TargetData *TD) {
3839 // If this GEP is only used inside the block it is defined in, there is no
3840 // need to rewrite it.
3841 bool isUsedOutsideDefBB = false;
3842 BasicBlock *DefBB = GEPI->getParent();
3843 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3845 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3846 isUsedOutsideDefBB = true;
3850 if (!isUsedOutsideDefBB) return false;
3852 // If this GEP has no non-zero constant indices, there is nothing we can do,
3854 bool hasConstantIndex = false;
3855 bool hasVariableIndex = false;
3856 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3857 E = GEPI->op_end(); OI != E; ++OI) {
3858 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3859 if (CI->getZExtValue()) {
3860 hasConstantIndex = true;
3864 hasVariableIndex = true;
3868 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3869 if (!hasConstantIndex && !hasVariableIndex) {
3870 /// The GEP operand must be a pointer, so must its result -> BitCast
3871 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3872 GEPI->getName(), GEPI);
3873 GEPI->replaceAllUsesWith(NC);
3874 GEPI->eraseFromParent();
3878 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3879 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3882 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3883 // constant offset (which we now know is non-zero) and deal with it later.
3884 uint64_t ConstantOffset = 0;
3885 const Type *UIntPtrTy = TD->getIntPtrType();
3886 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3887 const Type *Ty = GEPI->getOperand(0)->getType();
3889 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3890 E = GEPI->op_end(); OI != E; ++OI) {
3892 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3893 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3895 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
3896 Ty = StTy->getElementType(Field);
3898 Ty = cast<SequentialType>(Ty)->getElementType();
3900 // Handle constant subscripts.
3901 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3902 if (CI->getZExtValue() == 0) continue;
3903 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3907 // Ptr = Ptr + Idx * ElementSize;
3909 // Cast Idx to UIntPtrTy if needed.
3910 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
3912 uint64_t ElementSize = TD->getTypeSize(Ty);
3913 // Mask off bits that should not be set.
3914 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3915 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3917 // Multiply by the element size and add to the base.
3918 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3919 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3923 // Make sure that the offset fits in uintptr_t.
3924 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3925 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3927 // Okay, we have now emitted all of the variable index parts to the BB that
3928 // the GEP is defined in. Loop over all of the using instructions, inserting
3929 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3930 // instruction to use the newly computed value, making GEPI dead. When the
3931 // user is a load or store instruction address, we emit the add into the user
3932 // block, otherwise we use a canonical version right next to the gep (these
3933 // won't be foldable as addresses, so we might as well share the computation).
3935 std::map<BasicBlock*,Instruction*> InsertedExprs;
3936 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3938 // Finally, the GEP is dead, remove it.
3939 GEPI->eraseFromParent();
3945 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
3946 /// successor if it will improve codegen. We only do this if the successor has
3947 /// phi nodes (otherwise critical edges are ok). If there is already another
3948 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
3949 /// instead of introducing a new block.
3950 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3951 BasicBlock *TIBB = TI->getParent();
3952 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3953 assert(isa<PHINode>(Dest->begin()) &&
3954 "This should only be called if Dest has a PHI!");
3956 /// TIPHIValues - This array is lazily computed to determine the values of
3957 /// PHIs in Dest that TI would provide.
3958 std::vector<Value*> TIPHIValues;
3960 // Check to see if Dest has any blocks that can be used as a split edge for
3962 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3963 BasicBlock *Pred = *PI;
3964 // To be usable, the pred has to end with an uncond branch to the dest.
3965 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3966 if (!PredBr || !PredBr->isUnconditional() ||
3967 // Must be empty other than the branch.
3968 &Pred->front() != PredBr)
3971 // Finally, since we know that Dest has phi nodes in it, we have to make
3972 // sure that jumping to Pred will have the same affect as going to Dest in
3973 // terms of PHI values.
3976 bool FoundMatch = true;
3977 for (BasicBlock::iterator I = Dest->begin();
3978 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3979 if (PHINo == TIPHIValues.size())
3980 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3982 // If the PHI entry doesn't work, we can't use this pred.
3983 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3989 // If we found a workable predecessor, change TI to branch to Succ.
3991 Dest->removePredecessor(TIBB);
3992 TI->setSuccessor(SuccNum, Pred);
3997 SplitCriticalEdge(TI, SuccNum, P, true);
4001 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4002 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4003 RegMap = MF.getSSARegMap();
4004 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4006 // First, split all critical edges.
4008 // In this pass we also look for GEP and cast instructions that are used
4009 // across basic blocks and rewrite them to improve basic-block-at-a-time
4012 bool MadeChange = true;
4013 while (MadeChange) {
4015 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
4016 // Split all critical edges where the dest block has a PHI.
4017 TerminatorInst *BBTI = FNI->getTerminator();
4018 if (BBTI->getNumSuccessors() > 1) {
4019 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
4020 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
4021 isCriticalEdge(BBTI, i, true))
4022 SplitEdgeNicely(BBTI, i, this);
4026 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
4027 Instruction *I = BBI++;
4029 if (CallInst *CI = dyn_cast<CallInst>(I)) {
4030 // If we found an inline asm expession, and if the target knows how to
4031 // lower it to normal LLVM code, do so now.
4032 if (isa<InlineAsm>(CI->getCalledValue()))
4033 if (const TargetAsmInfo *TAI =
4034 TLI.getTargetMachine().getTargetAsmInfo()) {
4035 if (TAI->ExpandInlineAsm(CI))
4038 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
4039 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
4040 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
4041 // If the source of the cast is a constant, then this should have
4042 // already been constant folded. The only reason NOT to constant fold
4043 // it is if something (e.g. LSR) was careful to place the constant
4044 // evaluation in a block other than then one that uses it (e.g. to hoist
4045 // the address of globals out of a loop). If this is the case, we don't
4046 // want to forward-subst the cast.
4047 if (isa<Constant>(CI->getOperand(0)))
4050 // If this is a noop copy, sink it into user blocks to reduce the number
4051 // of virtual registers that must be created and coallesced.
4052 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4053 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4055 // This is an fp<->int conversion?
4056 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4059 // If this is an extension, it will be a zero or sign extension, which
4061 if (SrcVT < DstVT) continue;
4063 // If these values will be promoted, find out what they will be promoted
4064 // to. This helps us consider truncates on PPC as noop copies when they
4066 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4067 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4068 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4069 DstVT = TLI.getTypeToTransformTo(DstVT);
4071 // If, after promotion, these are the same types, this is a noop copy.
4073 MadeChange |= OptimizeNoopCopyExpression(CI);
4079 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4081 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4082 SelectBasicBlock(I, MF, FuncInfo);
4084 // Add function live-ins to entry block live-in set.
4085 BasicBlock *EntryBB = &Fn.getEntryBlock();
4086 BB = FuncInfo.MBBMap[EntryBB];
4087 if (!MF.livein_empty())
4088 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4089 E = MF.livein_end(); I != E; ++I)
4090 BB->addLiveIn(I->first);
4095 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4097 SDOperand Op = getValue(V);
4098 assert((Op.getOpcode() != ISD::CopyFromReg ||
4099 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4100 "Copy from a reg to the same reg!");
4102 // If this type is not legal, we must make sure to not create an invalid
4104 MVT::ValueType SrcVT = Op.getValueType();
4105 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
4106 if (SrcVT == DestVT) {
4107 return DAG.getCopyToReg(getRoot(), Reg, Op);
4108 } else if (SrcVT == MVT::Vector) {
4109 // Handle copies from generic vectors to registers.
4110 MVT::ValueType PTyElementVT, PTyLegalElementVT;
4111 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
4112 PTyElementVT, PTyLegalElementVT);
4114 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4115 // MVT::Vector type.
4116 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4117 DAG.getConstant(NE, MVT::i32),
4118 DAG.getValueType(PTyElementVT));
4120 // Loop over all of the elements of the resultant vector,
4121 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4122 // copying them into output registers.
4123 SmallVector<SDOperand, 8> OutChains;
4124 SDOperand Root = getRoot();
4125 for (unsigned i = 0; i != NE; ++i) {
4126 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
4127 Op, DAG.getConstant(i, TLI.getPointerTy()));
4128 if (PTyElementVT == PTyLegalElementVT) {
4129 // Elements are legal.
4130 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4131 } else if (PTyLegalElementVT > PTyElementVT) {
4132 // Elements are promoted.
4133 if (MVT::isFloatingPoint(PTyLegalElementVT))
4134 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4136 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4137 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4139 // Elements are expanded.
4140 // The src value is expanded into multiple registers.
4141 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4142 Elt, DAG.getConstant(0, TLI.getPointerTy()));
4143 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
4144 Elt, DAG.getConstant(1, TLI.getPointerTy()));
4145 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4146 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4149 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4150 &OutChains[0], OutChains.size());
4151 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
4152 // The src value is promoted to the register.
4153 if (MVT::isFloatingPoint(SrcVT))
4154 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4156 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
4157 return DAG.getCopyToReg(getRoot(), Reg, Op);
4159 DestVT = TLI.getTypeToExpandTo(SrcVT);
4160 unsigned NumVals = TLI.getNumElements(SrcVT);
4162 return DAG.getCopyToReg(getRoot(), Reg,
4163 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4164 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
4165 // The src value is expanded into multiple registers.
4166 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4167 Op, DAG.getConstant(0, TLI.getPointerTy()));
4168 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
4169 Op, DAG.getConstant(1, TLI.getPointerTy()));
4170 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
4171 return DAG.getCopyToReg(Op, Reg+1, Hi);
4175 void SelectionDAGISel::
4176 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4177 std::vector<SDOperand> &UnorderedChains) {
4178 // If this is the entry block, emit arguments.
4179 Function &F = *LLVMBB->getParent();
4180 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4181 SDOperand OldRoot = SDL.DAG.getRoot();
4182 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4185 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4187 if (!AI->use_empty()) {
4188 SDL.setValue(AI, Args[a]);
4190 // If this argument is live outside of the entry block, insert a copy from
4191 // whereever we got it to the vreg that other BB's will reference it as.
4192 if (FuncInfo.ValueMap.count(AI)) {
4194 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
4195 UnorderedChains.push_back(Copy);
4199 // Finally, if the target has anything special to do, allow it to do so.
4200 // FIXME: this should insert code into the DAG!
4201 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4204 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4205 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4206 FunctionLoweringInfo &FuncInfo) {
4207 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
4209 std::vector<SDOperand> UnorderedChains;
4211 // Lower any arguments needed in this block if this is the entry block.
4212 if (LLVMBB == &LLVMBB->getParent()->front())
4213 LowerArguments(LLVMBB, SDL, UnorderedChains);
4215 BB = FuncInfo.MBBMap[LLVMBB];
4216 SDL.setCurrentBasicBlock(BB);
4218 // Lower all of the non-terminator instructions.
4219 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4223 // Ensure that all instructions which are used outside of their defining
4224 // blocks are available as virtual registers.
4225 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4226 if (!I->use_empty() && !isa<PHINode>(I)) {
4227 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4228 if (VMI != FuncInfo.ValueMap.end())
4229 UnorderedChains.push_back(
4230 SDL.CopyValueToVirtualRegister(I, VMI->second));
4233 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4234 // ensure constants are generated when needed. Remember the virtual registers
4235 // that need to be added to the Machine PHI nodes as input. We cannot just
4236 // directly add them, because expansion might result in multiple MBB's for one
4237 // BB. As such, the start of the BB might correspond to a different MBB than
4240 TerminatorInst *TI = LLVMBB->getTerminator();
4242 // Emit constants only once even if used by multiple PHI nodes.
4243 std::map<Constant*, unsigned> ConstantsOut;
4245 // Vector bool would be better, but vector<bool> is really slow.
4246 std::vector<unsigned char> SuccsHandled;
4247 if (TI->getNumSuccessors())
4248 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4250 // Check successor nodes PHI nodes that expect a constant to be available from
4252 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4253 BasicBlock *SuccBB = TI->getSuccessor(succ);
4254 if (!isa<PHINode>(SuccBB->begin())) continue;
4255 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4257 // If this terminator has multiple identical successors (common for
4258 // switches), only handle each succ once.
4259 unsigned SuccMBBNo = SuccMBB->getNumber();
4260 if (SuccsHandled[SuccMBBNo]) continue;
4261 SuccsHandled[SuccMBBNo] = true;
4263 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4266 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4267 // nodes and Machine PHI nodes, but the incoming operands have not been
4269 for (BasicBlock::iterator I = SuccBB->begin();
4270 (PN = dyn_cast<PHINode>(I)); ++I) {
4271 // Ignore dead phi's.
4272 if (PN->use_empty()) continue;
4275 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4277 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4278 unsigned &RegOut = ConstantsOut[C];
4280 RegOut = FuncInfo.CreateRegForValue(C);
4281 UnorderedChains.push_back(
4282 SDL.CopyValueToVirtualRegister(C, RegOut));
4286 Reg = FuncInfo.ValueMap[PHIOp];
4288 assert(isa<AllocaInst>(PHIOp) &&
4289 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4290 "Didn't codegen value into a register!??");
4291 Reg = FuncInfo.CreateRegForValue(PHIOp);
4292 UnorderedChains.push_back(
4293 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4297 // Remember that this register needs to added to the machine PHI node as
4298 // the input for this MBB.
4299 MVT::ValueType VT = TLI.getValueType(PN->getType());
4300 unsigned NumElements;
4301 if (VT != MVT::Vector)
4302 NumElements = TLI.getNumElements(VT);
4304 MVT::ValueType VT1,VT2;
4306 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
4309 for (unsigned i = 0, e = NumElements; i != e; ++i)
4310 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4313 ConstantsOut.clear();
4315 // Turn all of the unordered chains into one factored node.
4316 if (!UnorderedChains.empty()) {
4317 SDOperand Root = SDL.getRoot();
4318 if (Root.getOpcode() != ISD::EntryToken) {
4319 unsigned i = 0, e = UnorderedChains.size();
4320 for (; i != e; ++i) {
4321 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4322 if (UnorderedChains[i].Val->getOperand(0) == Root)
4323 break; // Don't add the root if we already indirectly depend on it.
4327 UnorderedChains.push_back(Root);
4329 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4330 &UnorderedChains[0], UnorderedChains.size()));
4333 // Lower the terminator after the copies are emitted.
4334 SDL.visit(*LLVMBB->getTerminator());
4336 // Copy over any CaseBlock records that may now exist due to SwitchInst
4337 // lowering, as well as any jump table information.
4338 SwitchCases.clear();
4339 SwitchCases = SDL.SwitchCases;
4342 // Make sure the root of the DAG is up-to-date.
4343 DAG.setRoot(SDL.getRoot());
4346 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4347 // Get alias analysis for load/store combining.
4348 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4350 // Run the DAG combiner in pre-legalize mode.
4351 DAG.Combine(false, AA);
4353 DOUT << "Lowered selection DAG:\n";
4356 // Second step, hack on the DAG until it only uses operations and types that
4357 // the target supports.
4360 DOUT << "Legalized selection DAG:\n";
4363 // Run the DAG combiner in post-legalize mode.
4364 DAG.Combine(true, AA);
4366 if (ViewISelDAGs) DAG.viewGraph();
4368 // Third, instruction select all of the operations to machine code, adding the
4369 // code to the MachineBasicBlock.
4370 InstructionSelectBasicBlock(DAG);
4372 DOUT << "Selected machine code:\n";
4376 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4377 FunctionLoweringInfo &FuncInfo) {
4378 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4380 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4383 // First step, lower LLVM code to some DAG. This DAG may use operations and
4384 // types that are not supported by the target.
4385 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4387 // Second step, emit the lowered DAG as machine code.
4388 CodeGenAndEmitDAG(DAG);
4391 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4392 // PHI nodes in successors.
4393 if (SwitchCases.empty() && JT.Reg == 0) {
4394 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4395 MachineInstr *PHI = PHINodesToUpdate[i].first;
4396 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4397 "This is not a machine PHI node that we are updating!");
4398 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4399 PHI->addMachineBasicBlockOperand(BB);
4404 // If the JumpTable record is filled in, then we need to emit a jump table.
4405 // Updating the PHI nodes is tricky in this case, since we need to determine
4406 // whether the PHI is a successor of the range check MBB or the jump table MBB
4408 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4409 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4411 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4412 MachineBasicBlock *RangeBB = BB;
4413 // Set the current basic block to the mbb we wish to insert the code into
4415 SDL.setCurrentBasicBlock(BB);
4417 SDL.visitJumpTable(JT);
4418 SDAG.setRoot(SDL.getRoot());
4419 CodeGenAndEmitDAG(SDAG);
4421 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4422 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4423 MachineBasicBlock *PHIBB = PHI->getParent();
4424 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4425 "This is not a machine PHI node that we are updating!");
4426 if (PHIBB == JT.Default) {
4427 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4428 PHI->addMachineBasicBlockOperand(RangeBB);
4430 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4431 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4432 PHI->addMachineBasicBlockOperand(BB);
4438 // If the switch block involved a branch to one of the actual successors, we
4439 // need to update PHI nodes in that block.
4440 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4441 MachineInstr *PHI = PHINodesToUpdate[i].first;
4442 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4443 "This is not a machine PHI node that we are updating!");
4444 if (BB->isSuccessor(PHI->getParent())) {
4445 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4446 PHI->addMachineBasicBlockOperand(BB);
4450 // If we generated any switch lowering information, build and codegen any
4451 // additional DAGs necessary.
4452 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4453 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4455 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4457 // Set the current basic block to the mbb we wish to insert the code into
4458 BB = SwitchCases[i].ThisBB;
4459 SDL.setCurrentBasicBlock(BB);
4462 SDL.visitSwitchCase(SwitchCases[i]);
4463 SDAG.setRoot(SDL.getRoot());
4464 CodeGenAndEmitDAG(SDAG);
4466 // Handle any PHI nodes in successors of this chunk, as if we were coming
4467 // from the original BB before switch expansion. Note that PHI nodes can
4468 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4469 // handle them the right number of times.
4470 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4471 for (MachineBasicBlock::iterator Phi = BB->begin();
4472 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4473 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4474 for (unsigned pn = 0; ; ++pn) {
4475 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4476 if (PHINodesToUpdate[pn].first == Phi) {
4477 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4478 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4484 // Don't process RHS if same block as LHS.
4485 if (BB == SwitchCases[i].FalseBB)
4486 SwitchCases[i].FalseBB = 0;
4488 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4489 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4490 SwitchCases[i].FalseBB = 0;
4492 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4497 //===----------------------------------------------------------------------===//
4498 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4499 /// target node in the graph.
4500 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4501 if (ViewSchedDAGs) DAG.viewGraph();
4503 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4507 RegisterScheduler::setDefault(Ctor);
4510 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4516 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4517 return new HazardRecognizer();
4520 //===----------------------------------------------------------------------===//
4521 // Helper functions used by the generated instruction selector.
4522 //===----------------------------------------------------------------------===//
4523 // Calls to these methods are generated by tblgen.
4525 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4526 /// the dag combiner simplified the 255, we still want to match. RHS is the
4527 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4528 /// specified in the .td file (e.g. 255).
4529 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4530 int64_t DesiredMaskS) {
4531 uint64_t ActualMask = RHS->getValue();
4532 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4534 // If the actual mask exactly matches, success!
4535 if (ActualMask == DesiredMask)
4538 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4539 if (ActualMask & ~DesiredMask)
4542 // Otherwise, the DAG Combiner may have proven that the value coming in is
4543 // either already zero or is not demanded. Check for known zero input bits.
4544 uint64_t NeededMask = DesiredMask & ~ActualMask;
4545 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4548 // TODO: check to see if missing bits are just not demanded.
4550 // Otherwise, this pattern doesn't match.
4554 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4555 /// the dag combiner simplified the 255, we still want to match. RHS is the
4556 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4557 /// specified in the .td file (e.g. 255).
4558 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4559 int64_t DesiredMaskS) {
4560 uint64_t ActualMask = RHS->getValue();
4561 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4563 // If the actual mask exactly matches, success!
4564 if (ActualMask == DesiredMask)
4567 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4568 if (ActualMask & ~DesiredMask)
4571 // Otherwise, the DAG Combiner may have proven that the value coming in is
4572 // either already zero or is not demanded. Check for known zero input bits.
4573 uint64_t NeededMask = DesiredMask & ~ActualMask;
4575 uint64_t KnownZero, KnownOne;
4576 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4578 // If all the missing bits in the or are already known to be set, match!
4579 if ((NeededMask & KnownOne) == NeededMask)
4582 // TODO: check to see if missing bits are just not demanded.
4584 // Otherwise, this pattern doesn't match.
4589 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4590 /// by tblgen. Others should not call it.
4591 void SelectionDAGISel::
4592 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4593 std::vector<SDOperand> InOps;
4594 std::swap(InOps, Ops);
4596 Ops.push_back(InOps[0]); // input chain.
4597 Ops.push_back(InOps[1]); // input asm string.
4599 unsigned i = 2, e = InOps.size();
4600 if (InOps[e-1].getValueType() == MVT::Flag)
4601 --e; // Don't process a flag operand if it is here.
4604 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4605 if ((Flags & 7) != 4 /*MEM*/) {
4606 // Just skip over this operand, copying the operands verbatim.
4607 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4608 i += (Flags >> 3) + 1;
4610 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4611 // Otherwise, this is a memory operand. Ask the target to select it.
4612 std::vector<SDOperand> SelOps;
4613 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4614 cerr << "Could not match memory address. Inline asm failure!\n";
4618 // Add this to the output node.
4619 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4621 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4626 // Add the flag input back if present.
4627 if (e != InOps.size())
4628 Ops.push_back(InOps.back());