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/MachineDebugInfo.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 std::map<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()->getTypeAlignment(Ty),
250 // If the alignment of the value is smaller than the size of the
251 // value, and if the size of the value is particularly small
252 // (<= 8 bytes), round up to the size of the value for potentially
253 // better performance.
255 // FIXME: This could be made better with a preferred alignment hook in
256 // TargetData. It serves primarily to 8-byte align doubles for X86.
257 if (Align < TySize && TySize <= 8) Align = TySize;
258 TySize *= CUI->getZExtValue(); // Get total allocated size.
259 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
260 StaticAllocaMap[AI] =
261 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
264 for (; BB != EB; ++BB)
265 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
266 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
267 if (!isa<AllocaInst>(I) ||
268 !StaticAllocaMap.count(cast<AllocaInst>(I)))
269 InitializeRegForValue(I);
271 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
272 // also creates the initial PHI MachineInstrs, though none of the input
273 // operands are populated.
274 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
275 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
277 MF.getBasicBlockList().push_back(MBB);
279 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
282 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
283 if (PN->use_empty()) continue;
285 MVT::ValueType VT = TLI.getValueType(PN->getType());
286 unsigned NumElements;
287 if (VT != MVT::Vector)
288 NumElements = TLI.getNumElements(VT);
290 MVT::ValueType VT1,VT2;
292 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
295 unsigned PHIReg = ValueMap[PN];
296 assert(PHIReg && "PHI node does not have an assigned virtual register!");
297 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
298 for (unsigned i = 0; i != NumElements; ++i)
299 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
304 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
305 /// the correctly promoted or expanded types. Assign these registers
306 /// consecutive vreg numbers and return the first assigned number.
307 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
308 MVT::ValueType VT = TLI.getValueType(V->getType());
310 // The number of multiples of registers that we need, to, e.g., split up
311 // a <2 x int64> -> 4 x i32 registers.
312 unsigned NumVectorRegs = 1;
314 // If this is a packed type, figure out what type it will decompose into
315 // and how many of the elements it will use.
316 if (VT == MVT::Vector) {
317 const PackedType *PTy = cast<PackedType>(V->getType());
318 unsigned NumElts = PTy->getNumElements();
319 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
321 // Divide the input until we get to a supported size. This will always
322 // end with a scalar if the target doesn't support vectors.
323 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
330 VT = getVectorType(EltTy, NumElts);
333 // The common case is that we will only create one register for this
334 // value. If we have that case, create and return the virtual register.
335 unsigned NV = TLI.getNumElements(VT);
337 // If we are promoting this value, pick the next largest supported type.
338 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
339 unsigned Reg = MakeReg(PromotedType);
340 // If this is a vector of supported or promoted types (e.g. 4 x i16),
341 // create all of the registers.
342 for (unsigned i = 1; i != NumVectorRegs; ++i)
343 MakeReg(PromotedType);
347 // If this value is represented with multiple target registers, make sure
348 // to create enough consecutive registers of the right (smaller) type.
349 VT = TLI.getTypeToExpandTo(VT);
350 unsigned R = MakeReg(VT);
351 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
356 //===----------------------------------------------------------------------===//
357 /// SelectionDAGLowering - This is the common target-independent lowering
358 /// implementation that is parameterized by a TargetLowering object.
359 /// Also, targets can overload any lowering method.
362 class SelectionDAGLowering {
363 MachineBasicBlock *CurMBB;
365 std::map<const Value*, SDOperand> NodeMap;
367 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
368 /// them up and then emit token factor nodes when possible. This allows us to
369 /// get simple disambiguation between loads without worrying about alias
371 std::vector<SDOperand> PendingLoads;
373 /// Case - A pair of values to record the Value for a switch case, and the
374 /// case's target basic block.
375 typedef std::pair<Constant*, MachineBasicBlock*> Case;
376 typedef std::vector<Case>::iterator CaseItr;
377 typedef std::pair<CaseItr, CaseItr> CaseRange;
379 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
380 /// of conditional branches.
382 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
383 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
385 /// CaseBB - The MBB in which to emit the compare and branch
386 MachineBasicBlock *CaseBB;
387 /// LT, GE - If nonzero, we know the current case value must be less-than or
388 /// greater-than-or-equal-to these Constants.
391 /// Range - A pair of iterators representing the range of case values to be
392 /// processed at this point in the binary search tree.
396 /// The comparison function for sorting Case values.
398 bool operator () (const Case& C1, const Case& C2) {
399 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
400 if (I1->getType()->isUnsigned())
401 return I1->getZExtValue() <
402 cast<const ConstantInt>(C2.first)->getZExtValue();
404 return cast<const ConstantInt>(C1.first)->getSExtValue() <
405 cast<const ConstantInt>(C2.first)->getSExtValue();
410 // TLI - This is information that describes the available target features we
411 // need for lowering. This indicates when operations are unavailable,
412 // implemented with a libcall, etc.
415 const TargetData *TD;
417 /// SwitchCases - Vector of CaseBlock structures used to communicate
418 /// SwitchInst code generation information.
419 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
420 SelectionDAGISel::JumpTable JT;
422 /// FuncInfo - Information about the function as a whole.
424 FunctionLoweringInfo &FuncInfo;
426 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
427 FunctionLoweringInfo &funcinfo)
428 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
429 JT(0,0,0,0), FuncInfo(funcinfo) {
432 /// getRoot - Return the current virtual root of the Selection DAG.
434 SDOperand getRoot() {
435 if (PendingLoads.empty())
436 return DAG.getRoot();
438 if (PendingLoads.size() == 1) {
439 SDOperand Root = PendingLoads[0];
441 PendingLoads.clear();
445 // Otherwise, we have to make a token factor node.
446 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
447 &PendingLoads[0], PendingLoads.size());
448 PendingLoads.clear();
453 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
455 void visit(Instruction &I) { visit(I.getOpcode(), I); }
457 void visit(unsigned Opcode, User &I) {
458 // Note: this doesn't use InstVisitor, because it has to work with
459 // ConstantExpr's in addition to instructions.
461 default: assert(0 && "Unknown instruction type encountered!");
463 // Build the switch statement using the Instruction.def file.
464 #define HANDLE_INST(NUM, OPCODE, CLASS) \
465 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
466 #include "llvm/Instruction.def"
470 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
472 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
473 const Value *SV, SDOperand Root,
476 SDOperand getIntPtrConstant(uint64_t Val) {
477 return DAG.getConstant(Val, TLI.getPointerTy());
480 SDOperand getValue(const Value *V);
482 const SDOperand &setValue(const Value *V, SDOperand NewN) {
483 SDOperand &N = NodeMap[V];
484 assert(N.Val == 0 && "Already set a value for this node!");
488 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
490 bool OutReg, bool InReg,
491 std::set<unsigned> &OutputRegs,
492 std::set<unsigned> &InputRegs);
494 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
495 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
497 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
498 void ExportFromCurrentBlock(Value *V);
500 // Terminator instructions.
501 void visitRet(ReturnInst &I);
502 void visitBr(BranchInst &I);
503 void visitSwitch(SwitchInst &I);
504 void visitUnreachable(UnreachableInst &I) { /* noop */ }
506 // Helper for visitSwitch
507 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
508 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
510 // These all get lowered before this pass.
511 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
512 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
514 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
515 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
516 void visitShift(User &I, unsigned Opcode);
517 void visitAdd(User &I) {
518 if (I.getType()->isFloatingPoint())
519 visitFPBinary(I, ISD::FADD, ISD::VADD);
521 visitIntBinary(I, ISD::ADD, ISD::VADD);
523 void visitSub(User &I);
524 void visitMul(User &I) {
525 if (I.getType()->isFloatingPoint())
526 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
528 visitIntBinary(I, ISD::MUL, ISD::VMUL);
530 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
531 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
532 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
533 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
534 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
535 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
536 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
537 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
538 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
539 void visitShl(User &I) { visitShift(I, ISD::SHL); }
540 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
541 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
542 void visitICmp(User &I);
543 void visitFCmp(User &I);
544 // Visit the conversion instructions
545 void visitTrunc(User &I);
546 void visitZExt(User &I);
547 void visitSExt(User &I);
548 void visitFPTrunc(User &I);
549 void visitFPExt(User &I);
550 void visitFPToUI(User &I);
551 void visitFPToSI(User &I);
552 void visitUIToFP(User &I);
553 void visitSIToFP(User &I);
554 void visitPtrToInt(User &I);
555 void visitIntToPtr(User &I);
556 void visitBitCast(User &I);
558 void visitExtractElement(User &I);
559 void visitInsertElement(User &I);
560 void visitShuffleVector(User &I);
562 void visitGetElementPtr(User &I);
563 void visitSelect(User &I);
565 void visitMalloc(MallocInst &I);
566 void visitFree(FreeInst &I);
567 void visitAlloca(AllocaInst &I);
568 void visitLoad(LoadInst &I);
569 void visitStore(StoreInst &I);
570 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
571 void visitCall(CallInst &I);
572 void visitInlineAsm(CallInst &I);
573 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
574 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
576 void visitVAStart(CallInst &I);
577 void visitVAArg(VAArgInst &I);
578 void visitVAEnd(CallInst &I);
579 void visitVACopy(CallInst &I);
580 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
582 void visitMemIntrinsic(CallInst &I, unsigned Op);
584 void visitUserOp1(Instruction &I) {
585 assert(0 && "UserOp1 should not exist at instruction selection time!");
588 void visitUserOp2(Instruction &I) {
589 assert(0 && "UserOp2 should not exist at instruction selection time!");
593 } // end namespace llvm
595 SDOperand SelectionDAGLowering::getValue(const Value *V) {
596 SDOperand &N = NodeMap[V];
599 const Type *VTy = V->getType();
600 MVT::ValueType VT = TLI.getValueType(VTy);
601 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
603 visit(CE->getOpcode(), *CE);
604 assert(N.Val && "visit didn't populate the ValueMap!");
606 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
607 return N = DAG.getGlobalAddress(GV, VT);
608 } else if (isa<ConstantPointerNull>(C)) {
609 return N = DAG.getConstant(0, TLI.getPointerTy());
610 } else if (isa<UndefValue>(C)) {
611 if (!isa<PackedType>(VTy))
612 return N = DAG.getNode(ISD::UNDEF, VT);
614 // Create a VBUILD_VECTOR of undef nodes.
615 const PackedType *PTy = cast<PackedType>(VTy);
616 unsigned NumElements = PTy->getNumElements();
617 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
619 SmallVector<SDOperand, 8> Ops;
620 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
622 // Create a VConstant node with generic Vector type.
623 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
624 Ops.push_back(DAG.getValueType(PVT));
625 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
626 &Ops[0], Ops.size());
627 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
628 return N = DAG.getConstantFP(CFP->getValue(), VT);
629 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
630 unsigned NumElements = PTy->getNumElements();
631 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
633 // Now that we know the number and type of the elements, push a
634 // Constant or ConstantFP node onto the ops list for each element of
635 // the packed constant.
636 SmallVector<SDOperand, 8> Ops;
637 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
638 for (unsigned i = 0; i != NumElements; ++i)
639 Ops.push_back(getValue(CP->getOperand(i)));
641 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
643 if (MVT::isFloatingPoint(PVT))
644 Op = DAG.getConstantFP(0, PVT);
646 Op = DAG.getConstant(0, PVT);
647 Ops.assign(NumElements, Op);
650 // Create a VBUILD_VECTOR node with generic Vector type.
651 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
652 Ops.push_back(DAG.getValueType(PVT));
653 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
655 // Canonicalize all constant ints to be unsigned.
656 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
660 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
661 std::map<const AllocaInst*, int>::iterator SI =
662 FuncInfo.StaticAllocaMap.find(AI);
663 if (SI != FuncInfo.StaticAllocaMap.end())
664 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
667 std::map<const Value*, unsigned>::const_iterator VMI =
668 FuncInfo.ValueMap.find(V);
669 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
671 unsigned InReg = VMI->second;
673 // If this type is not legal, make it so now.
674 if (VT != MVT::Vector) {
675 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
676 // Source must be expanded. This input value is actually coming from the
677 // register pair VMI->second and VMI->second+1.
678 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
679 unsigned NumVals = TLI.getNumElements(VT);
680 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
682 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
684 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
685 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
686 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
689 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
690 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
691 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
692 N = MVT::isFloatingPoint(VT)
693 ? DAG.getNode(ISD::FP_ROUND, VT, N)
694 : DAG.getNode(ISD::TRUNCATE, VT, N);
697 // Otherwise, if this is a vector, make it available as a generic vector
699 MVT::ValueType PTyElementVT, PTyLegalElementVT;
700 const PackedType *PTy = cast<PackedType>(VTy);
701 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
704 // Build a VBUILD_VECTOR with the input registers.
705 SmallVector<SDOperand, 8> Ops;
706 if (PTyElementVT == PTyLegalElementVT) {
707 // If the value types are legal, just VBUILD the CopyFromReg nodes.
708 for (unsigned i = 0; i != NE; ++i)
709 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
711 } else if (PTyElementVT < PTyLegalElementVT) {
712 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
713 for (unsigned i = 0; i != NE; ++i) {
714 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
716 if (MVT::isFloatingPoint(PTyElementVT))
717 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
719 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
723 // If the register was expanded, use BUILD_PAIR.
724 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
725 for (unsigned i = 0; i != NE/2; ++i) {
726 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
728 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
730 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
734 Ops.push_back(DAG.getConstant(NE, MVT::i32));
735 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
736 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
738 // Finally, use a VBIT_CONVERT to make this available as the appropriate
740 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
741 DAG.getConstant(PTy->getNumElements(),
743 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
750 void SelectionDAGLowering::visitRet(ReturnInst &I) {
751 if (I.getNumOperands() == 0) {
752 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
755 SmallVector<SDOperand, 8> NewValues;
756 NewValues.push_back(getRoot());
757 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
758 SDOperand RetOp = getValue(I.getOperand(i));
759 bool isSigned = I.getOperand(i)->getType()->isSigned();
761 // If this is an integer return value, we need to promote it ourselves to
762 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
764 // FIXME: C calling convention requires the return type to be promoted to
765 // at least 32-bit. But this is not necessary for non-C calling conventions.
766 if (MVT::isInteger(RetOp.getValueType()) &&
767 RetOp.getValueType() < MVT::i64) {
768 MVT::ValueType TmpVT;
769 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
770 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
775 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
777 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
779 NewValues.push_back(RetOp);
780 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
782 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
783 &NewValues[0], NewValues.size()));
786 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
787 /// the current basic block, add it to ValueMap now so that we'll get a
789 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
790 // No need to export constants.
791 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
794 if (FuncInfo.isExportedInst(V)) return;
796 unsigned Reg = FuncInfo.InitializeRegForValue(V);
797 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
800 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
801 const BasicBlock *FromBB) {
802 // The operands of the setcc have to be in this block. We don't know
803 // how to export them from some other block.
804 if (Instruction *VI = dyn_cast<Instruction>(V)) {
805 // Can export from current BB.
806 if (VI->getParent() == FromBB)
809 // Is already exported, noop.
810 return FuncInfo.isExportedInst(V);
813 // If this is an argument, we can export it if the BB is the entry block or
814 // if it is already exported.
815 if (isa<Argument>(V)) {
816 if (FromBB == &FromBB->getParent()->getEntryBlock())
819 // Otherwise, can only export this if it is already exported.
820 return FuncInfo.isExportedInst(V);
823 // Otherwise, constants can always be exported.
827 static bool InBlock(const Value *V, const BasicBlock *BB) {
828 if (const Instruction *I = dyn_cast<Instruction>(V))
829 return I->getParent() == BB;
833 /// FindMergedConditions - If Cond is an expression like
834 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
835 MachineBasicBlock *TBB,
836 MachineBasicBlock *FBB,
837 MachineBasicBlock *CurBB,
839 // If this node is not part of the or/and tree, emit it as a branch.
840 Instruction *BOp = dyn_cast<Instruction>(Cond);
842 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
843 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
844 BOp->getParent() != CurBB->getBasicBlock() ||
845 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
846 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
847 const BasicBlock *BB = CurBB->getBasicBlock();
849 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
850 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
851 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
852 // The operands of the setcc have to be in this block. We don't know
853 // how to export them from some other block. If this is the first
854 // block of the sequence, no exporting is needed.
856 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
857 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
858 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
859 II->getOperand(2), TBB, FBB, CurBB);
860 SwitchCases.push_back(CB);
865 // If the leaf of the tree is a comparison, merge the condition into
867 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
868 // The operands of the cmp have to be in this block. We don't know
869 // how to export them from some other block. If this is the first block
870 // of the sequence, no exporting is needed.
872 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
873 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
874 BOp = cast<Instruction>(Cond);
875 ISD::CondCode Condition;
876 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
877 switch (IC->getPredicate()) {
878 default: assert(0 && "Unknown icmp predicate opcode!");
879 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
880 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
881 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
882 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
883 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
884 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
885 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
886 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
887 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
888 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
890 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
891 ISD::CondCode FPC, FOC;
892 switch (FC->getPredicate()) {
893 default: assert(0 && "Unknown fcmp predicate opcode!");
894 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
895 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
896 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
897 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
898 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
899 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
900 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
901 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
902 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
903 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
904 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
905 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
906 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
907 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
908 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
909 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
911 if (FiniteOnlyFPMath())
916 assert(0 && "Unknown compare instruction");
919 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
920 BOp->getOperand(1), TBB, FBB, CurBB);
921 SwitchCases.push_back(CB);
925 // Create a CaseBlock record representing this branch.
926 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
928 SwitchCases.push_back(CB);
933 // Create TmpBB after CurBB.
934 MachineFunction::iterator BBI = CurBB;
935 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
936 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
938 if (Opc == Instruction::Or) {
947 // Emit the LHS condition.
948 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
950 // Emit the RHS condition into TmpBB.
951 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
953 assert(Opc == Instruction::And && "Unknown merge op!");
961 // This requires creation of TmpBB after CurBB.
963 // Emit the LHS condition.
964 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
966 // Emit the RHS condition into TmpBB.
967 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
971 /// If the set of cases should be emitted as a series of branches, return true.
972 /// If we should emit this as a bunch of and/or'd together conditions, return
975 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
976 if (Cases.size() != 2) return true;
978 // If this is two comparisons of the same values or'd or and'd together, they
979 // will get folded into a single comparison, so don't emit two blocks.
980 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
981 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
982 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
983 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
990 void SelectionDAGLowering::visitBr(BranchInst &I) {
991 // Update machine-CFG edges.
992 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
994 // Figure out which block is immediately after the current one.
995 MachineBasicBlock *NextBlock = 0;
996 MachineFunction::iterator BBI = CurMBB;
997 if (++BBI != CurMBB->getParent()->end())
1000 if (I.isUnconditional()) {
1001 // If this is not a fall-through branch, emit the branch.
1002 if (Succ0MBB != NextBlock)
1003 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1004 DAG.getBasicBlock(Succ0MBB)));
1006 // Update machine-CFG edges.
1007 CurMBB->addSuccessor(Succ0MBB);
1012 // If this condition is one of the special cases we handle, do special stuff
1014 Value *CondVal = I.getCondition();
1015 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1017 // If this is a series of conditions that are or'd or and'd together, emit
1018 // this as a sequence of branches instead of setcc's with and/or operations.
1019 // For example, instead of something like:
1032 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1033 if (BOp->hasOneUse() &&
1034 (BOp->getOpcode() == Instruction::And ||
1035 BOp->getOpcode() == Instruction::Or)) {
1036 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1037 // If the compares in later blocks need to use values not currently
1038 // exported from this block, export them now. This block should always
1039 // be the first entry.
1040 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1042 // Allow some cases to be rejected.
1043 if (ShouldEmitAsBranches(SwitchCases)) {
1044 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1045 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1046 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1049 // Emit the branch for this block.
1050 visitSwitchCase(SwitchCases[0]);
1051 SwitchCases.erase(SwitchCases.begin());
1055 // Okay, we decided not to do this, remove any inserted MBB's and clear
1057 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1058 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1060 SwitchCases.clear();
1064 // Create a CaseBlock record representing this branch.
1065 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
1066 Succ0MBB, Succ1MBB, CurMBB);
1067 // Use visitSwitchCase to actually insert the fast branch sequence for this
1069 visitSwitchCase(CB);
1072 /// visitSwitchCase - Emits the necessary code to represent a single node in
1073 /// the binary search tree resulting from lowering a switch instruction.
1074 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1076 SDOperand CondLHS = getValue(CB.CmpLHS);
1078 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1079 // handle common cases produced by branch lowering.
1080 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
1082 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1083 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1084 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1086 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1088 // Set NextBlock to be the MBB immediately after the current one, if any.
1089 // This is used to avoid emitting unnecessary branches to the next block.
1090 MachineBasicBlock *NextBlock = 0;
1091 MachineFunction::iterator BBI = CurMBB;
1092 if (++BBI != CurMBB->getParent()->end())
1095 // If the lhs block is the next block, invert the condition so that we can
1096 // fall through to the lhs instead of the rhs block.
1097 if (CB.TrueBB == NextBlock) {
1098 std::swap(CB.TrueBB, CB.FalseBB);
1099 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1100 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1102 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1103 DAG.getBasicBlock(CB.TrueBB));
1104 if (CB.FalseBB == NextBlock)
1105 DAG.setRoot(BrCond);
1107 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1108 DAG.getBasicBlock(CB.FalseBB)));
1109 // Update successor info
1110 CurMBB->addSuccessor(CB.TrueBB);
1111 CurMBB->addSuccessor(CB.FalseBB);
1114 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1115 // Emit the code for the jump table
1116 MVT::ValueType PTy = TLI.getPointerTy();
1117 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1118 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1119 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1124 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1125 // Figure out which block is immediately after the current one.
1126 MachineBasicBlock *NextBlock = 0;
1127 MachineFunction::iterator BBI = CurMBB;
1129 if (++BBI != CurMBB->getParent()->end())
1132 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1134 // If there is only the default destination, branch to it if it is not the
1135 // next basic block. Otherwise, just fall through.
1136 if (I.getNumOperands() == 2) {
1137 // Update machine-CFG edges.
1139 // If this is not a fall-through branch, emit the branch.
1140 if (Default != NextBlock)
1141 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1142 DAG.getBasicBlock(Default)));
1144 CurMBB->addSuccessor(Default);
1148 // If there are any non-default case statements, create a vector of Cases
1149 // representing each one, and sort the vector so that we can efficiently
1150 // create a binary search tree from them.
1151 std::vector<Case> Cases;
1153 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1154 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1155 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1158 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1160 // Get the Value to be switched on and default basic blocks, which will be
1161 // inserted into CaseBlock records, representing basic blocks in the binary
1163 Value *SV = I.getOperand(0);
1165 // Get the MachineFunction which holds the current MBB. This is used during
1166 // emission of jump tables, and when inserting any additional MBBs necessary
1167 // to represent the switch.
1168 MachineFunction *CurMF = CurMBB->getParent();
1169 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1171 // If the switch has few cases (two or less) emit a series of specific
1173 if (Cases.size() < 3) {
1174 // TODO: If any two of the cases has the same destination, and if one value
1175 // is the same as the other, but has one bit unset that the other has set,
1176 // use bit manipulation to do two compares at once. For example:
1177 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1179 // Rearrange the case blocks so that the last one falls through if possible.
1180 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1181 // The last case block won't fall through into 'NextBlock' if we emit the
1182 // branches in this order. See if rearranging a case value would help.
1183 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1184 if (Cases[i].second == NextBlock) {
1185 std::swap(Cases[i], Cases.back());
1191 // Create a CaseBlock record representing a conditional branch to
1192 // the Case's target mbb if the value being switched on SV is equal
1194 MachineBasicBlock *CurBlock = CurMBB;
1195 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1196 MachineBasicBlock *FallThrough;
1198 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1199 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1201 // If the last case doesn't match, go to the default block.
1202 FallThrough = Default;
1205 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1206 Cases[i].second, FallThrough, CurBlock);
1208 // If emitting the first comparison, just call visitSwitchCase to emit the
1209 // code into the current block. Otherwise, push the CaseBlock onto the
1210 // vector to be later processed by SDISel, and insert the node's MBB
1211 // before the next MBB.
1212 if (CurBlock == CurMBB)
1213 visitSwitchCase(CB);
1215 SwitchCases.push_back(CB);
1217 CurBlock = FallThrough;
1222 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1223 // target supports indirect branches, then emit a jump table rather than
1224 // lowering the switch to a binary tree of conditional branches.
1225 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1226 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1228 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1229 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
1230 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1232 if (Density >= 0.3125) {
1233 // Create a new basic block to hold the code for loading the address
1234 // of the jump table, and jumping to it. Update successor information;
1235 // we will either branch to the default case for the switch, or the jump
1237 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1238 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1239 CurMBB->addSuccessor(Default);
1240 CurMBB->addSuccessor(JumpTableBB);
1242 // Subtract the lowest switch case value from the value being switched on
1243 // and conditional branch to default mbb if the result is greater than the
1244 // difference between smallest and largest cases.
1245 SDOperand SwitchOp = getValue(SV);
1246 MVT::ValueType VT = SwitchOp.getValueType();
1247 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1248 DAG.getConstant(First, VT));
1250 // The SDNode we just created, which holds the value being switched on
1251 // minus the the smallest case value, needs to be copied to a virtual
1252 // register so it can be used as an index into the jump table in a
1253 // subsequent basic block. This value may be smaller or larger than the
1254 // target's pointer type, and therefore require extension or truncating.
1255 if (VT > TLI.getPointerTy())
1256 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1258 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1260 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1261 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1263 // Emit the range check for the jump table, and branch to the default
1264 // block for the switch statement if the value being switched on exceeds
1265 // the largest case in the switch.
1266 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1267 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1268 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1269 DAG.getBasicBlock(Default)));
1271 // Build a vector of destination BBs, corresponding to each target
1272 // of the jump table. If the value of the jump table slot corresponds to
1273 // a case statement, push the case's BB onto the vector, otherwise, push
1275 std::vector<MachineBasicBlock*> DestBBs;
1276 uint64_t TEI = First;
1277 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1278 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
1279 DestBBs.push_back(ii->second);
1282 DestBBs.push_back(Default);
1285 // Update successor info. Add one edge to each unique successor.
1286 // Vector bool would be better, but vector<bool> is really slow.
1287 std::vector<unsigned char> SuccsHandled;
1288 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1290 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1291 E = DestBBs.end(); I != E; ++I) {
1292 if (!SuccsHandled[(*I)->getNumber()]) {
1293 SuccsHandled[(*I)->getNumber()] = true;
1294 JumpTableBB->addSuccessor(*I);
1298 // Create a jump table index for this jump table, or return an existing
1300 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1302 // Set the jump table information so that we can codegen it as a second
1303 // MachineBasicBlock
1304 JT.Reg = JumpTableReg;
1306 JT.MBB = JumpTableBB;
1307 JT.Default = Default;
1312 // Push the initial CaseRec onto the worklist
1313 std::vector<CaseRec> CaseVec;
1314 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1316 while (!CaseVec.empty()) {
1317 // Grab a record representing a case range to process off the worklist
1318 CaseRec CR = CaseVec.back();
1321 // Size is the number of Cases represented by this range. If Size is 1,
1322 // then we are processing a leaf of the binary search tree. Otherwise,
1323 // we need to pick a pivot, and push left and right ranges onto the
1325 unsigned Size = CR.Range.second - CR.Range.first;
1328 // Create a CaseBlock record representing a conditional branch to
1329 // the Case's target mbb if the value being switched on SV is equal
1330 // to C. Otherwise, branch to default.
1331 Constant *C = CR.Range.first->first;
1332 MachineBasicBlock *Target = CR.Range.first->second;
1333 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1336 // If the MBB representing the leaf node is the current MBB, then just
1337 // call visitSwitchCase to emit the code into the current block.
1338 // Otherwise, push the CaseBlock onto the vector to be later processed
1339 // by SDISel, and insert the node's MBB before the next MBB.
1340 if (CR.CaseBB == CurMBB)
1341 visitSwitchCase(CB);
1343 SwitchCases.push_back(CB);
1345 // split case range at pivot
1346 CaseItr Pivot = CR.Range.first + (Size / 2);
1347 CaseRange LHSR(CR.Range.first, Pivot);
1348 CaseRange RHSR(Pivot, CR.Range.second);
1349 Constant *C = Pivot->first;
1350 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1352 // We know that we branch to the LHS if the Value being switched on is
1353 // less than the Pivot value, C. We use this to optimize our binary
1354 // tree a bit, by recognizing that if SV is greater than or equal to the
1355 // LHS's Case Value, and that Case Value is exactly one less than the
1356 // Pivot's Value, then we can branch directly to the LHS's Target,
1357 // rather than creating a leaf node for it.
1358 if ((LHSR.second - LHSR.first) == 1 &&
1359 LHSR.first->first == CR.GE &&
1360 cast<ConstantIntegral>(C)->getZExtValue() ==
1361 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
1362 TrueBB = LHSR.first->second;
1364 TrueBB = new MachineBasicBlock(LLVMBB);
1365 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1366 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1369 // Similar to the optimization above, if the Value being switched on is
1370 // known to be less than the Constant CR.LT, and the current Case Value
1371 // is CR.LT - 1, then we can branch directly to the target block for
1372 // the current Case Value, rather than emitting a RHS leaf node for it.
1373 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1374 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1375 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
1376 FalseBB = RHSR.first->second;
1378 FalseBB = new MachineBasicBlock(LLVMBB);
1379 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1380 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1383 // Create a CaseBlock record representing a conditional branch to
1384 // the LHS node if the value being switched on SV is less than C.
1385 // Otherwise, branch to LHS.
1386 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1387 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
1389 if (CR.CaseBB == CurMBB)
1390 visitSwitchCase(CB);
1392 SwitchCases.push_back(CB);
1397 void SelectionDAGLowering::visitSub(User &I) {
1398 // -0.0 - X --> fneg
1399 if (I.getType()->isFloatingPoint()) {
1400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1401 if (CFP->isExactlyValue(-0.0)) {
1402 SDOperand Op2 = getValue(I.getOperand(1));
1403 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1406 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1408 visitIntBinary(I, ISD::SUB, ISD::VSUB);
1412 SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
1413 const Type *Ty = I.getType();
1414 SDOperand Op1 = getValue(I.getOperand(0));
1415 SDOperand Op2 = getValue(I.getOperand(1));
1417 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1418 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1419 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1420 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1422 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1427 SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1428 const Type *Ty = I.getType();
1429 SDOperand Op1 = getValue(I.getOperand(0));
1430 SDOperand Op2 = getValue(I.getOperand(1));
1432 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1433 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1434 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1435 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1437 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1441 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1442 SDOperand Op1 = getValue(I.getOperand(0));
1443 SDOperand Op2 = getValue(I.getOperand(1));
1445 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1447 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1450 void SelectionDAGLowering::visitICmp(User &I) {
1451 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1452 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1453 predicate = IC->getPredicate();
1454 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1455 predicate = ICmpInst::Predicate(IC->getPredicate());
1456 SDOperand Op1 = getValue(I.getOperand(0));
1457 SDOperand Op2 = getValue(I.getOperand(1));
1458 ISD::CondCode Opcode;
1459 switch (predicate) {
1460 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1461 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1462 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1463 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1464 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1465 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1466 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1467 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1468 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1469 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1471 assert(!"Invalid ICmp predicate value");
1472 Opcode = ISD::SETEQ;
1475 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1478 void SelectionDAGLowering::visitFCmp(User &I) {
1479 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1480 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1481 predicate = FC->getPredicate();
1482 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1483 predicate = FCmpInst::Predicate(FC->getPredicate());
1484 SDOperand Op1 = getValue(I.getOperand(0));
1485 SDOperand Op2 = getValue(I.getOperand(1));
1486 ISD::CondCode Condition, FOC, FPC;
1487 switch (predicate) {
1488 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1489 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1490 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1491 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1492 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1493 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1494 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1495 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1496 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1497 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1498 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1499 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1500 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1501 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1502 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1503 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1505 assert(!"Invalid FCmp predicate value");
1506 FOC = FPC = ISD::SETFALSE;
1509 if (FiniteOnlyFPMath())
1513 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
1516 void SelectionDAGLowering::visitSelect(User &I) {
1517 SDOperand Cond = getValue(I.getOperand(0));
1518 SDOperand TrueVal = getValue(I.getOperand(1));
1519 SDOperand FalseVal = getValue(I.getOperand(2));
1520 if (!isa<PackedType>(I.getType())) {
1521 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1522 TrueVal, FalseVal));
1524 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1525 *(TrueVal.Val->op_end()-2),
1526 *(TrueVal.Val->op_end()-1)));
1531 void SelectionDAGLowering::visitTrunc(User &I) {
1532 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1533 SDOperand N = getValue(I.getOperand(0));
1534 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1535 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1538 void SelectionDAGLowering::visitZExt(User &I) {
1539 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1540 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1541 SDOperand N = getValue(I.getOperand(0));
1542 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1543 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1546 void SelectionDAGLowering::visitSExt(User &I) {
1547 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1548 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1549 SDOperand N = getValue(I.getOperand(0));
1550 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1551 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1554 void SelectionDAGLowering::visitFPTrunc(User &I) {
1555 // FPTrunc is never a no-op cast, no need to check
1556 SDOperand N = getValue(I.getOperand(0));
1557 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1558 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1561 void SelectionDAGLowering::visitFPExt(User &I){
1562 // FPTrunc is never a no-op cast, no need to check
1563 SDOperand N = getValue(I.getOperand(0));
1564 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1565 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1568 void SelectionDAGLowering::visitFPToUI(User &I) {
1569 // FPToUI is never a no-op cast, no need to check
1570 SDOperand N = getValue(I.getOperand(0));
1571 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1572 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1575 void SelectionDAGLowering::visitFPToSI(User &I) {
1576 // FPToSI is never a no-op cast, no need to check
1577 SDOperand N = getValue(I.getOperand(0));
1578 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1579 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1582 void SelectionDAGLowering::visitUIToFP(User &I) {
1583 // UIToFP is never a no-op cast, no need to check
1584 SDOperand N = getValue(I.getOperand(0));
1585 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1586 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1589 void SelectionDAGLowering::visitSIToFP(User &I){
1590 // UIToFP is never a no-op cast, no need to check
1591 SDOperand N = getValue(I.getOperand(0));
1592 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1593 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1596 void SelectionDAGLowering::visitPtrToInt(User &I) {
1597 // What to do depends on the size of the integer and the size of the pointer.
1598 // We can either truncate, zero extend, or no-op, accordingly.
1599 SDOperand N = getValue(I.getOperand(0));
1600 MVT::ValueType SrcVT = N.getValueType();
1601 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1603 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1604 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1606 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1607 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1608 setValue(&I, Result);
1611 void SelectionDAGLowering::visitIntToPtr(User &I) {
1612 // What to do depends on the size of the integer and the size of the pointer.
1613 // We can either truncate, zero extend, or no-op, accordingly.
1614 SDOperand N = getValue(I.getOperand(0));
1615 MVT::ValueType SrcVT = N.getValueType();
1616 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1617 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1618 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1620 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1621 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1624 void SelectionDAGLowering::visitBitCast(User &I) {
1625 SDOperand N = getValue(I.getOperand(0));
1626 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1627 if (DestVT == MVT::Vector) {
1628 // This is a cast to a vector from something else.
1629 // Get information about the output vector.
1630 const PackedType *DestTy = cast<PackedType>(I.getType());
1631 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1632 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1633 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1634 DAG.getValueType(EltVT)));
1637 MVT::ValueType SrcVT = N.getValueType();
1638 if (SrcVT == MVT::Vector) {
1639 // This is a cast from a vctor to something else.
1640 // Get information about the input vector.
1641 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1645 // BitCast assures us that source and destination are the same size so this
1646 // is either a BIT_CONVERT or a no-op.
1647 if (DestVT != N.getValueType())
1648 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1650 setValue(&I, N); // noop cast.
1653 void SelectionDAGLowering::visitInsertElement(User &I) {
1654 SDOperand InVec = getValue(I.getOperand(0));
1655 SDOperand InVal = getValue(I.getOperand(1));
1656 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1657 getValue(I.getOperand(2)));
1659 SDOperand Num = *(InVec.Val->op_end()-2);
1660 SDOperand Typ = *(InVec.Val->op_end()-1);
1661 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1662 InVec, InVal, InIdx, Num, Typ));
1665 void SelectionDAGLowering::visitExtractElement(User &I) {
1666 SDOperand InVec = getValue(I.getOperand(0));
1667 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1668 getValue(I.getOperand(1)));
1669 SDOperand Typ = *(InVec.Val->op_end()-1);
1670 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1671 TLI.getValueType(I.getType()), InVec, InIdx));
1674 void SelectionDAGLowering::visitShuffleVector(User &I) {
1675 SDOperand V1 = getValue(I.getOperand(0));
1676 SDOperand V2 = getValue(I.getOperand(1));
1677 SDOperand Mask = getValue(I.getOperand(2));
1679 SDOperand Num = *(V1.Val->op_end()-2);
1680 SDOperand Typ = *(V2.Val->op_end()-1);
1681 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1682 V1, V2, Mask, Num, Typ));
1686 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1687 SDOperand N = getValue(I.getOperand(0));
1688 const Type *Ty = I.getOperand(0)->getType();
1690 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1693 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1694 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1697 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1698 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1699 getIntPtrConstant(Offset));
1701 Ty = StTy->getElementType(Field);
1703 Ty = cast<SequentialType>(Ty)->getElementType();
1705 // If this is a constant subscript, handle it quickly.
1706 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1707 if (CI->getZExtValue() == 0) continue;
1709 if (CI->getType()->isSigned())
1711 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1714 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
1715 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1719 // N = N + Idx * ElementSize;
1720 uint64_t ElementSize = TD->getTypeSize(Ty);
1721 SDOperand IdxN = getValue(Idx);
1723 // If the index is smaller or larger than intptr_t, truncate or extend
1725 if (IdxN.getValueType() < N.getValueType()) {
1726 if (Idx->getType()->isSigned())
1727 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1729 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1730 } else if (IdxN.getValueType() > N.getValueType())
1731 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1733 // If this is a multiply by a power of two, turn it into a shl
1734 // immediately. This is a very common case.
1735 if (isPowerOf2_64(ElementSize)) {
1736 unsigned Amt = Log2_64(ElementSize);
1737 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1738 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1739 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1743 SDOperand Scale = getIntPtrConstant(ElementSize);
1744 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1745 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1751 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1752 // If this is a fixed sized alloca in the entry block of the function,
1753 // allocate it statically on the stack.
1754 if (FuncInfo.StaticAllocaMap.count(&I))
1755 return; // getValue will auto-populate this.
1757 const Type *Ty = I.getAllocatedType();
1758 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1759 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1762 SDOperand AllocSize = getValue(I.getArraySize());
1763 MVT::ValueType IntPtr = TLI.getPointerTy();
1764 if (IntPtr < AllocSize.getValueType())
1765 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1766 else if (IntPtr > AllocSize.getValueType())
1767 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1769 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1770 getIntPtrConstant(TySize));
1772 // Handle alignment. If the requested alignment is less than or equal to the
1773 // stack alignment, ignore it and round the size of the allocation up to the
1774 // stack alignment size. If the size is greater than the stack alignment, we
1775 // note this in the DYNAMIC_STACKALLOC node.
1776 unsigned StackAlign =
1777 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1778 if (Align <= StackAlign) {
1780 // Add SA-1 to the size.
1781 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1782 getIntPtrConstant(StackAlign-1));
1783 // Mask out the low bits for alignment purposes.
1784 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1785 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1788 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1789 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1791 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1792 DAG.setRoot(setValue(&I, DSA).getValue(1));
1794 // Inform the Frame Information that we have just allocated a variable-sized
1796 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1799 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1800 SDOperand Ptr = getValue(I.getOperand(0));
1806 // Do not serialize non-volatile loads against each other.
1807 Root = DAG.getRoot();
1810 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1811 Root, I.isVolatile()));
1814 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1815 const Value *SV, SDOperand Root,
1818 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1819 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1820 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1821 DAG.getSrcValue(SV));
1823 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
1827 DAG.setRoot(L.getValue(1));
1829 PendingLoads.push_back(L.getValue(1));
1835 void SelectionDAGLowering::visitStore(StoreInst &I) {
1836 Value *SrcV = I.getOperand(0);
1837 SDOperand Src = getValue(SrcV);
1838 SDOperand Ptr = getValue(I.getOperand(1));
1839 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
1843 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1844 /// access memory and has no other side effects at all.
1845 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1846 #define GET_NO_MEMORY_INTRINSICS
1847 #include "llvm/Intrinsics.gen"
1848 #undef GET_NO_MEMORY_INTRINSICS
1852 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1853 // have any side-effects or if it only reads memory.
1854 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1855 #define GET_SIDE_EFFECT_INFO
1856 #include "llvm/Intrinsics.gen"
1857 #undef GET_SIDE_EFFECT_INFO
1861 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1863 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1864 unsigned Intrinsic) {
1865 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1866 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1868 // Build the operand list.
1869 SmallVector<SDOperand, 8> Ops;
1870 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1872 // We don't need to serialize loads against other loads.
1873 Ops.push_back(DAG.getRoot());
1875 Ops.push_back(getRoot());
1879 // Add the intrinsic ID as an integer operand.
1880 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1882 // Add all operands of the call to the operand list.
1883 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1884 SDOperand Op = getValue(I.getOperand(i));
1886 // If this is a vector type, force it to the right packed type.
1887 if (Op.getValueType() == MVT::Vector) {
1888 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1889 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1891 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1892 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1893 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1896 assert(TLI.isTypeLegal(Op.getValueType()) &&
1897 "Intrinsic uses a non-legal type?");
1901 std::vector<MVT::ValueType> VTs;
1902 if (I.getType() != Type::VoidTy) {
1903 MVT::ValueType VT = TLI.getValueType(I.getType());
1904 if (VT == MVT::Vector) {
1905 const PackedType *DestTy = cast<PackedType>(I.getType());
1906 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1908 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1909 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1912 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1916 VTs.push_back(MVT::Other);
1918 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1923 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1924 &Ops[0], Ops.size());
1925 else if (I.getType() != Type::VoidTy)
1926 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1927 &Ops[0], Ops.size());
1929 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1930 &Ops[0], Ops.size());
1933 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1935 PendingLoads.push_back(Chain);
1939 if (I.getType() != Type::VoidTy) {
1940 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1941 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1942 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1943 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1944 DAG.getValueType(EVT));
1946 setValue(&I, Result);
1950 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1951 /// we want to emit this as a call to a named external function, return the name
1952 /// otherwise lower it and return null.
1954 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1955 switch (Intrinsic) {
1957 // By default, turn this into a target intrinsic node.
1958 visitTargetIntrinsic(I, Intrinsic);
1960 case Intrinsic::vastart: visitVAStart(I); return 0;
1961 case Intrinsic::vaend: visitVAEnd(I); return 0;
1962 case Intrinsic::vacopy: visitVACopy(I); return 0;
1963 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1964 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1965 case Intrinsic::setjmp:
1966 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
1968 case Intrinsic::longjmp:
1969 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
1971 case Intrinsic::memcpy_i32:
1972 case Intrinsic::memcpy_i64:
1973 visitMemIntrinsic(I, ISD::MEMCPY);
1975 case Intrinsic::memset_i32:
1976 case Intrinsic::memset_i64:
1977 visitMemIntrinsic(I, ISD::MEMSET);
1979 case Intrinsic::memmove_i32:
1980 case Intrinsic::memmove_i64:
1981 visitMemIntrinsic(I, ISD::MEMMOVE);
1984 case Intrinsic::dbg_stoppoint: {
1985 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1986 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1987 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1991 Ops[1] = getValue(SPI.getLineValue());
1992 Ops[2] = getValue(SPI.getColumnValue());
1994 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1995 assert(DD && "Not a debug information descriptor");
1996 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1998 Ops[3] = DAG.getString(CompileUnit->getFileName());
1999 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2001 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2006 case Intrinsic::dbg_region_start: {
2007 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2008 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2009 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
2010 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
2011 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
2012 DAG.getConstant(LabelID, MVT::i32)));
2017 case Intrinsic::dbg_region_end: {
2018 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2019 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2020 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
2021 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
2022 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2023 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2028 case Intrinsic::dbg_func_start: {
2029 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2030 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2031 if (DebugInfo && FSI.getSubprogram() &&
2032 DebugInfo->Verify(FSI.getSubprogram())) {
2033 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
2034 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2035 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2040 case Intrinsic::dbg_declare: {
2041 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2042 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2043 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
2044 SDOperand AddressOp = getValue(DI.getAddress());
2045 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2046 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
2052 case Intrinsic::isunordered_f32:
2053 case Intrinsic::isunordered_f64:
2054 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
2055 getValue(I.getOperand(2)), ISD::SETUO));
2058 case Intrinsic::sqrt_f32:
2059 case Intrinsic::sqrt_f64:
2060 setValue(&I, DAG.getNode(ISD::FSQRT,
2061 getValue(I.getOperand(1)).getValueType(),
2062 getValue(I.getOperand(1))));
2064 case Intrinsic::powi_f32:
2065 case Intrinsic::powi_f64:
2066 setValue(&I, DAG.getNode(ISD::FPOWI,
2067 getValue(I.getOperand(1)).getValueType(),
2068 getValue(I.getOperand(1)),
2069 getValue(I.getOperand(2))));
2071 case Intrinsic::pcmarker: {
2072 SDOperand Tmp = getValue(I.getOperand(1));
2073 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2076 case Intrinsic::readcyclecounter: {
2077 SDOperand Op = getRoot();
2078 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2079 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2082 DAG.setRoot(Tmp.getValue(1));
2085 case Intrinsic::bswap_i16:
2086 case Intrinsic::bswap_i32:
2087 case Intrinsic::bswap_i64:
2088 setValue(&I, DAG.getNode(ISD::BSWAP,
2089 getValue(I.getOperand(1)).getValueType(),
2090 getValue(I.getOperand(1))));
2092 case Intrinsic::cttz_i8:
2093 case Intrinsic::cttz_i16:
2094 case Intrinsic::cttz_i32:
2095 case Intrinsic::cttz_i64:
2096 setValue(&I, DAG.getNode(ISD::CTTZ,
2097 getValue(I.getOperand(1)).getValueType(),
2098 getValue(I.getOperand(1))));
2100 case Intrinsic::ctlz_i8:
2101 case Intrinsic::ctlz_i16:
2102 case Intrinsic::ctlz_i32:
2103 case Intrinsic::ctlz_i64:
2104 setValue(&I, DAG.getNode(ISD::CTLZ,
2105 getValue(I.getOperand(1)).getValueType(),
2106 getValue(I.getOperand(1))));
2108 case Intrinsic::ctpop_i8:
2109 case Intrinsic::ctpop_i16:
2110 case Intrinsic::ctpop_i32:
2111 case Intrinsic::ctpop_i64:
2112 setValue(&I, DAG.getNode(ISD::CTPOP,
2113 getValue(I.getOperand(1)).getValueType(),
2114 getValue(I.getOperand(1))));
2116 case Intrinsic::stacksave: {
2117 SDOperand Op = getRoot();
2118 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2119 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2121 DAG.setRoot(Tmp.getValue(1));
2124 case Intrinsic::stackrestore: {
2125 SDOperand Tmp = getValue(I.getOperand(1));
2126 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2129 case Intrinsic::prefetch:
2130 // FIXME: Currently discarding prefetches.
2136 void SelectionDAGLowering::visitCall(CallInst &I) {
2137 const char *RenameFn = 0;
2138 if (Function *F = I.getCalledFunction()) {
2139 if (F->isExternal())
2140 if (unsigned IID = F->getIntrinsicID()) {
2141 RenameFn = visitIntrinsicCall(I, IID);
2144 } else { // Not an LLVM intrinsic.
2145 const std::string &Name = F->getName();
2146 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2147 if (I.getNumOperands() == 3 && // Basic sanity checks.
2148 I.getOperand(1)->getType()->isFloatingPoint() &&
2149 I.getType() == I.getOperand(1)->getType() &&
2150 I.getType() == I.getOperand(2)->getType()) {
2151 SDOperand LHS = getValue(I.getOperand(1));
2152 SDOperand RHS = getValue(I.getOperand(2));
2153 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2157 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2158 if (I.getNumOperands() == 2 && // Basic sanity checks.
2159 I.getOperand(1)->getType()->isFloatingPoint() &&
2160 I.getType() == I.getOperand(1)->getType()) {
2161 SDOperand Tmp = getValue(I.getOperand(1));
2162 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2165 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2166 if (I.getNumOperands() == 2 && // Basic sanity checks.
2167 I.getOperand(1)->getType()->isFloatingPoint() &&
2168 I.getType() == I.getOperand(1)->getType()) {
2169 SDOperand Tmp = getValue(I.getOperand(1));
2170 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2173 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2174 if (I.getNumOperands() == 2 && // Basic sanity checks.
2175 I.getOperand(1)->getType()->isFloatingPoint() &&
2176 I.getType() == I.getOperand(1)->getType()) {
2177 SDOperand Tmp = getValue(I.getOperand(1));
2178 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2183 } else if (isa<InlineAsm>(I.getOperand(0))) {
2190 Callee = getValue(I.getOperand(0));
2192 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2193 std::vector<std::pair<SDOperand, const Type*> > Args;
2194 Args.reserve(I.getNumOperands());
2195 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2196 Value *Arg = I.getOperand(i);
2197 SDOperand ArgNode = getValue(Arg);
2198 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2201 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2202 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2204 std::pair<SDOperand,SDOperand> Result =
2205 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
2206 I.isTailCall(), Callee, Args, DAG);
2207 if (I.getType() != Type::VoidTy)
2208 setValue(&I, Result.first);
2209 DAG.setRoot(Result.second);
2212 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2213 SDOperand &Chain, SDOperand &Flag)const{
2214 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2215 Chain = Val.getValue(1);
2216 Flag = Val.getValue(2);
2218 // If the result was expanded, copy from the top part.
2219 if (Regs.size() > 1) {
2220 assert(Regs.size() == 2 &&
2221 "Cannot expand to more than 2 elts yet!");
2222 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2223 Chain = Hi.getValue(1);
2224 Flag = Hi.getValue(2);
2225 if (DAG.getTargetLoweringInfo().isLittleEndian())
2226 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2228 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2231 // Otherwise, if the return value was promoted or extended, truncate it to the
2232 // appropriate type.
2233 if (RegVT == ValueVT)
2236 if (MVT::isInteger(RegVT)) {
2237 if (ValueVT < RegVT)
2238 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2240 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2242 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2246 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2247 /// specified value into the registers specified by this object. This uses
2248 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2249 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2250 SDOperand &Chain, SDOperand &Flag,
2251 MVT::ValueType PtrVT) const {
2252 if (Regs.size() == 1) {
2253 // If there is a single register and the types differ, this must be
2255 if (RegVT != ValueVT) {
2256 if (MVT::isInteger(RegVT)) {
2257 if (RegVT < ValueVT)
2258 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2260 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2262 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2264 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2265 Flag = Chain.getValue(1);
2267 std::vector<unsigned> R(Regs);
2268 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2269 std::reverse(R.begin(), R.end());
2271 for (unsigned i = 0, e = R.size(); i != e; ++i) {
2272 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2273 DAG.getConstant(i, PtrVT));
2274 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2275 Flag = Chain.getValue(1);
2280 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2281 /// operand list. This adds the code marker and includes the number of
2282 /// values added into it.
2283 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2284 std::vector<SDOperand> &Ops) const {
2285 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2286 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2287 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2290 /// isAllocatableRegister - If the specified register is safe to allocate,
2291 /// i.e. it isn't a stack pointer or some other special register, return the
2292 /// register class for the register. Otherwise, return null.
2293 static const TargetRegisterClass *
2294 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2295 const TargetLowering &TLI, const MRegisterInfo *MRI) {
2296 MVT::ValueType FoundVT = MVT::Other;
2297 const TargetRegisterClass *FoundRC = 0;
2298 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2299 E = MRI->regclass_end(); RCI != E; ++RCI) {
2300 MVT::ValueType ThisVT = MVT::Other;
2302 const TargetRegisterClass *RC = *RCI;
2303 // If none of the the value types for this register class are valid, we
2304 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2305 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2307 if (TLI.isTypeLegal(*I)) {
2308 // If we have already found this register in a different register class,
2309 // choose the one with the largest VT specified. For example, on
2310 // PowerPC, we favor f64 register classes over f32.
2311 if (FoundVT == MVT::Other ||
2312 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2319 if (ThisVT == MVT::Other) continue;
2321 // NOTE: This isn't ideal. In particular, this might allocate the
2322 // frame pointer in functions that need it (due to them not being taken
2323 // out of allocation, because a variable sized allocation hasn't been seen
2324 // yet). This is a slight code pessimization, but should still work.
2325 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2326 E = RC->allocation_order_end(MF); I != E; ++I)
2328 // We found a matching register class. Keep looking at others in case
2329 // we find one with larger registers that this physreg is also in.
2338 RegsForValue SelectionDAGLowering::
2339 GetRegistersForValue(const std::string &ConstrCode,
2340 MVT::ValueType VT, bool isOutReg, bool isInReg,
2341 std::set<unsigned> &OutputRegs,
2342 std::set<unsigned> &InputRegs) {
2343 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2344 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2345 std::vector<unsigned> Regs;
2347 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2348 MVT::ValueType RegVT;
2349 MVT::ValueType ValueVT = VT;
2351 // If this is a constraint for a specific physical register, like {r17},
2353 if (PhysReg.first) {
2354 if (VT == MVT::Other)
2355 ValueVT = *PhysReg.second->vt_begin();
2357 // Get the actual register value type. This is important, because the user
2358 // may have asked for (e.g.) the AX register in i32 type. We need to
2359 // remember that AX is actually i16 to get the right extension.
2360 RegVT = *PhysReg.second->vt_begin();
2362 // This is a explicit reference to a physical register.
2363 Regs.push_back(PhysReg.first);
2365 // If this is an expanded reference, add the rest of the regs to Regs.
2367 TargetRegisterClass::iterator I = PhysReg.second->begin();
2368 TargetRegisterClass::iterator E = PhysReg.second->end();
2369 for (; *I != PhysReg.first; ++I)
2370 assert(I != E && "Didn't find reg!");
2372 // Already added the first reg.
2374 for (; NumRegs; --NumRegs, ++I) {
2375 assert(I != E && "Ran out of registers to allocate!");
2379 return RegsForValue(Regs, RegVT, ValueVT);
2382 // Otherwise, if this was a reference to an LLVM register class, create vregs
2383 // for this reference.
2384 std::vector<unsigned> RegClassRegs;
2385 if (PhysReg.second) {
2386 // If this is an early clobber or tied register, our regalloc doesn't know
2387 // how to maintain the constraint. If it isn't, go ahead and create vreg
2388 // and let the regalloc do the right thing.
2389 if (!isOutReg || !isInReg) {
2390 if (VT == MVT::Other)
2391 ValueVT = *PhysReg.second->vt_begin();
2392 RegVT = *PhysReg.second->vt_begin();
2394 // Create the appropriate number of virtual registers.
2395 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2396 for (; NumRegs; --NumRegs)
2397 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2399 return RegsForValue(Regs, RegVT, ValueVT);
2402 // Otherwise, we can't allocate it. Let the code below figure out how to
2403 // maintain these constraints.
2404 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2407 // This is a reference to a register class that doesn't directly correspond
2408 // to an LLVM register class. Allocate NumRegs consecutive, available,
2409 // registers from the class.
2410 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2413 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2414 MachineFunction &MF = *CurMBB->getParent();
2415 unsigned NumAllocated = 0;
2416 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2417 unsigned Reg = RegClassRegs[i];
2418 // See if this register is available.
2419 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2420 (isInReg && InputRegs.count(Reg))) { // Already used.
2421 // Make sure we find consecutive registers.
2426 // Check to see if this register is allocatable (i.e. don't give out the
2428 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2430 // Make sure we find consecutive registers.
2435 // Okay, this register is good, we can use it.
2438 // If we allocated enough consecutive
2439 if (NumAllocated == NumRegs) {
2440 unsigned RegStart = (i-NumAllocated)+1;
2441 unsigned RegEnd = i+1;
2442 // Mark all of the allocated registers used.
2443 for (unsigned i = RegStart; i != RegEnd; ++i) {
2444 unsigned Reg = RegClassRegs[i];
2445 Regs.push_back(Reg);
2446 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2447 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2450 return RegsForValue(Regs, *RC->vt_begin(), VT);
2454 // Otherwise, we couldn't allocate enough registers for this.
2455 return RegsForValue();
2459 /// visitInlineAsm - Handle a call to an InlineAsm object.
2461 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2462 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2464 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2467 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2468 std::vector<MVT::ValueType> ConstraintVTs;
2470 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2471 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2472 /// if it is a def of that register.
2473 std::vector<SDOperand> AsmNodeOperands;
2474 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2475 AsmNodeOperands.push_back(AsmStr);
2477 SDOperand Chain = getRoot();
2480 // We fully assign registers here at isel time. This is not optimal, but
2481 // should work. For register classes that correspond to LLVM classes, we
2482 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2483 // over the constraints, collecting fixed registers that we know we can't use.
2484 std::set<unsigned> OutputRegs, InputRegs;
2486 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2487 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2488 std::string &ConstraintCode = Constraints[i].Codes[0];
2490 MVT::ValueType OpVT;
2492 // Compute the value type for each operand and add it to ConstraintVTs.
2493 switch (Constraints[i].Type) {
2494 case InlineAsm::isOutput:
2495 if (!Constraints[i].isIndirectOutput) {
2496 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2497 OpVT = TLI.getValueType(I.getType());
2499 const Type *OpTy = I.getOperand(OpNum)->getType();
2500 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2501 OpNum++; // Consumes a call operand.
2504 case InlineAsm::isInput:
2505 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2506 OpNum++; // Consumes a call operand.
2508 case InlineAsm::isClobber:
2513 ConstraintVTs.push_back(OpVT);
2515 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2516 continue; // Not assigned a fixed reg.
2518 // Build a list of regs that this operand uses. This always has a single
2519 // element for promoted/expanded operands.
2520 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2522 OutputRegs, InputRegs);
2524 switch (Constraints[i].Type) {
2525 case InlineAsm::isOutput:
2526 // We can't assign any other output to this register.
2527 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2528 // If this is an early-clobber output, it cannot be assigned to the same
2529 // value as the input reg.
2530 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2531 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2533 case InlineAsm::isInput:
2534 // We can't assign any other input to this register.
2535 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2537 case InlineAsm::isClobber:
2538 // Clobbered regs cannot be used as inputs or outputs.
2539 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2540 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2545 // Loop over all of the inputs, copying the operand values into the
2546 // appropriate registers and processing the output regs.
2547 RegsForValue RetValRegs;
2548 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2551 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2552 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2553 std::string &ConstraintCode = Constraints[i].Codes[0];
2555 switch (Constraints[i].Type) {
2556 case InlineAsm::isOutput: {
2557 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2558 if (ConstraintCode.size() == 1) // not a physreg name.
2559 CTy = TLI.getConstraintType(ConstraintCode[0]);
2561 if (CTy == TargetLowering::C_Memory) {
2563 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2565 // Check that the operand (the address to store to) isn't a float.
2566 if (!MVT::isInteger(InOperandVal.getValueType()))
2567 assert(0 && "MATCH FAIL!");
2569 if (!Constraints[i].isIndirectOutput)
2570 assert(0 && "MATCH FAIL!");
2572 OpNum++; // Consumes a call operand.
2574 // Extend/truncate to the right pointer type if needed.
2575 MVT::ValueType PtrType = TLI.getPointerTy();
2576 if (InOperandVal.getValueType() < PtrType)
2577 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2578 else if (InOperandVal.getValueType() > PtrType)
2579 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2581 // Add information to the INLINEASM node to know about this output.
2582 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2583 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2584 AsmNodeOperands.push_back(InOperandVal);
2588 // Otherwise, this is a register output.
2589 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2591 // If this is an early-clobber output, or if there is an input
2592 // constraint that matches this, we need to reserve the input register
2593 // so no other inputs allocate to it.
2594 bool UsesInputRegister = false;
2595 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2596 UsesInputRegister = true;
2598 // Copy the output from the appropriate register. Find a register that
2601 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2602 true, UsesInputRegister,
2603 OutputRegs, InputRegs);
2604 if (Regs.Regs.empty()) {
2605 cerr << "Couldn't allocate output reg for contraint '"
2606 << ConstraintCode << "'!\n";
2610 if (!Constraints[i].isIndirectOutput) {
2611 assert(RetValRegs.Regs.empty() &&
2612 "Cannot have multiple output constraints yet!");
2613 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2616 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2617 I.getOperand(OpNum)));
2618 OpNum++; // Consumes a call operand.
2621 // Add information to the INLINEASM node to know that this register is
2623 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2626 case InlineAsm::isInput: {
2627 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2628 OpNum++; // Consumes a call operand.
2630 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2631 // If this is required to match an output register we have already set,
2632 // just use its register.
2633 unsigned OperandNo = atoi(ConstraintCode.c_str());
2635 // Scan until we find the definition we already emitted of this operand.
2636 // When we find it, create a RegsForValue operand.
2637 unsigned CurOp = 2; // The first operand.
2638 for (; OperandNo; --OperandNo) {
2639 // Advance to the next operand.
2641 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2642 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2643 (NumOps & 7) == 4 /*MEM*/) &&
2644 "Skipped past definitions?");
2645 CurOp += (NumOps>>3)+1;
2649 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2650 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2651 "Skipped past definitions?");
2653 // Add NumOps>>3 registers to MatchedRegs.
2654 RegsForValue MatchedRegs;
2655 MatchedRegs.ValueVT = InOperandVal.getValueType();
2656 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2657 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2658 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2659 MatchedRegs.Regs.push_back(Reg);
2662 // Use the produced MatchedRegs object to
2663 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2664 TLI.getPointerTy());
2665 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2669 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2670 if (ConstraintCode.size() == 1) // not a physreg name.
2671 CTy = TLI.getConstraintType(ConstraintCode[0]);
2673 if (CTy == TargetLowering::C_Other) {
2674 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2675 ConstraintCode[0], DAG);
2676 if (!InOperandVal.Val) {
2677 cerr << "Invalid operand for inline asm constraint '"
2678 << ConstraintCode << "'!\n";
2682 // Add information to the INLINEASM node to know about this input.
2683 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2684 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2685 AsmNodeOperands.push_back(InOperandVal);
2687 } else if (CTy == TargetLowering::C_Memory) {
2690 // Check that the operand isn't a float.
2691 if (!MVT::isInteger(InOperandVal.getValueType()))
2692 assert(0 && "MATCH FAIL!");
2694 // Extend/truncate to the right pointer type if needed.
2695 MVT::ValueType PtrType = TLI.getPointerTy();
2696 if (InOperandVal.getValueType() < PtrType)
2697 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2698 else if (InOperandVal.getValueType() > PtrType)
2699 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2701 // Add information to the INLINEASM node to know about this input.
2702 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2703 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2704 AsmNodeOperands.push_back(InOperandVal);
2708 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2710 // Copy the input into the appropriate registers.
2711 RegsForValue InRegs =
2712 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2713 false, true, OutputRegs, InputRegs);
2714 // FIXME: should be match fail.
2715 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2717 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2719 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2722 case InlineAsm::isClobber: {
2723 RegsForValue ClobberedRegs =
2724 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2725 OutputRegs, InputRegs);
2726 // Add the clobbered value to the operand list, so that the register
2727 // allocator is aware that the physreg got clobbered.
2728 if (!ClobberedRegs.Regs.empty())
2729 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2735 // Finish up input operands.
2736 AsmNodeOperands[0] = Chain;
2737 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2739 Chain = DAG.getNode(ISD::INLINEASM,
2740 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2741 &AsmNodeOperands[0], AsmNodeOperands.size());
2742 Flag = Chain.getValue(1);
2744 // If this asm returns a register value, copy the result from that register
2745 // and set it as the value of the call.
2746 if (!RetValRegs.Regs.empty())
2747 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2749 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2751 // Process indirect outputs, first output all of the flagged copies out of
2753 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2754 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2755 Value *Ptr = IndirectStoresToEmit[i].second;
2756 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2757 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2760 // Emit the non-flagged stores from the physregs.
2761 SmallVector<SDOperand, 8> OutChains;
2762 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2763 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
2764 getValue(StoresToEmit[i].second),
2765 StoresToEmit[i].second, 0));
2766 if (!OutChains.empty())
2767 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2768 &OutChains[0], OutChains.size());
2773 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2774 SDOperand Src = getValue(I.getOperand(0));
2776 MVT::ValueType IntPtr = TLI.getPointerTy();
2778 if (IntPtr < Src.getValueType())
2779 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2780 else if (IntPtr > Src.getValueType())
2781 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2783 // Scale the source by the type size.
2784 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2785 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2786 Src, getIntPtrConstant(ElementSize));
2788 std::vector<std::pair<SDOperand, const Type*> > Args;
2789 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2791 std::pair<SDOperand,SDOperand> Result =
2792 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2793 DAG.getExternalSymbol("malloc", IntPtr),
2795 setValue(&I, Result.first); // Pointers always fit in registers
2796 DAG.setRoot(Result.second);
2799 void SelectionDAGLowering::visitFree(FreeInst &I) {
2800 std::vector<std::pair<SDOperand, const Type*> > Args;
2801 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2802 TLI.getTargetData()->getIntPtrType()));
2803 MVT::ValueType IntPtr = TLI.getPointerTy();
2804 std::pair<SDOperand,SDOperand> Result =
2805 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2806 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2807 DAG.setRoot(Result.second);
2810 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2811 // mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2812 // instructions are special in various ways, which require special support to
2813 // insert. The specified MachineInstr is created but not inserted into any
2814 // basic blocks, and the scheduler passes ownership of it to this method.
2815 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2816 MachineBasicBlock *MBB) {
2817 cerr << "If a target marks an instruction with "
2818 << "'usesCustomDAGSchedInserter', it must implement "
2819 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
2824 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2825 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2826 getValue(I.getOperand(1)),
2827 DAG.getSrcValue(I.getOperand(1))));
2830 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2831 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2832 getValue(I.getOperand(0)),
2833 DAG.getSrcValue(I.getOperand(0)));
2835 DAG.setRoot(V.getValue(1));
2838 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2839 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2840 getValue(I.getOperand(1)),
2841 DAG.getSrcValue(I.getOperand(1))));
2844 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2845 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2846 getValue(I.getOperand(1)),
2847 getValue(I.getOperand(2)),
2848 DAG.getSrcValue(I.getOperand(1)),
2849 DAG.getSrcValue(I.getOperand(2))));
2852 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2853 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2854 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2855 unsigned &i, SelectionDAG &DAG,
2856 TargetLowering &TLI) {
2857 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2858 return SDOperand(Arg, i++);
2860 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2861 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2863 return DAG.getNode(ISD::BIT_CONVERT, VT,
2864 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2865 } else if (NumVals == 2) {
2866 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2867 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2868 if (!TLI.isLittleEndian())
2870 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2872 // Value scalarized into many values. Unimp for now.
2873 assert(0 && "Cannot expand i64 -> i16 yet!");
2878 /// TargetLowering::LowerArguments - This is the default LowerArguments
2879 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
2880 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2881 /// integrated into SDISel.
2882 std::vector<SDOperand>
2883 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2884 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2885 std::vector<SDOperand> Ops;
2886 Ops.push_back(DAG.getRoot());
2887 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2888 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2890 // Add one result value for each formal argument.
2891 std::vector<MVT::ValueType> RetVals;
2892 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2893 MVT::ValueType VT = getValueType(I->getType());
2895 switch (getTypeAction(VT)) {
2896 default: assert(0 && "Unknown type action!");
2898 RetVals.push_back(VT);
2901 RetVals.push_back(getTypeToTransformTo(VT));
2904 if (VT != MVT::Vector) {
2905 // If this is a large integer, it needs to be broken up into small
2906 // integers. Figure out what the destination type is and how many small
2907 // integers it turns into.
2908 MVT::ValueType NVT = getTypeToExpandTo(VT);
2909 unsigned NumVals = getNumElements(VT);
2910 for (unsigned i = 0; i != NumVals; ++i)
2911 RetVals.push_back(NVT);
2913 // Otherwise, this is a vector type. We only support legal vectors
2915 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2916 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2918 // Figure out if there is a Packed type corresponding to this Vector
2919 // type. If so, convert to the packed type.
2920 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2921 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2922 RetVals.push_back(TVT);
2924 assert(0 && "Don't support illegal by-val vector arguments yet!");
2931 RetVals.push_back(MVT::Other);
2934 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2935 DAG.getNodeValueTypes(RetVals), RetVals.size(),
2936 &Ops[0], Ops.size()).Val;
2938 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2940 // Set up the return result vector.
2943 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2944 MVT::ValueType VT = getValueType(I->getType());
2946 switch (getTypeAction(VT)) {
2947 default: assert(0 && "Unknown type action!");
2949 Ops.push_back(SDOperand(Result, i++));
2952 SDOperand Op(Result, i++);
2953 if (MVT::isInteger(VT)) {
2954 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2956 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2957 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2959 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2960 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2966 if (VT != MVT::Vector) {
2967 // If this is a large integer or a floating point node that needs to be
2968 // expanded, it needs to be reassembled from small integers. Figure out
2969 // what the source elt type is and how many small integers it is.
2970 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
2972 // Otherwise, this is a vector type. We only support legal vectors
2974 const PackedType *PTy = cast<PackedType>(I->getType());
2975 unsigned NumElems = PTy->getNumElements();
2976 const Type *EltTy = PTy->getElementType();
2978 // Figure out if there is a Packed type corresponding to this Vector
2979 // type. If so, convert to the packed type.
2980 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2981 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2982 SDOperand N = SDOperand(Result, i++);
2983 // Handle copies from generic vectors to registers.
2984 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2985 DAG.getConstant(NumElems, MVT::i32),
2986 DAG.getValueType(getValueType(EltTy)));
2989 assert(0 && "Don't support illegal by-val vector arguments yet!");
3000 /// ExpandScalarCallArgs - Recursively expand call argument node by
3001 /// bit_converting it or extract a pair of elements from the larger node.
3002 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3004 SmallVector<SDOperand, 32> &Ops,
3006 TargetLowering &TLI) {
3007 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3009 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
3013 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3014 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3016 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3017 ExpandScalarCallArgs(EVT, Arg, isSigned, Ops, DAG, TLI);
3018 } else if (NumVals == 2) {
3019 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3020 DAG.getConstant(0, TLI.getPointerTy()));
3021 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3022 DAG.getConstant(1, TLI.getPointerTy()));
3023 if (!TLI.isLittleEndian())
3025 ExpandScalarCallArgs(EVT, Lo, isSigned, Ops, DAG, TLI);
3026 ExpandScalarCallArgs(EVT, Hi, isSigned, Ops, DAG, TLI);
3028 // Value scalarized into many values. Unimp for now.
3029 assert(0 && "Cannot expand i64 -> i16 yet!");
3033 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3034 /// implementation, which just inserts an ISD::CALL node, which is later custom
3035 /// lowered by the target to something concrete. FIXME: When all targets are
3036 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3037 std::pair<SDOperand, SDOperand>
3038 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
3039 unsigned CallingConv, bool isTailCall,
3041 ArgListTy &Args, SelectionDAG &DAG) {
3042 SmallVector<SDOperand, 32> Ops;
3043 Ops.push_back(Chain); // Op#0 - Chain
3044 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3045 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3046 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3047 Ops.push_back(Callee);
3049 // Handle all of the outgoing arguments.
3050 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3051 MVT::ValueType VT = getValueType(Args[i].second);
3052 SDOperand Op = Args[i].first;
3053 bool isSigned = Args[i].second->isSigned();
3054 switch (getTypeAction(VT)) {
3055 default: assert(0 && "Unknown type action!");
3058 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
3061 if (MVT::isInteger(VT)) {
3062 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3063 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3065 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3066 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3069 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
3072 if (VT != MVT::Vector) {
3073 // If this is a large integer, it needs to be broken down into small
3074 // integers. Figure out what the source elt type is and how many small
3076 ExpandScalarCallArgs(VT, Op, isSigned, Ops, DAG, *this);
3078 // Otherwise, this is a vector type. We only support legal vectors
3080 const PackedType *PTy = cast<PackedType>(Args[i].second);
3081 unsigned NumElems = PTy->getNumElements();
3082 const Type *EltTy = PTy->getElementType();
3084 // Figure out if there is a Packed type corresponding to this Vector
3085 // type. If so, convert to the packed type.
3086 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3087 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3088 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3089 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3091 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
3093 assert(0 && "Don't support illegal by-val vector call args yet!");
3101 // Figure out the result value types.
3102 SmallVector<MVT::ValueType, 4> RetTys;
3104 if (RetTy != Type::VoidTy) {
3105 MVT::ValueType VT = getValueType(RetTy);
3106 switch (getTypeAction(VT)) {
3107 default: assert(0 && "Unknown type action!");
3109 RetTys.push_back(VT);
3112 RetTys.push_back(getTypeToTransformTo(VT));
3115 if (VT != MVT::Vector) {
3116 // If this is a large integer, it needs to be reassembled from small
3117 // integers. Figure out what the source elt type is and how many small
3119 MVT::ValueType NVT = getTypeToExpandTo(VT);
3120 unsigned NumVals = getNumElements(VT);
3121 for (unsigned i = 0; i != NumVals; ++i)
3122 RetTys.push_back(NVT);
3124 // Otherwise, this is a vector type. We only support legal vectors
3126 const PackedType *PTy = cast<PackedType>(RetTy);
3127 unsigned NumElems = PTy->getNumElements();
3128 const Type *EltTy = PTy->getElementType();
3130 // Figure out if there is a Packed type corresponding to this Vector
3131 // type. If so, convert to the packed type.
3132 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3133 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3134 RetTys.push_back(TVT);
3136 assert(0 && "Don't support illegal by-val vector call results yet!");
3143 RetTys.push_back(MVT::Other); // Always has a chain.
3145 // Finally, create the CALL node.
3146 SDOperand Res = DAG.getNode(ISD::CALL,
3147 DAG.getVTList(&RetTys[0], RetTys.size()),
3148 &Ops[0], Ops.size());
3150 // This returns a pair of operands. The first element is the
3151 // return value for the function (if RetTy is not VoidTy). The second
3152 // element is the outgoing token chain.
3154 if (RetTys.size() != 1) {
3155 MVT::ValueType VT = getValueType(RetTy);
3156 if (RetTys.size() == 2) {
3159 // If this value was promoted, truncate it down.
3160 if (ResVal.getValueType() != VT) {
3161 if (VT == MVT::Vector) {
3162 // Insert a VBITCONVERT to convert from the packed result type to the
3163 // MVT::Vector type.
3164 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3165 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3167 // Figure out if there is a Packed type corresponding to this Vector
3168 // type. If so, convert to the packed type.
3169 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3170 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3171 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3172 // "N x PTyElementVT" MVT::Vector type.
3173 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3174 DAG.getConstant(NumElems, MVT::i32),
3175 DAG.getValueType(getValueType(EltTy)));
3179 } else if (MVT::isInteger(VT)) {
3180 unsigned AssertOp = RetTy->isSigned() ?
3181 ISD::AssertSext : ISD::AssertZext;
3182 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3183 DAG.getValueType(VT));
3184 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3186 assert(MVT::isFloatingPoint(VT));
3187 if (getTypeAction(VT) == Expand)
3188 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3190 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3193 } else if (RetTys.size() == 3) {
3194 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3195 Res.getValue(0), Res.getValue(1));
3198 assert(0 && "Case not handled yet!");
3202 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3207 // It is always conservatively correct for llvm.returnaddress and
3208 // llvm.frameaddress to return 0.
3210 // FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3211 // expanded to 0 if the target wants.
3212 std::pair<SDOperand, SDOperand>
3213 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3214 unsigned Depth, SelectionDAG &DAG) {
3215 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
3218 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3219 assert(0 && "LowerOperation not implemented for this target!");
3224 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3225 SelectionDAG &DAG) {
3226 assert(0 && "CustomPromoteOperation not implemented for this target!");
3231 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
3232 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
3233 std::pair<SDOperand,SDOperand> Result =
3234 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
3235 setValue(&I, Result.first);
3236 DAG.setRoot(Result.second);
3239 /// getMemsetValue - Vectorized representation of the memset value
3241 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3242 SelectionDAG &DAG) {
3243 MVT::ValueType CurVT = VT;
3244 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3245 uint64_t Val = C->getValue() & 255;
3247 while (CurVT != MVT::i8) {
3248 Val = (Val << Shift) | Val;
3250 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3252 return DAG.getConstant(Val, VT);
3254 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3256 while (CurVT != MVT::i8) {
3258 DAG.getNode(ISD::OR, VT,
3259 DAG.getNode(ISD::SHL, VT, Value,
3260 DAG.getConstant(Shift, MVT::i8)), Value);
3262 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3269 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3270 /// used when a memcpy is turned into a memset when the source is a constant
3272 static SDOperand getMemsetStringVal(MVT::ValueType VT,
3273 SelectionDAG &DAG, TargetLowering &TLI,
3274 std::string &Str, unsigned Offset) {
3276 unsigned MSB = getSizeInBits(VT) / 8;
3277 if (TLI.isLittleEndian())
3278 Offset = Offset + MSB - 1;
3279 for (unsigned i = 0; i != MSB; ++i) {
3280 Val = (Val << 8) | (unsigned char)Str[Offset];
3281 Offset += TLI.isLittleEndian() ? -1 : 1;
3283 return DAG.getConstant(Val, VT);
3286 /// getMemBasePlusOffset - Returns base and offset node for the
3287 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3288 SelectionDAG &DAG, TargetLowering &TLI) {
3289 MVT::ValueType VT = Base.getValueType();
3290 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3293 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3294 /// to replace the memset / memcpy is below the threshold. It also returns the
3295 /// types of the sequence of memory ops to perform memset / memcpy.
3296 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3297 unsigned Limit, uint64_t Size,
3298 unsigned Align, TargetLowering &TLI) {
3301 if (TLI.allowsUnalignedMemoryAccesses()) {
3304 switch (Align & 7) {
3320 MVT::ValueType LVT = MVT::i64;
3321 while (!TLI.isTypeLegal(LVT))
3322 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3323 assert(MVT::isInteger(LVT));
3328 unsigned NumMemOps = 0;
3330 unsigned VTSize = getSizeInBits(VT) / 8;
3331 while (VTSize > Size) {
3332 VT = (MVT::ValueType)((unsigned)VT - 1);
3335 assert(MVT::isInteger(VT));
3337 if (++NumMemOps > Limit)
3339 MemOps.push_back(VT);
3346 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3347 SDOperand Op1 = getValue(I.getOperand(1));
3348 SDOperand Op2 = getValue(I.getOperand(2));
3349 SDOperand Op3 = getValue(I.getOperand(3));
3350 SDOperand Op4 = getValue(I.getOperand(4));
3351 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3352 if (Align == 0) Align = 1;
3354 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3355 std::vector<MVT::ValueType> MemOps;
3357 // Expand memset / memcpy to a series of load / store ops
3358 // if the size operand falls below a certain threshold.
3359 SmallVector<SDOperand, 8> OutChains;
3361 default: break; // Do nothing for now.
3363 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3364 Size->getValue(), Align, TLI)) {
3365 unsigned NumMemOps = MemOps.size();
3366 unsigned Offset = 0;
3367 for (unsigned i = 0; i < NumMemOps; i++) {
3368 MVT::ValueType VT = MemOps[i];
3369 unsigned VTSize = getSizeInBits(VT) / 8;
3370 SDOperand Value = getMemsetValue(Op2, VT, DAG);
3371 SDOperand Store = DAG.getStore(getRoot(), Value,
3372 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3373 I.getOperand(1), Offset);
3374 OutChains.push_back(Store);
3381 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3382 Size->getValue(), Align, TLI)) {
3383 unsigned NumMemOps = MemOps.size();
3384 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3385 GlobalAddressSDNode *G = NULL;
3387 bool CopyFromStr = false;
3389 if (Op2.getOpcode() == ISD::GlobalAddress)
3390 G = cast<GlobalAddressSDNode>(Op2);
3391 else if (Op2.getOpcode() == ISD::ADD &&
3392 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3393 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3394 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3395 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3398 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3399 if (GV && GV->isConstant()) {
3400 Str = GV->getStringValue(false);
3408 for (unsigned i = 0; i < NumMemOps; i++) {
3409 MVT::ValueType VT = MemOps[i];
3410 unsigned VTSize = getSizeInBits(VT) / 8;
3411 SDOperand Value, Chain, Store;
3414 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3417 DAG.getStore(Chain, Value,
3418 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3419 I.getOperand(1), DstOff);
3421 Value = DAG.getLoad(VT, getRoot(),
3422 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3423 I.getOperand(2), SrcOff);
3424 Chain = Value.getValue(1);
3426 DAG.getStore(Chain, Value,
3427 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3428 I.getOperand(1), DstOff);
3430 OutChains.push_back(Store);
3439 if (!OutChains.empty()) {
3440 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3441 &OutChains[0], OutChains.size()));
3446 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3449 //===----------------------------------------------------------------------===//
3450 // SelectionDAGISel code
3451 //===----------------------------------------------------------------------===//
3453 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3454 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3457 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3458 // FIXME: we only modify the CFG to split critical edges. This
3459 // updates dom and loop info.
3460 AU.addRequired<AliasAnalysis>();
3464 /// OptimizeNoopCopyExpression - We have determined that the specified cast
3465 /// instruction is a noop copy (e.g. it's casting from one pointer type to
3466 /// another, int->uint, or int->sbyte on PPC.
3468 /// Return true if any changes are made.
3469 static bool OptimizeNoopCopyExpression(CastInst *CI) {
3470 BasicBlock *DefBB = CI->getParent();
3472 /// InsertedCasts - Only insert a cast in each block once.
3473 std::map<BasicBlock*, CastInst*> InsertedCasts;
3475 bool MadeChange = false;
3476 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3478 Use &TheUse = UI.getUse();
3479 Instruction *User = cast<Instruction>(*UI);
3481 // Figure out which BB this cast is used in. For PHI's this is the
3482 // appropriate predecessor block.
3483 BasicBlock *UserBB = User->getParent();
3484 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3485 unsigned OpVal = UI.getOperandNo()/2;
3486 UserBB = PN->getIncomingBlock(OpVal);
3489 // Preincrement use iterator so we don't invalidate it.
3492 // If this user is in the same block as the cast, don't change the cast.
3493 if (UserBB == DefBB) continue;
3495 // If we have already inserted a cast into this block, use it.
3496 CastInst *&InsertedCast = InsertedCasts[UserBB];
3498 if (!InsertedCast) {
3499 BasicBlock::iterator InsertPt = UserBB->begin();
3500 while (isa<PHINode>(InsertPt)) ++InsertPt;
3503 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3508 // Replace a use of the cast with a use of the new casat.
3509 TheUse = InsertedCast;
3512 // If we removed all uses, nuke the cast.
3513 if (CI->use_empty())
3514 CI->eraseFromParent();
3519 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3520 /// casting to the type of GEPI.
3521 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3522 Instruction *GEPI, Value *Ptr,
3524 if (V) return V; // Already computed.
3526 // Figure out the insertion point
3527 BasicBlock::iterator InsertPt;
3528 if (BB == GEPI->getParent()) {
3529 // If GEP is already inserted into BB, insert right after the GEP.
3533 // Otherwise, insert at the top of BB, after any PHI nodes
3534 InsertPt = BB->begin();
3535 while (isa<PHINode>(InsertPt)) ++InsertPt;
3538 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3539 // BB so that there is only one value live across basic blocks (the cast
3541 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3542 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3543 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3546 // Add the offset, cast it to the right type.
3547 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3548 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3549 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3553 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3554 /// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3555 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3556 /// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3557 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3558 /// the constant add into a load or store instruction. Additionally, if a user
3559 /// is a pointer-pointer cast, we look through it to find its users.
3560 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3561 Constant *PtrOffset, BasicBlock *DefBB,
3562 GetElementPtrInst *GEPI,
3563 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3564 while (!RepPtr->use_empty()) {
3565 Instruction *User = cast<Instruction>(RepPtr->use_back());
3567 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3568 // used for a Pointer-Pointer cast.
3569 if (isa<BitCastInst>(User)) {
3570 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3572 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3573 // could invalidate an iterator.
3574 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3578 // If this is a load of the pointer, or a store through the pointer, emit
3579 // the increment into the load/store block.
3580 Instruction *NewVal;
3581 if (isa<LoadInst>(User) ||
3582 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3583 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3584 User->getParent(), GEPI,
3587 // If this use is not foldable into the addressing mode, use a version
3588 // emitted in the GEP block.
3589 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3593 if (GEPI->getType() != RepPtr->getType()) {
3594 BasicBlock::iterator IP = NewVal;
3596 // NewVal must be a GEP which must be pointer type, so BitCast
3597 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
3599 User->replaceUsesOfWith(RepPtr, NewVal);
3604 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3605 /// selection, we want to be a bit careful about some things. In particular, if
3606 /// we have a GEP instruction that is used in a different block than it is
3607 /// defined, the addressing expression of the GEP cannot be folded into loads or
3608 /// stores that use it. In this case, decompose the GEP and move constant
3609 /// indices into blocks that use it.
3610 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3611 const TargetData *TD) {
3612 // If this GEP is only used inside the block it is defined in, there is no
3613 // need to rewrite it.
3614 bool isUsedOutsideDefBB = false;
3615 BasicBlock *DefBB = GEPI->getParent();
3616 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3618 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3619 isUsedOutsideDefBB = true;
3623 if (!isUsedOutsideDefBB) return false;
3625 // If this GEP has no non-zero constant indices, there is nothing we can do,
3627 bool hasConstantIndex = false;
3628 bool hasVariableIndex = false;
3629 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3630 E = GEPI->op_end(); OI != E; ++OI) {
3631 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3632 if (CI->getZExtValue()) {
3633 hasConstantIndex = true;
3637 hasVariableIndex = true;
3641 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3642 if (!hasConstantIndex && !hasVariableIndex) {
3643 /// The GEP operand must be a pointer, so must its result -> BitCast
3644 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3645 GEPI->getName(), GEPI);
3646 GEPI->replaceAllUsesWith(NC);
3647 GEPI->eraseFromParent();
3651 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3652 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3655 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3656 // constant offset (which we now know is non-zero) and deal with it later.
3657 uint64_t ConstantOffset = 0;
3658 const Type *UIntPtrTy = TD->getIntPtrType();
3659 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3660 const Type *Ty = GEPI->getOperand(0)->getType();
3662 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3663 E = GEPI->op_end(); OI != E; ++OI) {
3665 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3666 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3668 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3669 Ty = StTy->getElementType(Field);
3671 Ty = cast<SequentialType>(Ty)->getElementType();
3673 // Handle constant subscripts.
3674 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3675 if (CI->getZExtValue() == 0) continue;
3676 if (CI->getType()->isSigned())
3677 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3679 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
3683 // Ptr = Ptr + Idx * ElementSize;
3685 // Cast Idx to UIntPtrTy if needed.
3686 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
3688 uint64_t ElementSize = TD->getTypeSize(Ty);
3689 // Mask off bits that should not be set.
3690 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3691 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3693 // Multiply by the element size and add to the base.
3694 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3695 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3699 // Make sure that the offset fits in uintptr_t.
3700 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3701 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3703 // Okay, we have now emitted all of the variable index parts to the BB that
3704 // the GEP is defined in. Loop over all of the using instructions, inserting
3705 // an "add Ptr, ConstantOffset" into each block that uses it and update the
3706 // instruction to use the newly computed value, making GEPI dead. When the
3707 // user is a load or store instruction address, we emit the add into the user
3708 // block, otherwise we use a canonical version right next to the gep (these
3709 // won't be foldable as addresses, so we might as well share the computation).
3711 std::map<BasicBlock*,Instruction*> InsertedExprs;
3712 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3714 // Finally, the GEP is dead, remove it.
3715 GEPI->eraseFromParent();
3721 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
3722 /// successor if it will improve codegen. We only do this if the successor has
3723 /// phi nodes (otherwise critical edges are ok). If there is already another
3724 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
3725 /// instead of introducing a new block.
3726 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3727 BasicBlock *TIBB = TI->getParent();
3728 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3729 assert(isa<PHINode>(Dest->begin()) &&
3730 "This should only be called if Dest has a PHI!");
3732 /// TIPHIValues - This array is lazily computed to determine the values of
3733 /// PHIs in Dest that TI would provide.
3734 std::vector<Value*> TIPHIValues;
3736 // Check to see if Dest has any blocks that can be used as a split edge for
3738 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3739 BasicBlock *Pred = *PI;
3740 // To be usable, the pred has to end with an uncond branch to the dest.
3741 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3742 if (!PredBr || !PredBr->isUnconditional() ||
3743 // Must be empty other than the branch.
3744 &Pred->front() != PredBr)
3747 // Finally, since we know that Dest has phi nodes in it, we have to make
3748 // sure that jumping to Pred will have the same affect as going to Dest in
3749 // terms of PHI values.
3752 bool FoundMatch = true;
3753 for (BasicBlock::iterator I = Dest->begin();
3754 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3755 if (PHINo == TIPHIValues.size())
3756 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3758 // If the PHI entry doesn't work, we can't use this pred.
3759 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3765 // If we found a workable predecessor, change TI to branch to Succ.
3767 Dest->removePredecessor(TIBB);
3768 TI->setSuccessor(SuccNum, Pred);
3773 SplitCriticalEdge(TI, SuccNum, P, true);
3777 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3778 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3779 RegMap = MF.getSSARegMap();
3780 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
3782 // First, split all critical edges.
3784 // In this pass we also look for GEP and cast instructions that are used
3785 // across basic blocks and rewrite them to improve basic-block-at-a-time
3788 bool MadeChange = true;
3789 while (MadeChange) {
3791 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3792 // Split all critical edges where the dest block has a PHI.
3793 TerminatorInst *BBTI = BB->getTerminator();
3794 if (BBTI->getNumSuccessors() > 1) {
3795 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3796 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3797 isCriticalEdge(BBTI, i, true))
3798 SplitEdgeNicely(BBTI, i, this);
3802 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3803 Instruction *I = BBI++;
3805 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3806 // If we found an inline asm expession, and if the target knows how to
3807 // lower it to normal LLVM code, do so now.
3808 if (isa<InlineAsm>(CI->getCalledValue()))
3809 if (const TargetAsmInfo *TAI =
3810 TLI.getTargetMachine().getTargetAsmInfo()) {
3811 if (TAI->ExpandInlineAsm(CI))
3814 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3815 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3816 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3817 // If the source of the cast is a constant, then this should have
3818 // already been constant folded. The only reason NOT to constant fold
3819 // it is if something (e.g. LSR) was careful to place the constant
3820 // evaluation in a block other than then one that uses it (e.g. to hoist
3821 // the address of globals out of a loop). If this is the case, we don't
3822 // want to forward-subst the cast.
3823 if (isa<Constant>(CI->getOperand(0)))
3826 // If this is a noop copy, sink it into user blocks to reduce the number
3827 // of virtual registers that must be created and coallesced.
3828 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3829 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3831 // This is an fp<->int conversion?
3832 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3835 // If this is an extension, it will be a zero or sign extension, which
3837 if (SrcVT < DstVT) continue;
3839 // If these values will be promoted, find out what they will be promoted
3840 // to. This helps us consider truncates on PPC as noop copies when they
3842 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3843 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3844 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3845 DstVT = TLI.getTypeToTransformTo(DstVT);
3847 // If, after promotion, these are the same types, this is a noop copy.
3849 MadeChange |= OptimizeNoopCopyExpression(CI);
3855 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3857 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3858 SelectBasicBlock(I, MF, FuncInfo);
3863 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3865 SDOperand Op = getValue(V);
3866 assert((Op.getOpcode() != ISD::CopyFromReg ||
3867 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3868 "Copy from a reg to the same reg!");
3870 // If this type is not legal, we must make sure to not create an invalid
3872 MVT::ValueType SrcVT = Op.getValueType();
3873 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3874 if (SrcVT == DestVT) {
3875 return DAG.getCopyToReg(getRoot(), Reg, Op);
3876 } else if (SrcVT == MVT::Vector) {
3877 // Handle copies from generic vectors to registers.
3878 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3879 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3880 PTyElementVT, PTyLegalElementVT);
3882 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3883 // MVT::Vector type.
3884 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3885 DAG.getConstant(NE, MVT::i32),
3886 DAG.getValueType(PTyElementVT));
3888 // Loop over all of the elements of the resultant vector,
3889 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3890 // copying them into output registers.
3891 SmallVector<SDOperand, 8> OutChains;
3892 SDOperand Root = getRoot();
3893 for (unsigned i = 0; i != NE; ++i) {
3894 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3895 Op, DAG.getConstant(i, TLI.getPointerTy()));
3896 if (PTyElementVT == PTyLegalElementVT) {
3897 // Elements are legal.
3898 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3899 } else if (PTyLegalElementVT > PTyElementVT) {
3900 // Elements are promoted.
3901 if (MVT::isFloatingPoint(PTyLegalElementVT))
3902 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3904 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3905 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3907 // Elements are expanded.
3908 // The src value is expanded into multiple registers.
3909 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3910 Elt, DAG.getConstant(0, TLI.getPointerTy()));
3911 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3912 Elt, DAG.getConstant(1, TLI.getPointerTy()));
3913 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3914 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3917 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3918 &OutChains[0], OutChains.size());
3919 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
3920 // The src value is promoted to the register.
3921 if (MVT::isFloatingPoint(SrcVT))
3922 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3924 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3925 return DAG.getCopyToReg(getRoot(), Reg, Op);
3927 DestVT = TLI.getTypeToExpandTo(SrcVT);
3928 unsigned NumVals = TLI.getNumElements(SrcVT);
3930 return DAG.getCopyToReg(getRoot(), Reg,
3931 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3932 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
3933 // The src value is expanded into multiple registers.
3934 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3935 Op, DAG.getConstant(0, TLI.getPointerTy()));
3936 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3937 Op, DAG.getConstant(1, TLI.getPointerTy()));
3938 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
3939 return DAG.getCopyToReg(Op, Reg+1, Hi);
3943 void SelectionDAGISel::
3944 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3945 std::vector<SDOperand> &UnorderedChains) {
3946 // If this is the entry block, emit arguments.
3947 Function &F = *BB->getParent();
3948 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3949 SDOperand OldRoot = SDL.DAG.getRoot();
3950 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3953 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3955 if (!AI->use_empty()) {
3956 SDL.setValue(AI, Args[a]);
3958 // If this argument is live outside of the entry block, insert a copy from
3959 // whereever we got it to the vreg that other BB's will reference it as.
3960 if (FuncInfo.ValueMap.count(AI)) {
3962 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
3963 UnorderedChains.push_back(Copy);
3967 // Finally, if the target has anything special to do, allow it to do so.
3968 // FIXME: this should insert code into the DAG!
3969 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3972 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3973 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3974 FunctionLoweringInfo &FuncInfo) {
3975 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3977 std::vector<SDOperand> UnorderedChains;
3979 // Lower any arguments needed in this block if this is the entry block.
3980 if (LLVMBB == &LLVMBB->getParent()->front())
3981 LowerArguments(LLVMBB, SDL, UnorderedChains);
3983 BB = FuncInfo.MBBMap[LLVMBB];
3984 SDL.setCurrentBasicBlock(BB);
3986 // Lower all of the non-terminator instructions.
3987 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3991 // Ensure that all instructions which are used outside of their defining
3992 // blocks are available as virtual registers.
3993 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3994 if (!I->use_empty() && !isa<PHINode>(I)) {
3995 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3996 if (VMI != FuncInfo.ValueMap.end())
3997 UnorderedChains.push_back(
3998 SDL.CopyValueToVirtualRegister(I, VMI->second));
4001 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4002 // ensure constants are generated when needed. Remember the virtual registers
4003 // that need to be added to the Machine PHI nodes as input. We cannot just
4004 // directly add them, because expansion might result in multiple MBB's for one
4005 // BB. As such, the start of the BB might correspond to a different MBB than
4008 TerminatorInst *TI = LLVMBB->getTerminator();
4010 // Emit constants only once even if used by multiple PHI nodes.
4011 std::map<Constant*, unsigned> ConstantsOut;
4013 // Vector bool would be better, but vector<bool> is really slow.
4014 std::vector<unsigned char> SuccsHandled;
4015 if (TI->getNumSuccessors())
4016 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4018 // Check successor nodes PHI nodes that expect a constant to be available from
4020 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4021 BasicBlock *SuccBB = TI->getSuccessor(succ);
4022 if (!isa<PHINode>(SuccBB->begin())) continue;
4023 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4025 // If this terminator has multiple identical successors (common for
4026 // switches), only handle each succ once.
4027 unsigned SuccMBBNo = SuccMBB->getNumber();
4028 if (SuccsHandled[SuccMBBNo]) continue;
4029 SuccsHandled[SuccMBBNo] = true;
4031 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4034 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4035 // nodes and Machine PHI nodes, but the incoming operands have not been
4037 for (BasicBlock::iterator I = SuccBB->begin();
4038 (PN = dyn_cast<PHINode>(I)); ++I) {
4039 // Ignore dead phi's.
4040 if (PN->use_empty()) continue;
4043 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4045 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4046 unsigned &RegOut = ConstantsOut[C];
4048 RegOut = FuncInfo.CreateRegForValue(C);
4049 UnorderedChains.push_back(
4050 SDL.CopyValueToVirtualRegister(C, RegOut));
4054 Reg = FuncInfo.ValueMap[PHIOp];
4056 assert(isa<AllocaInst>(PHIOp) &&
4057 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4058 "Didn't codegen value into a register!??");
4059 Reg = FuncInfo.CreateRegForValue(PHIOp);
4060 UnorderedChains.push_back(
4061 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4065 // Remember that this register needs to added to the machine PHI node as
4066 // the input for this MBB.
4067 MVT::ValueType VT = TLI.getValueType(PN->getType());
4068 unsigned NumElements;
4069 if (VT != MVT::Vector)
4070 NumElements = TLI.getNumElements(VT);
4072 MVT::ValueType VT1,VT2;
4074 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4077 for (unsigned i = 0, e = NumElements; i != e; ++i)
4078 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4081 ConstantsOut.clear();
4083 // Turn all of the unordered chains into one factored node.
4084 if (!UnorderedChains.empty()) {
4085 SDOperand Root = SDL.getRoot();
4086 if (Root.getOpcode() != ISD::EntryToken) {
4087 unsigned i = 0, e = UnorderedChains.size();
4088 for (; i != e; ++i) {
4089 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4090 if (UnorderedChains[i].Val->getOperand(0) == Root)
4091 break; // Don't add the root if we already indirectly depend on it.
4095 UnorderedChains.push_back(Root);
4097 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4098 &UnorderedChains[0], UnorderedChains.size()));
4101 // Lower the terminator after the copies are emitted.
4102 SDL.visit(*LLVMBB->getTerminator());
4104 // Copy over any CaseBlock records that may now exist due to SwitchInst
4105 // lowering, as well as any jump table information.
4106 SwitchCases.clear();
4107 SwitchCases = SDL.SwitchCases;
4110 // Make sure the root of the DAG is up-to-date.
4111 DAG.setRoot(SDL.getRoot());
4114 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4115 // Get alias analysis for load/store combining.
4116 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4118 // Run the DAG combiner in pre-legalize mode.
4119 DAG.Combine(false, AA);
4121 DOUT << "Lowered selection DAG:\n";
4124 // Second step, hack on the DAG until it only uses operations and types that
4125 // the target supports.
4128 DOUT << "Legalized selection DAG:\n";
4131 // Run the DAG combiner in post-legalize mode.
4132 DAG.Combine(true, AA);
4134 if (ViewISelDAGs) DAG.viewGraph();
4136 // Third, instruction select all of the operations to machine code, adding the
4137 // code to the MachineBasicBlock.
4138 InstructionSelectBasicBlock(DAG);
4140 DOUT << "Selected machine code:\n";
4144 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4145 FunctionLoweringInfo &FuncInfo) {
4146 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4148 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4151 // First step, lower LLVM code to some DAG. This DAG may use operations and
4152 // types that are not supported by the target.
4153 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4155 // Second step, emit the lowered DAG as machine code.
4156 CodeGenAndEmitDAG(DAG);
4159 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4160 // PHI nodes in successors.
4161 if (SwitchCases.empty() && JT.Reg == 0) {
4162 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4163 MachineInstr *PHI = PHINodesToUpdate[i].first;
4164 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4165 "This is not a machine PHI node that we are updating!");
4166 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4167 PHI->addMachineBasicBlockOperand(BB);
4172 // If the JumpTable record is filled in, then we need to emit a jump table.
4173 // Updating the PHI nodes is tricky in this case, since we need to determine
4174 // whether the PHI is a successor of the range check MBB or the jump table MBB
4176 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4177 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4179 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4180 MachineBasicBlock *RangeBB = BB;
4181 // Set the current basic block to the mbb we wish to insert the code into
4183 SDL.setCurrentBasicBlock(BB);
4185 SDL.visitJumpTable(JT);
4186 SDAG.setRoot(SDL.getRoot());
4187 CodeGenAndEmitDAG(SDAG);
4189 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4190 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4191 MachineBasicBlock *PHIBB = PHI->getParent();
4192 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4193 "This is not a machine PHI node that we are updating!");
4194 if (PHIBB == JT.Default) {
4195 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4196 PHI->addMachineBasicBlockOperand(RangeBB);
4198 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4199 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4200 PHI->addMachineBasicBlockOperand(BB);
4206 // If the switch block involved a branch to one of the actual successors, we
4207 // need to update PHI nodes in that block.
4208 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4209 MachineInstr *PHI = PHINodesToUpdate[i].first;
4210 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4211 "This is not a machine PHI node that we are updating!");
4212 if (BB->isSuccessor(PHI->getParent())) {
4213 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4214 PHI->addMachineBasicBlockOperand(BB);
4218 // If we generated any switch lowering information, build and codegen any
4219 // additional DAGs necessary.
4220 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4221 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4223 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4225 // Set the current basic block to the mbb we wish to insert the code into
4226 BB = SwitchCases[i].ThisBB;
4227 SDL.setCurrentBasicBlock(BB);
4230 SDL.visitSwitchCase(SwitchCases[i]);
4231 SDAG.setRoot(SDL.getRoot());
4232 CodeGenAndEmitDAG(SDAG);
4234 // Handle any PHI nodes in successors of this chunk, as if we were coming
4235 // from the original BB before switch expansion. Note that PHI nodes can
4236 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4237 // handle them the right number of times.
4238 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4239 for (MachineBasicBlock::iterator Phi = BB->begin();
4240 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4241 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4242 for (unsigned pn = 0; ; ++pn) {
4243 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4244 if (PHINodesToUpdate[pn].first == Phi) {
4245 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4246 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4252 // Don't process RHS if same block as LHS.
4253 if (BB == SwitchCases[i].FalseBB)
4254 SwitchCases[i].FalseBB = 0;
4256 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4257 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4258 SwitchCases[i].FalseBB = 0;
4260 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4265 //===----------------------------------------------------------------------===//
4266 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4267 /// target node in the graph.
4268 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4269 if (ViewSchedDAGs) DAG.viewGraph();
4271 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4275 RegisterScheduler::setDefault(Ctor);
4278 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4284 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4285 return new HazardRecognizer();
4288 //===----------------------------------------------------------------------===//
4289 // Helper functions used by the generated instruction selector.
4290 //===----------------------------------------------------------------------===//
4291 // Calls to these methods are generated by tblgen.
4293 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
4294 /// the dag combiner simplified the 255, we still want to match. RHS is the
4295 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4296 /// specified in the .td file (e.g. 255).
4297 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4298 int64_t DesiredMaskS) {
4299 uint64_t ActualMask = RHS->getValue();
4300 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4302 // If the actual mask exactly matches, success!
4303 if (ActualMask == DesiredMask)
4306 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4307 if (ActualMask & ~DesiredMask)
4310 // Otherwise, the DAG Combiner may have proven that the value coming in is
4311 // either already zero or is not demanded. Check for known zero input bits.
4312 uint64_t NeededMask = DesiredMask & ~ActualMask;
4313 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4316 // TODO: check to see if missing bits are just not demanded.
4318 // Otherwise, this pattern doesn't match.
4322 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
4323 /// the dag combiner simplified the 255, we still want to match. RHS is the
4324 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4325 /// specified in the .td file (e.g. 255).
4326 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4327 int64_t DesiredMaskS) {
4328 uint64_t ActualMask = RHS->getValue();
4329 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4331 // If the actual mask exactly matches, success!
4332 if (ActualMask == DesiredMask)
4335 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4336 if (ActualMask & ~DesiredMask)
4339 // Otherwise, the DAG Combiner may have proven that the value coming in is
4340 // either already zero or is not demanded. Check for known zero input bits.
4341 uint64_t NeededMask = DesiredMask & ~ActualMask;
4343 uint64_t KnownZero, KnownOne;
4344 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4346 // If all the missing bits in the or are already known to be set, match!
4347 if ((NeededMask & KnownOne) == NeededMask)
4350 // TODO: check to see if missing bits are just not demanded.
4352 // Otherwise, this pattern doesn't match.
4357 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4358 /// by tblgen. Others should not call it.
4359 void SelectionDAGISel::
4360 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4361 std::vector<SDOperand> InOps;
4362 std::swap(InOps, Ops);
4364 Ops.push_back(InOps[0]); // input chain.
4365 Ops.push_back(InOps[1]); // input asm string.
4367 unsigned i = 2, e = InOps.size();
4368 if (InOps[e-1].getValueType() == MVT::Flag)
4369 --e; // Don't process a flag operand if it is here.
4372 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4373 if ((Flags & 7) != 4 /*MEM*/) {
4374 // Just skip over this operand, copying the operands verbatim.
4375 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4376 i += (Flags >> 3) + 1;
4378 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4379 // Otherwise, this is a memory operand. Ask the target to select it.
4380 std::vector<SDOperand> SelOps;
4381 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4382 cerr << "Could not match memory address. Inline asm failure!\n";
4386 // Add this to the output node.
4387 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4389 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4394 // Add the flag input back if present.
4395 if (e != InOps.size())
4396 Ops.push_back(InOps.back());