1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/CodeGen/Collector.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SchedulerRegistry.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Compiler.h"
53 ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
56 ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
59 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
60 cl::desc("Pop up a window to show SUnit dags after they are processed"));
62 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
65 //===---------------------------------------------------------------------===//
67 /// RegisterScheduler class - Track the registration of instruction schedulers.
69 //===---------------------------------------------------------------------===//
70 MachinePassRegistry RegisterScheduler::Registry;
72 //===---------------------------------------------------------------------===//
74 /// ISHeuristic command line option for instruction schedulers.
76 //===---------------------------------------------------------------------===//
77 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79 ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
84 static RegisterScheduler
85 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
88 namespace { struct SDISelAsmOperandInfo; }
90 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
91 /// insertvalue or extractvalue indices that identify a member, return
92 /// the linearized index of the start of the member.
94 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
95 const unsigned *Indices,
96 const unsigned *IndicesEnd,
97 unsigned CurIndex = 0) {
98 // Base case: We're done.
99 if (Indices == IndicesEnd)
102 // Otherwise we need to recurse. A non-negative value is used to
103 // indicate the final result value; a negative value carries the
104 // complemented position to continue the search.
105 CurIndex = ~CurIndex;
107 // Given a struct type, recursively traverse the elements.
108 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
109 for (StructType::element_iterator EI = STy->element_begin(),
110 EE = STy->element_end();
112 CurIndex = ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd,
114 if ((int)CurIndex >= 0)
118 // Given an array type, recursively traverse the elements.
119 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
120 const Type *EltTy = ATy->getElementType();
121 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
122 CurIndex = ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd,
124 if ((int)CurIndex >= 0)
128 // We haven't found the type we're looking for, so keep searching.
132 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
133 /// MVTs that represent all the individual underlying
134 /// non-aggregate types that comprise it.
136 /// If Offsets is non-null, it points to a vector to be filled in
137 /// with the in-memory offsets of each of the individual values.
139 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
140 SmallVectorImpl<MVT> &ValueVTs,
141 SmallVectorImpl<uint64_t> *Offsets = 0,
142 uint64_t StartingOffset = 0) {
143 // Given a struct type, recursively traverse the elements.
144 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
145 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
146 for (StructType::element_iterator EB = STy->element_begin(),
148 EE = STy->element_end();
150 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
151 StartingOffset + SL->getElementOffset(EI - EB));
154 // Given an array type, recursively traverse the elements.
155 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
156 const Type *EltTy = ATy->getElementType();
157 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
158 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
159 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
160 StartingOffset + i * EltSize);
163 // Base case: we can get an MVT for this LLVM IR type.
164 ValueVTs.push_back(TLI.getValueType(Ty));
166 Offsets->push_back(StartingOffset);
170 /// RegsForValue - This struct represents the registers (physical or virtual)
171 /// that a particular set of values is assigned, and the type information about
172 /// the value. The most common situation is to represent one value at a time,
173 /// but struct or array values are handled element-wise as multiple values.
174 /// The splitting of aggregates is performed recursively, so that we never
175 /// have aggregate-typed registers. The values at this point do not necessarily
176 /// have legal types, so each value may require one or more registers of some
179 struct VISIBILITY_HIDDEN RegsForValue {
180 /// TLI - The TargetLowering object.
182 const TargetLowering *TLI;
184 /// ValueVTs - The value types of the values, which may not be legal, and
185 /// may need be promoted or synthesized from one or more registers.
187 SmallVector<MVT, 4> ValueVTs;
189 /// RegVTs - The value types of the registers. This is the same size as
190 /// ValueVTs and it records, for each value, what the type of the assigned
191 /// register or registers are. (Individual values are never synthesized
192 /// from more than one type of register.)
194 /// With virtual registers, the contents of RegVTs is redundant with TLI's
195 /// getRegisterType member function, however when with physical registers
196 /// it is necessary to have a separate record of the types.
198 SmallVector<MVT, 4> RegVTs;
200 /// Regs - This list holds the registers assigned to the values.
201 /// Each legal or promoted value requires one register, and each
202 /// expanded value requires multiple registers.
204 SmallVector<unsigned, 4> Regs;
206 RegsForValue() : TLI(0) {}
208 RegsForValue(const TargetLowering &tli,
209 const SmallVector<unsigned, 4> ®s,
210 MVT regvt, MVT valuevt)
211 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
212 RegsForValue(const TargetLowering &tli,
213 const SmallVector<unsigned, 4> ®s,
214 const SmallVector<MVT, 4> ®vts,
215 const SmallVector<MVT, 4> &valuevts)
216 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
217 RegsForValue(const TargetLowering &tli,
218 unsigned Reg, const Type *Ty) : TLI(&tli) {
219 ComputeValueVTs(tli, Ty, ValueVTs);
221 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
222 MVT ValueVT = ValueVTs[Value];
223 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
224 MVT RegisterVT = TLI->getRegisterType(ValueVT);
225 for (unsigned i = 0; i != NumRegs; ++i)
226 Regs.push_back(Reg + i);
227 RegVTs.push_back(RegisterVT);
232 /// append - Add the specified values to this one.
233 void append(const RegsForValue &RHS) {
235 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
236 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
237 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
241 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
242 /// this value and returns the result as a ValueVTs value. This uses
243 /// Chain/Flag as the input and updates them for the output Chain/Flag.
244 /// If the Flag pointer is NULL, no flag is used.
245 SDOperand getCopyFromRegs(SelectionDAG &DAG,
246 SDOperand &Chain, SDOperand *Flag) const;
248 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
249 /// specified value into the registers specified by this object. This uses
250 /// Chain/Flag as the input and updates them for the output Chain/Flag.
251 /// If the Flag pointer is NULL, no flag is used.
252 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
253 SDOperand &Chain, SDOperand *Flag) const;
255 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
256 /// operand list. This adds the code marker and includes the number of
257 /// values added into it.
258 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
259 std::vector<SDOperand> &Ops) const;
264 //===--------------------------------------------------------------------===//
265 /// createDefaultScheduler - This creates an instruction scheduler appropriate
267 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
269 MachineBasicBlock *BB) {
270 TargetLowering &TLI = IS->getTargetLowering();
272 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
273 return createTDListDAGScheduler(IS, DAG, BB);
275 assert(TLI.getSchedulingPreference() ==
276 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
277 return createBURRListDAGScheduler(IS, DAG, BB);
282 //===--------------------------------------------------------------------===//
283 /// FunctionLoweringInfo - This contains information that is global to a
284 /// function that is used when lowering a region of the function.
285 class FunctionLoweringInfo {
290 MachineRegisterInfo &RegInfo;
292 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
294 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
295 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
297 /// ValueMap - Since we emit code for the function a basic block at a time,
298 /// we must remember which virtual registers hold the values for
299 /// cross-basic-block values.
300 DenseMap<const Value*, unsigned> ValueMap;
302 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
303 /// the entry block. This allows the allocas to be efficiently referenced
304 /// anywhere in the function.
305 std::map<const AllocaInst*, int> StaticAllocaMap;
308 SmallSet<Instruction*, 8> CatchInfoLost;
309 SmallSet<Instruction*, 8> CatchInfoFound;
312 unsigned MakeReg(MVT VT) {
313 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
316 /// isExportedInst - Return true if the specified value is an instruction
317 /// exported from its block.
318 bool isExportedInst(const Value *V) {
319 return ValueMap.count(V);
322 unsigned CreateRegForValue(const Value *V);
324 unsigned InitializeRegForValue(const Value *V) {
325 unsigned &R = ValueMap[V];
326 assert(R == 0 && "Already initialized this value register!");
327 return R = CreateRegForValue(V);
332 /// isSelector - Return true if this instruction is a call to the
333 /// eh.selector intrinsic.
334 static bool isSelector(Instruction *I) {
335 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
336 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
337 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
341 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
342 /// PHI nodes or outside of the basic block that defines it, or used by a
343 /// switch or atomic instruction, which may expand to multiple basic blocks.
344 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
345 if (isa<PHINode>(I)) return true;
346 BasicBlock *BB = I->getParent();
347 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
348 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
349 // FIXME: Remove switchinst special case.
350 isa<SwitchInst>(*UI))
355 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
356 /// entry block, return true. This includes arguments used by switches, since
357 /// the switch may expand into multiple basic blocks.
358 static bool isOnlyUsedInEntryBlock(Argument *A) {
359 BasicBlock *Entry = A->getParent()->begin();
360 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
361 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
362 return false; // Use not in entry block.
366 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
367 Function &fn, MachineFunction &mf)
368 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
370 // Create a vreg for each argument register that is not dead and is used
371 // outside of the entry block for the function.
372 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
374 if (!isOnlyUsedInEntryBlock(AI))
375 InitializeRegForValue(AI);
377 // Initialize the mapping of values to registers. This is only set up for
378 // instruction values that are used outside of the block that defines
380 Function::iterator BB = Fn.begin(), EB = Fn.end();
381 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
382 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
383 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
384 const Type *Ty = AI->getAllocatedType();
385 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
387 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
390 TySize *= CUI->getZExtValue(); // Get total allocated size.
391 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
392 StaticAllocaMap[AI] =
393 MF.getFrameInfo()->CreateStackObject(TySize, Align);
396 for (; BB != EB; ++BB)
397 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
398 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
399 if (!isa<AllocaInst>(I) ||
400 !StaticAllocaMap.count(cast<AllocaInst>(I)))
401 InitializeRegForValue(I);
403 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
404 // also creates the initial PHI MachineInstrs, though none of the input
405 // operands are populated.
406 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
407 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
409 MF.getBasicBlockList().push_back(MBB);
411 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
414 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
415 if (PN->use_empty()) continue;
417 MVT VT = TLI.getValueType(PN->getType());
418 unsigned NumRegisters = TLI.getNumRegisters(VT);
419 unsigned PHIReg = ValueMap[PN];
420 assert(PHIReg && "PHI node does not have an assigned virtual register!");
421 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
422 for (unsigned i = 0; i != NumRegisters; ++i)
423 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
428 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
429 /// the correctly promoted or expanded types. Assign these registers
430 /// consecutive vreg numbers and return the first assigned number.
432 /// In the case that the given value has struct or array type, this function
433 /// will assign registers for each member or element.
435 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
436 SmallVector<MVT, 4> ValueVTs;
437 ComputeValueVTs(TLI, V->getType(), ValueVTs);
439 unsigned FirstReg = 0;
440 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
441 MVT ValueVT = ValueVTs[Value];
442 MVT RegisterVT = TLI.getRegisterType(ValueVT);
444 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
445 for (unsigned i = 0; i != NumRegs; ++i) {
446 unsigned R = MakeReg(RegisterVT);
447 if (!FirstReg) FirstReg = R;
453 //===----------------------------------------------------------------------===//
454 /// SelectionDAGLowering - This is the common target-independent lowering
455 /// implementation that is parameterized by a TargetLowering object.
456 /// Also, targets can overload any lowering method.
459 class SelectionDAGLowering {
460 MachineBasicBlock *CurMBB;
462 DenseMap<const Value*, SDOperand> NodeMap;
464 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
465 /// them up and then emit token factor nodes when possible. This allows us to
466 /// get simple disambiguation between loads without worrying about alias
468 std::vector<SDOperand> PendingLoads;
470 /// PendingExports - CopyToReg nodes that copy values to virtual registers
471 /// for export to other blocks need to be emitted before any terminator
472 /// instruction, but they have no other ordering requirements. We bunch them
473 /// up and the emit a single tokenfactor for them just before terminator
475 std::vector<SDOperand> PendingExports;
477 /// Case - A struct to record the Value for a switch case, and the
478 /// case's target basic block.
482 MachineBasicBlock* BB;
484 Case() : Low(0), High(0), BB(0) { }
485 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
486 Low(low), High(high), BB(bb) { }
487 uint64_t size() const {
488 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
489 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
490 return (rHigh - rLow + 1ULL);
496 MachineBasicBlock* BB;
499 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
500 Mask(mask), BB(bb), Bits(bits) { }
503 typedef std::vector<Case> CaseVector;
504 typedef std::vector<CaseBits> CaseBitsVector;
505 typedef CaseVector::iterator CaseItr;
506 typedef std::pair<CaseItr, CaseItr> CaseRange;
508 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
509 /// of conditional branches.
511 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
512 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
514 /// CaseBB - The MBB in which to emit the compare and branch
515 MachineBasicBlock *CaseBB;
516 /// LT, GE - If nonzero, we know the current case value must be less-than or
517 /// greater-than-or-equal-to these Constants.
520 /// Range - A pair of iterators representing the range of case values to be
521 /// processed at this point in the binary search tree.
525 typedef std::vector<CaseRec> CaseRecVector;
527 /// The comparison function for sorting the switch case values in the vector.
528 /// WARNING: Case ranges should be disjoint!
530 bool operator () (const Case& C1, const Case& C2) {
531 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
532 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
533 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
534 return CI1->getValue().slt(CI2->getValue());
539 bool operator () (const CaseBits& C1, const CaseBits& C2) {
540 return C1.Bits > C2.Bits;
544 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
547 // TLI - This is information that describes the available target features we
548 // need for lowering. This indicates when operations are unavailable,
549 // implemented with a libcall, etc.
552 const TargetData *TD;
555 /// SwitchCases - Vector of CaseBlock structures used to communicate
556 /// SwitchInst code generation information.
557 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
558 /// JTCases - Vector of JumpTable structures used to communicate
559 /// SwitchInst code generation information.
560 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
561 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
563 /// FuncInfo - Information about the function as a whole.
565 FunctionLoweringInfo &FuncInfo;
567 /// GCI - Garbage collection metadata for the function.
568 CollectorMetadata *GCI;
570 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
572 FunctionLoweringInfo &funcinfo,
573 CollectorMetadata *gci)
574 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
575 FuncInfo(funcinfo), GCI(gci) {
578 /// getRoot - Return the current virtual root of the Selection DAG,
579 /// flushing any PendingLoad items. This must be done before emitting
580 /// a store or any other node that may need to be ordered after any
581 /// prior load instructions.
583 SDOperand getRoot() {
584 if (PendingLoads.empty())
585 return DAG.getRoot();
587 if (PendingLoads.size() == 1) {
588 SDOperand Root = PendingLoads[0];
590 PendingLoads.clear();
594 // Otherwise, we have to make a token factor node.
595 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
596 &PendingLoads[0], PendingLoads.size());
597 PendingLoads.clear();
602 /// getControlRoot - Similar to getRoot, but instead of flushing all the
603 /// PendingLoad items, flush all the PendingExports items. It is necessary
604 /// to do this before emitting a terminator instruction.
606 SDOperand getControlRoot() {
607 SDOperand Root = DAG.getRoot();
609 if (PendingExports.empty())
612 // Turn all of the CopyToReg chains into one factored node.
613 if (Root.getOpcode() != ISD::EntryToken) {
614 unsigned i = 0, e = PendingExports.size();
615 for (; i != e; ++i) {
616 assert(PendingExports[i].Val->getNumOperands() > 1);
617 if (PendingExports[i].Val->getOperand(0) == Root)
618 break; // Don't add the root if we already indirectly depend on it.
622 PendingExports.push_back(Root);
625 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
627 PendingExports.size());
628 PendingExports.clear();
633 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
635 void visit(Instruction &I) { visit(I.getOpcode(), I); }
637 void visit(unsigned Opcode, User &I) {
638 // Note: this doesn't use InstVisitor, because it has to work with
639 // ConstantExpr's in addition to instructions.
641 default: assert(0 && "Unknown instruction type encountered!");
643 // Build the switch statement using the Instruction.def file.
644 #define HANDLE_INST(NUM, OPCODE, CLASS) \
645 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
646 #include "llvm/Instruction.def"
650 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
652 SDOperand getValue(const Value *V);
654 void setValue(const Value *V, SDOperand NewN) {
655 SDOperand &N = NodeMap[V];
656 assert(N.Val == 0 && "Already set a value for this node!");
660 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
661 std::set<unsigned> &OutputRegs,
662 std::set<unsigned> &InputRegs);
664 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
665 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
667 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
668 void ExportFromCurrentBlock(Value *V);
669 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
670 MachineBasicBlock *LandingPad = NULL);
672 // Terminator instructions.
673 void visitRet(ReturnInst &I);
674 void visitBr(BranchInst &I);
675 void visitSwitch(SwitchInst &I);
676 void visitUnreachable(UnreachableInst &I) { /* noop */ }
678 // Helpers for visitSwitch
679 bool handleSmallSwitchRange(CaseRec& CR,
680 CaseRecVector& WorkList,
682 MachineBasicBlock* Default);
683 bool handleJTSwitchCase(CaseRec& CR,
684 CaseRecVector& WorkList,
686 MachineBasicBlock* Default);
687 bool handleBTSplitSwitchCase(CaseRec& CR,
688 CaseRecVector& WorkList,
690 MachineBasicBlock* Default);
691 bool handleBitTestsSwitchCase(CaseRec& CR,
692 CaseRecVector& WorkList,
694 MachineBasicBlock* Default);
695 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
696 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
697 void visitBitTestCase(MachineBasicBlock* NextMBB,
699 SelectionDAGISel::BitTestCase &B);
700 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
701 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
702 SelectionDAGISel::JumpTableHeader &JTH);
704 // These all get lowered before this pass.
705 void visitInvoke(InvokeInst &I);
706 void visitUnwind(UnwindInst &I);
708 void visitBinary(User &I, unsigned OpCode);
709 void visitShift(User &I, unsigned Opcode);
710 void visitAdd(User &I) {
711 if (I.getType()->isFPOrFPVector())
712 visitBinary(I, ISD::FADD);
714 visitBinary(I, ISD::ADD);
716 void visitSub(User &I);
717 void visitMul(User &I) {
718 if (I.getType()->isFPOrFPVector())
719 visitBinary(I, ISD::FMUL);
721 visitBinary(I, ISD::MUL);
723 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
724 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
725 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
726 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
727 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
728 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
729 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
730 void visitOr (User &I) { visitBinary(I, ISD::OR); }
731 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
732 void visitShl (User &I) { visitShift(I, ISD::SHL); }
733 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
734 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
735 void visitICmp(User &I);
736 void visitFCmp(User &I);
737 void visitVICmp(User &I);
738 void visitVFCmp(User &I);
739 // Visit the conversion instructions
740 void visitTrunc(User &I);
741 void visitZExt(User &I);
742 void visitSExt(User &I);
743 void visitFPTrunc(User &I);
744 void visitFPExt(User &I);
745 void visitFPToUI(User &I);
746 void visitFPToSI(User &I);
747 void visitUIToFP(User &I);
748 void visitSIToFP(User &I);
749 void visitPtrToInt(User &I);
750 void visitIntToPtr(User &I);
751 void visitBitCast(User &I);
753 void visitExtractElement(User &I);
754 void visitInsertElement(User &I);
755 void visitShuffleVector(User &I);
757 void visitExtractValue(ExtractValueInst &I);
758 void visitInsertValue(InsertValueInst &I);
760 void visitGetElementPtr(User &I);
761 void visitSelect(User &I);
763 void visitMalloc(MallocInst &I);
764 void visitFree(FreeInst &I);
765 void visitAlloca(AllocaInst &I);
766 void visitLoad(LoadInst &I);
767 void visitStore(StoreInst &I);
768 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
769 void visitCall(CallInst &I);
770 void visitInlineAsm(CallSite CS);
771 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
772 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
774 void visitVAStart(CallInst &I);
775 void visitVAArg(VAArgInst &I);
776 void visitVAEnd(CallInst &I);
777 void visitVACopy(CallInst &I);
779 void visitGetResult(GetResultInst &I);
781 void visitUserOp1(Instruction &I) {
782 assert(0 && "UserOp1 should not exist at instruction selection time!");
785 void visitUserOp2(Instruction &I) {
786 assert(0 && "UserOp2 should not exist at instruction selection time!");
791 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
794 } // end namespace llvm
797 /// getCopyFromParts - Create a value that contains the specified legal parts
798 /// combined into the value they represent. If the parts combine to a type
799 /// larger then ValueVT then AssertOp can be used to specify whether the extra
800 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
801 /// (ISD::AssertSext).
802 static SDOperand getCopyFromParts(SelectionDAG &DAG,
803 const SDOperand *Parts,
807 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
808 assert(NumParts > 0 && "No parts to assemble!");
809 TargetLowering &TLI = DAG.getTargetLoweringInfo();
810 SDOperand Val = Parts[0];
813 // Assemble the value from multiple parts.
814 if (!ValueVT.isVector()) {
815 unsigned PartBits = PartVT.getSizeInBits();
816 unsigned ValueBits = ValueVT.getSizeInBits();
818 // Assemble the power of 2 part.
819 unsigned RoundParts = NumParts & (NumParts - 1) ?
820 1 << Log2_32(NumParts) : NumParts;
821 unsigned RoundBits = PartBits * RoundParts;
822 MVT RoundVT = RoundBits == ValueBits ?
823 ValueVT : MVT::getIntegerVT(RoundBits);
826 if (RoundParts > 2) {
827 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
828 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
829 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
835 if (TLI.isBigEndian())
837 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
839 if (RoundParts < NumParts) {
840 // Assemble the trailing non-power-of-2 part.
841 unsigned OddParts = NumParts - RoundParts;
842 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
843 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
845 // Combine the round and odd parts.
847 if (TLI.isBigEndian())
849 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
850 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
851 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
852 DAG.getConstant(Lo.getValueType().getSizeInBits(),
853 TLI.getShiftAmountTy()));
854 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
855 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
858 // Handle a multi-element vector.
859 MVT IntermediateVT, RegisterVT;
860 unsigned NumIntermediates;
862 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
864 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
865 NumParts = NumRegs; // Silence a compiler warning.
866 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
867 assert(RegisterVT == Parts[0].getValueType() &&
868 "Part type doesn't match part!");
870 // Assemble the parts into intermediate operands.
871 SmallVector<SDOperand, 8> Ops(NumIntermediates);
872 if (NumIntermediates == NumParts) {
873 // If the register was not expanded, truncate or copy the value,
875 for (unsigned i = 0; i != NumParts; ++i)
876 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
877 PartVT, IntermediateVT);
878 } else if (NumParts > 0) {
879 // If the intermediate type was expanded, build the intermediate operands
881 assert(NumParts % NumIntermediates == 0 &&
882 "Must expand into a divisible number of parts!");
883 unsigned Factor = NumParts / NumIntermediates;
884 for (unsigned i = 0; i != NumIntermediates; ++i)
885 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
886 PartVT, IntermediateVT);
889 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
891 Val = DAG.getNode(IntermediateVT.isVector() ?
892 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
893 ValueVT, &Ops[0], NumIntermediates);
897 // There is now one part, held in Val. Correct it to match ValueVT.
898 PartVT = Val.getValueType();
900 if (PartVT == ValueVT)
903 if (PartVT.isVector()) {
904 assert(ValueVT.isVector() && "Unknown vector conversion!");
905 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
908 if (ValueVT.isVector()) {
909 assert(ValueVT.getVectorElementType() == PartVT &&
910 ValueVT.getVectorNumElements() == 1 &&
911 "Only trivial scalar-to-vector conversions should get here!");
912 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
915 if (PartVT.isInteger() &&
916 ValueVT.isInteger()) {
917 if (ValueVT.bitsLT(PartVT)) {
918 // For a truncate, see if we have any information to
919 // indicate whether the truncated bits will always be
920 // zero or sign-extension.
921 if (AssertOp != ISD::DELETED_NODE)
922 Val = DAG.getNode(AssertOp, PartVT, Val,
923 DAG.getValueType(ValueVT));
924 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
926 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
930 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
931 if (ValueVT.bitsLT(Val.getValueType()))
932 // FP_ROUND's are always exact here.
933 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
934 DAG.getIntPtrConstant(1));
935 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
938 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
939 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
941 assert(0 && "Unknown mismatch!");
945 /// getCopyToParts - Create a series of nodes that contain the specified value
946 /// split into legal parts. If the parts contain more bits than Val, then, for
947 /// integers, ExtendKind can be used to specify how to generate the extra bits.
948 static void getCopyToParts(SelectionDAG &DAG,
953 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
954 TargetLowering &TLI = DAG.getTargetLoweringInfo();
955 MVT PtrVT = TLI.getPointerTy();
956 MVT ValueVT = Val.getValueType();
957 unsigned PartBits = PartVT.getSizeInBits();
958 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
963 if (!ValueVT.isVector()) {
964 if (PartVT == ValueVT) {
965 assert(NumParts == 1 && "No-op copy with multiple parts!");
970 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
971 // If the parts cover more bits than the value has, promote the value.
972 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
973 assert(NumParts == 1 && "Do not know what to promote to!");
974 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
975 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
976 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
977 Val = DAG.getNode(ExtendKind, ValueVT, Val);
979 assert(0 && "Unknown mismatch!");
981 } else if (PartBits == ValueVT.getSizeInBits()) {
982 // Different types of the same size.
983 assert(NumParts == 1 && PartVT != ValueVT);
984 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
985 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
986 // If the parts cover less bits than value has, truncate the value.
987 if (PartVT.isInteger() && ValueVT.isInteger()) {
988 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
989 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
991 assert(0 && "Unknown mismatch!");
995 // The value may have changed - recompute ValueVT.
996 ValueVT = Val.getValueType();
997 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
998 "Failed to tile the value with PartVT!");
1000 if (NumParts == 1) {
1001 assert(PartVT == ValueVT && "Type conversion failed!");
1006 // Expand the value into multiple parts.
1007 if (NumParts & (NumParts - 1)) {
1008 // The number of parts is not a power of 2. Split off and copy the tail.
1009 assert(PartVT.isInteger() && ValueVT.isInteger() &&
1010 "Do not know what to expand to!");
1011 unsigned RoundParts = 1 << Log2_32(NumParts);
1012 unsigned RoundBits = RoundParts * PartBits;
1013 unsigned OddParts = NumParts - RoundParts;
1014 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1015 DAG.getConstant(RoundBits,
1016 TLI.getShiftAmountTy()));
1017 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1018 if (TLI.isBigEndian())
1019 // The odd parts were reversed by getCopyToParts - unreverse them.
1020 std::reverse(Parts + RoundParts, Parts + NumParts);
1021 NumParts = RoundParts;
1022 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1023 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1026 // The number of parts is a power of 2. Repeatedly bisect the value using
1028 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
1029 MVT::getIntegerVT(ValueVT.getSizeInBits()),
1031 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1032 for (unsigned i = 0; i < NumParts; i += StepSize) {
1033 unsigned ThisBits = StepSize * PartBits / 2;
1034 MVT ThisVT = MVT::getIntegerVT (ThisBits);
1035 SDOperand &Part0 = Parts[i];
1036 SDOperand &Part1 = Parts[i+StepSize/2];
1038 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1039 DAG.getConstant(1, PtrVT));
1040 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1041 DAG.getConstant(0, PtrVT));
1043 if (ThisBits == PartBits && ThisVT != PartVT) {
1044 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1045 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1050 if (TLI.isBigEndian())
1051 std::reverse(Parts, Parts + NumParts);
1057 if (NumParts == 1) {
1058 if (PartVT != ValueVT) {
1059 if (PartVT.isVector()) {
1060 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1062 assert(ValueVT.getVectorElementType() == PartVT &&
1063 ValueVT.getVectorNumElements() == 1 &&
1064 "Only trivial vector-to-scalar conversions should get here!");
1065 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1066 DAG.getConstant(0, PtrVT));
1074 // Handle a multi-element vector.
1075 MVT IntermediateVT, RegisterVT;
1076 unsigned NumIntermediates;
1078 DAG.getTargetLoweringInfo()
1079 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1081 unsigned NumElements = ValueVT.getVectorNumElements();
1083 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1084 NumParts = NumRegs; // Silence a compiler warning.
1085 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1087 // Split the vector into intermediate operands.
1088 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1089 for (unsigned i = 0; i != NumIntermediates; ++i)
1090 if (IntermediateVT.isVector())
1091 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1092 IntermediateVT, Val,
1093 DAG.getConstant(i * (NumElements / NumIntermediates),
1096 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1097 IntermediateVT, Val,
1098 DAG.getConstant(i, PtrVT));
1100 // Split the intermediate operands into legal parts.
1101 if (NumParts == NumIntermediates) {
1102 // If the register was not expanded, promote or copy the value,
1104 for (unsigned i = 0; i != NumParts; ++i)
1105 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1106 } else if (NumParts > 0) {
1107 // If the intermediate type was expanded, split each the value into
1109 assert(NumParts % NumIntermediates == 0 &&
1110 "Must expand into a divisible number of parts!");
1111 unsigned Factor = NumParts / NumIntermediates;
1112 for (unsigned i = 0; i != NumIntermediates; ++i)
1113 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1118 SDOperand SelectionDAGLowering::getValue(const Value *V) {
1119 SDOperand &N = NodeMap[V];
1120 if (N.Val) return N;
1122 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1123 MVT VT = TLI.getValueType(V->getType(), true);
1125 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1126 return N = DAG.getConstant(CI->getValue(), VT);
1128 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1129 return N = DAG.getGlobalAddress(GV, VT);
1131 if (isa<ConstantPointerNull>(C))
1132 return N = DAG.getConstant(0, TLI.getPointerTy());
1134 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1135 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1137 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1138 !V->getType()->isAggregateType())
1139 return N = DAG.getNode(ISD::UNDEF, VT);
1141 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1142 visit(CE->getOpcode(), *CE);
1143 SDOperand N1 = NodeMap[V];
1144 assert(N1.Val && "visit didn't populate the ValueMap!");
1148 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1149 SmallVector<SDOperand, 4> Constants;
1150 SmallVector<MVT, 4> ValueVTs;
1151 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1153 SDNode *Val = getValue(*OI).Val;
1154 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) {
1155 Constants.push_back(SDOperand(Val, i));
1156 ValueVTs.push_back(Val->getValueType(i));
1159 return DAG.getNode(ISD::MERGE_VALUES,
1160 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1161 &Constants[0], Constants.size());
1164 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
1165 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1166 "Unknown array constant!");
1167 unsigned NumElts = ATy->getNumElements();
1169 return SDOperand(); // empty array
1170 MVT EltVT = TLI.getValueType(ATy->getElementType());
1171 SmallVector<SDOperand, 4> Constants(NumElts);
1172 SmallVector<MVT, 4> ValueVTs(NumElts, EltVT);
1173 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1174 if (isa<UndefValue>(C))
1175 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1176 else if (EltVT.isFloatingPoint())
1177 Constants[i] = DAG.getConstantFP(0, EltVT);
1179 Constants[i] = DAG.getConstant(0, EltVT);
1181 return DAG.getNode(ISD::MERGE_VALUES,
1182 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1183 &Constants[0], Constants.size());
1186 if (const StructType *STy = dyn_cast<StructType>(C->getType())) {
1187 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1188 "Unknown struct constant!");
1189 unsigned NumElts = STy->getNumElements();
1191 return SDOperand(); // empty struct
1192 SmallVector<SDOperand, 4> Constants(NumElts);
1193 SmallVector<MVT, 4> ValueVTs(NumElts);
1194 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1195 MVT EltVT = TLI.getValueType(STy->getElementType(i));
1196 ValueVTs[i] = EltVT;
1197 if (isa<UndefValue>(C))
1198 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1199 else if (EltVT.isFloatingPoint())
1200 Constants[i] = DAG.getConstantFP(0, EltVT);
1202 Constants[i] = DAG.getConstant(0, EltVT);
1204 return DAG.getNode(ISD::MERGE_VALUES,
1205 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1206 &Constants[0], Constants.size());
1209 const VectorType *VecTy = cast<VectorType>(V->getType());
1210 unsigned NumElements = VecTy->getNumElements();
1212 // Now that we know the number and type of the elements, get that number of
1213 // elements into the Ops array based on what kind of constant it is.
1214 SmallVector<SDOperand, 16> Ops;
1215 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1216 for (unsigned i = 0; i != NumElements; ++i)
1217 Ops.push_back(getValue(CP->getOperand(i)));
1219 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1220 "Unknown vector constant!");
1221 MVT EltVT = TLI.getValueType(VecTy->getElementType());
1224 if (isa<UndefValue>(C))
1225 Op = DAG.getNode(ISD::UNDEF, EltVT);
1226 else if (EltVT.isFloatingPoint())
1227 Op = DAG.getConstantFP(0, EltVT);
1229 Op = DAG.getConstant(0, EltVT);
1230 Ops.assign(NumElements, Op);
1233 // Create a BUILD_VECTOR node.
1234 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1237 // If this is a static alloca, generate it as the frameindex instead of
1239 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1240 std::map<const AllocaInst*, int>::iterator SI =
1241 FuncInfo.StaticAllocaMap.find(AI);
1242 if (SI != FuncInfo.StaticAllocaMap.end())
1243 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1246 unsigned InReg = FuncInfo.ValueMap[V];
1247 assert(InReg && "Value not in map!");
1249 RegsForValue RFV(TLI, InReg, V->getType());
1250 SDOperand Chain = DAG.getEntryNode();
1251 return RFV.getCopyFromRegs(DAG, Chain, NULL);
1255 void SelectionDAGLowering::visitRet(ReturnInst &I) {
1256 if (I.getNumOperands() == 0) {
1257 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1261 SmallVector<SDOperand, 8> NewValues;
1262 NewValues.push_back(getControlRoot());
1263 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1264 SDOperand RetOp = getValue(I.getOperand(i));
1265 MVT VT = RetOp.getValueType();
1267 // FIXME: C calling convention requires the return type to be promoted to
1268 // at least 32-bit. But this is not necessary for non-C calling conventions.
1269 if (VT.isInteger()) {
1270 MVT MinVT = TLI.getRegisterType(MVT::i32);
1271 if (VT.bitsLT(MinVT))
1275 unsigned NumParts = TLI.getNumRegisters(VT);
1276 MVT PartVT = TLI.getRegisterType(VT);
1277 SmallVector<SDOperand, 4> Parts(NumParts);
1278 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1280 const Function *F = I.getParent()->getParent();
1281 if (F->paramHasAttr(0, ParamAttr::SExt))
1282 ExtendKind = ISD::SIGN_EXTEND;
1283 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1284 ExtendKind = ISD::ZERO_EXTEND;
1286 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1288 for (unsigned i = 0; i < NumParts; ++i) {
1289 NewValues.push_back(Parts[i]);
1290 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1293 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1294 &NewValues[0], NewValues.size()));
1297 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1298 /// the current basic block, add it to ValueMap now so that we'll get a
1300 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1301 // No need to export constants.
1302 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1304 // Already exported?
1305 if (FuncInfo.isExportedInst(V)) return;
1307 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1308 CopyValueToVirtualRegister(V, Reg);
1311 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1312 const BasicBlock *FromBB) {
1313 // The operands of the setcc have to be in this block. We don't know
1314 // how to export them from some other block.
1315 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1316 // Can export from current BB.
1317 if (VI->getParent() == FromBB)
1320 // Is already exported, noop.
1321 return FuncInfo.isExportedInst(V);
1324 // If this is an argument, we can export it if the BB is the entry block or
1325 // if it is already exported.
1326 if (isa<Argument>(V)) {
1327 if (FromBB == &FromBB->getParent()->getEntryBlock())
1330 // Otherwise, can only export this if it is already exported.
1331 return FuncInfo.isExportedInst(V);
1334 // Otherwise, constants can always be exported.
1338 static bool InBlock(const Value *V, const BasicBlock *BB) {
1339 if (const Instruction *I = dyn_cast<Instruction>(V))
1340 return I->getParent() == BB;
1344 /// FindMergedConditions - If Cond is an expression like
1345 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1346 MachineBasicBlock *TBB,
1347 MachineBasicBlock *FBB,
1348 MachineBasicBlock *CurBB,
1350 // If this node is not part of the or/and tree, emit it as a branch.
1351 Instruction *BOp = dyn_cast<Instruction>(Cond);
1353 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1354 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1355 BOp->getParent() != CurBB->getBasicBlock() ||
1356 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1357 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1358 const BasicBlock *BB = CurBB->getBasicBlock();
1360 // If the leaf of the tree is a comparison, merge the condition into
1362 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1363 // The operands of the cmp have to be in this block. We don't know
1364 // how to export them from some other block. If this is the first block
1365 // of the sequence, no exporting is needed.
1367 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1368 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1369 BOp = cast<Instruction>(Cond);
1370 ISD::CondCode Condition;
1371 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1372 switch (IC->getPredicate()) {
1373 default: assert(0 && "Unknown icmp predicate opcode!");
1374 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1375 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1376 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1377 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1378 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1379 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1380 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1381 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1382 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1383 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1385 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1386 ISD::CondCode FPC, FOC;
1387 switch (FC->getPredicate()) {
1388 default: assert(0 && "Unknown fcmp predicate opcode!");
1389 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1390 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1391 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1392 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1393 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1394 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1395 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1396 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1397 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1398 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1399 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1400 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1401 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1402 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1403 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1404 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1406 if (FiniteOnlyFPMath())
1411 Condition = ISD::SETEQ; // silence warning.
1412 assert(0 && "Unknown compare instruction");
1415 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1416 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1417 SwitchCases.push_back(CB);
1421 // Create a CaseBlock record representing this branch.
1422 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1423 NULL, TBB, FBB, CurBB);
1424 SwitchCases.push_back(CB);
1429 // Create TmpBB after CurBB.
1430 MachineFunction::iterator BBI = CurBB;
1431 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1432 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1434 if (Opc == Instruction::Or) {
1435 // Codegen X | Y as:
1443 // Emit the LHS condition.
1444 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1446 // Emit the RHS condition into TmpBB.
1447 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1449 assert(Opc == Instruction::And && "Unknown merge op!");
1450 // Codegen X & Y as:
1457 // This requires creation of TmpBB after CurBB.
1459 // Emit the LHS condition.
1460 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1462 // Emit the RHS condition into TmpBB.
1463 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1467 /// If the set of cases should be emitted as a series of branches, return true.
1468 /// If we should emit this as a bunch of and/or'd together conditions, return
1471 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1472 if (Cases.size() != 2) return true;
1474 // If this is two comparisons of the same values or'd or and'd together, they
1475 // will get folded into a single comparison, so don't emit two blocks.
1476 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1477 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1478 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1479 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1486 void SelectionDAGLowering::visitBr(BranchInst &I) {
1487 // Update machine-CFG edges.
1488 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1490 // Figure out which block is immediately after the current one.
1491 MachineBasicBlock *NextBlock = 0;
1492 MachineFunction::iterator BBI = CurMBB;
1493 if (++BBI != CurMBB->getParent()->end())
1496 if (I.isUnconditional()) {
1497 // Update machine-CFG edges.
1498 CurMBB->addSuccessor(Succ0MBB);
1500 // If this is not a fall-through branch, emit the branch.
1501 if (Succ0MBB != NextBlock)
1502 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1503 DAG.getBasicBlock(Succ0MBB)));
1507 // If this condition is one of the special cases we handle, do special stuff
1509 Value *CondVal = I.getCondition();
1510 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1512 // If this is a series of conditions that are or'd or and'd together, emit
1513 // this as a sequence of branches instead of setcc's with and/or operations.
1514 // For example, instead of something like:
1527 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1528 if (BOp->hasOneUse() &&
1529 (BOp->getOpcode() == Instruction::And ||
1530 BOp->getOpcode() == Instruction::Or)) {
1531 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1532 // If the compares in later blocks need to use values not currently
1533 // exported from this block, export them now. This block should always
1534 // be the first entry.
1535 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1537 // Allow some cases to be rejected.
1538 if (ShouldEmitAsBranches(SwitchCases)) {
1539 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1540 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1541 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1544 // Emit the branch for this block.
1545 visitSwitchCase(SwitchCases[0]);
1546 SwitchCases.erase(SwitchCases.begin());
1550 // Okay, we decided not to do this, remove any inserted MBB's and clear
1552 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1553 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1555 SwitchCases.clear();
1559 // Create a CaseBlock record representing this branch.
1560 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1561 NULL, Succ0MBB, Succ1MBB, CurMBB);
1562 // Use visitSwitchCase to actually insert the fast branch sequence for this
1564 visitSwitchCase(CB);
1567 /// visitSwitchCase - Emits the necessary code to represent a single node in
1568 /// the binary search tree resulting from lowering a switch instruction.
1569 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1571 SDOperand CondLHS = getValue(CB.CmpLHS);
1573 // Build the setcc now.
1574 if (CB.CmpMHS == NULL) {
1575 // Fold "(X == true)" to X and "(X == false)" to !X to
1576 // handle common cases produced by branch lowering.
1577 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1579 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1580 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1581 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1583 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1585 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1587 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1588 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1590 SDOperand CmpOp = getValue(CB.CmpMHS);
1591 MVT VT = CmpOp.getValueType();
1593 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1594 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1596 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1597 Cond = DAG.getSetCC(MVT::i1, SUB,
1598 DAG.getConstant(High-Low, VT), ISD::SETULE);
1602 // Update successor info
1603 CurMBB->addSuccessor(CB.TrueBB);
1604 CurMBB->addSuccessor(CB.FalseBB);
1606 // Set NextBlock to be the MBB immediately after the current one, if any.
1607 // This is used to avoid emitting unnecessary branches to the next block.
1608 MachineBasicBlock *NextBlock = 0;
1609 MachineFunction::iterator BBI = CurMBB;
1610 if (++BBI != CurMBB->getParent()->end())
1613 // If the lhs block is the next block, invert the condition so that we can
1614 // fall through to the lhs instead of the rhs block.
1615 if (CB.TrueBB == NextBlock) {
1616 std::swap(CB.TrueBB, CB.FalseBB);
1617 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1618 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1620 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1621 DAG.getBasicBlock(CB.TrueBB));
1622 if (CB.FalseBB == NextBlock)
1623 DAG.setRoot(BrCond);
1625 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1626 DAG.getBasicBlock(CB.FalseBB)));
1629 /// visitJumpTable - Emit JumpTable node in the current MBB
1630 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1631 // Emit the code for the jump table
1632 assert(JT.Reg != -1U && "Should lower JT Header first!");
1633 MVT PTy = TLI.getPointerTy();
1634 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1635 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1636 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1641 /// visitJumpTableHeader - This function emits necessary code to produce index
1642 /// in the JumpTable from switch case.
1643 void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1644 SelectionDAGISel::JumpTableHeader &JTH) {
1645 // Subtract the lowest switch case value from the value being switched on
1646 // and conditional branch to default mbb if the result is greater than the
1647 // difference between smallest and largest cases.
1648 SDOperand SwitchOp = getValue(JTH.SValue);
1649 MVT VT = SwitchOp.getValueType();
1650 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1651 DAG.getConstant(JTH.First, VT));
1653 // The SDNode we just created, which holds the value being switched on
1654 // minus the the smallest case value, needs to be copied to a virtual
1655 // register so it can be used as an index into the jump table in a
1656 // subsequent basic block. This value may be smaller or larger than the
1657 // target's pointer type, and therefore require extension or truncating.
1658 if (VT.bitsGT(TLI.getPointerTy()))
1659 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1661 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1663 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1664 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1665 JT.Reg = JumpTableReg;
1667 // Emit the range check for the jump table, and branch to the default
1668 // block for the switch statement if the value being switched on exceeds
1669 // the largest case in the switch.
1670 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1671 DAG.getConstant(JTH.Last-JTH.First,VT),
1674 // Set NextBlock to be the MBB immediately after the current one, if any.
1675 // This is used to avoid emitting unnecessary branches to the next block.
1676 MachineBasicBlock *NextBlock = 0;
1677 MachineFunction::iterator BBI = CurMBB;
1678 if (++BBI != CurMBB->getParent()->end())
1681 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1682 DAG.getBasicBlock(JT.Default));
1684 if (JT.MBB == NextBlock)
1685 DAG.setRoot(BrCond);
1687 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1688 DAG.getBasicBlock(JT.MBB)));
1693 /// visitBitTestHeader - This function emits necessary code to produce value
1694 /// suitable for "bit tests"
1695 void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1696 // Subtract the minimum value
1697 SDOperand SwitchOp = getValue(B.SValue);
1698 MVT VT = SwitchOp.getValueType();
1699 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1700 DAG.getConstant(B.First, VT));
1703 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1704 DAG.getConstant(B.Range, VT),
1708 if (VT.bitsGT(TLI.getShiftAmountTy()))
1709 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1711 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1713 // Make desired shift
1714 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1715 DAG.getConstant(1, TLI.getPointerTy()),
1718 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1719 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1722 // Set NextBlock to be the MBB immediately after the current one, if any.
1723 // This is used to avoid emitting unnecessary branches to the next block.
1724 MachineBasicBlock *NextBlock = 0;
1725 MachineFunction::iterator BBI = CurMBB;
1726 if (++BBI != CurMBB->getParent()->end())
1729 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1731 CurMBB->addSuccessor(B.Default);
1732 CurMBB->addSuccessor(MBB);
1734 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1735 DAG.getBasicBlock(B.Default));
1737 if (MBB == NextBlock)
1738 DAG.setRoot(BrRange);
1740 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1741 DAG.getBasicBlock(MBB)));
1746 /// visitBitTestCase - this function produces one "bit test"
1747 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1749 SelectionDAGISel::BitTestCase &B) {
1750 // Emit bit tests and jumps
1751 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
1753 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1755 DAG.getConstant(B.Mask,
1756 TLI.getPointerTy()));
1757 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1758 DAG.getConstant(0, TLI.getPointerTy()),
1761 CurMBB->addSuccessor(B.TargetBB);
1762 CurMBB->addSuccessor(NextMBB);
1764 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1765 AndCmp, DAG.getBasicBlock(B.TargetBB));
1767 // Set NextBlock to be the MBB immediately after the current one, if any.
1768 // This is used to avoid emitting unnecessary branches to the next block.
1769 MachineBasicBlock *NextBlock = 0;
1770 MachineFunction::iterator BBI = CurMBB;
1771 if (++BBI != CurMBB->getParent()->end())
1774 if (NextMBB == NextBlock)
1777 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1778 DAG.getBasicBlock(NextMBB)));
1783 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1784 // Retrieve successors.
1785 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1786 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1788 if (isa<InlineAsm>(I.getCalledValue()))
1791 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1793 // If the value of the invoke is used outside of its defining block, make it
1794 // available as a virtual register.
1795 if (!I.use_empty()) {
1796 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1797 if (VMI != FuncInfo.ValueMap.end())
1798 CopyValueToVirtualRegister(&I, VMI->second);
1801 // Update successor info
1802 CurMBB->addSuccessor(Return);
1803 CurMBB->addSuccessor(LandingPad);
1805 // Drop into normal successor.
1806 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1807 DAG.getBasicBlock(Return)));
1810 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1813 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1814 /// small case ranges).
1815 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1816 CaseRecVector& WorkList,
1818 MachineBasicBlock* Default) {
1819 Case& BackCase = *(CR.Range.second-1);
1821 // Size is the number of Cases represented by this range.
1822 unsigned Size = CR.Range.second - CR.Range.first;
1826 // Get the MachineFunction which holds the current MBB. This is used when
1827 // inserting any additional MBBs necessary to represent the switch.
1828 MachineFunction *CurMF = CurMBB->getParent();
1830 // Figure out which block is immediately after the current one.
1831 MachineBasicBlock *NextBlock = 0;
1832 MachineFunction::iterator BBI = CR.CaseBB;
1834 if (++BBI != CurMBB->getParent()->end())
1837 // TODO: If any two of the cases has the same destination, and if one value
1838 // is the same as the other, but has one bit unset that the other has set,
1839 // use bit manipulation to do two compares at once. For example:
1840 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1842 // Rearrange the case blocks so that the last one falls through if possible.
1843 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1844 // The last case block won't fall through into 'NextBlock' if we emit the
1845 // branches in this order. See if rearranging a case value would help.
1846 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1847 if (I->BB == NextBlock) {
1848 std::swap(*I, BackCase);
1854 // Create a CaseBlock record representing a conditional branch to
1855 // the Case's target mbb if the value being switched on SV is equal
1857 MachineBasicBlock *CurBlock = CR.CaseBB;
1858 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1859 MachineBasicBlock *FallThrough;
1861 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1862 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1864 // If the last case doesn't match, go to the default block.
1865 FallThrough = Default;
1868 Value *RHS, *LHS, *MHS;
1870 if (I->High == I->Low) {
1871 // This is just small small case range :) containing exactly 1 case
1873 LHS = SV; RHS = I->High; MHS = NULL;
1876 LHS = I->Low; MHS = SV; RHS = I->High;
1878 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1879 I->BB, FallThrough, CurBlock);
1881 // If emitting the first comparison, just call visitSwitchCase to emit the
1882 // code into the current block. Otherwise, push the CaseBlock onto the
1883 // vector to be later processed by SDISel, and insert the node's MBB
1884 // before the next MBB.
1885 if (CurBlock == CurMBB)
1886 visitSwitchCase(CB);
1888 SwitchCases.push_back(CB);
1890 CurBlock = FallThrough;
1896 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1897 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1898 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1901 /// handleJTSwitchCase - Emit jumptable for current switch case range
1902 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1903 CaseRecVector& WorkList,
1905 MachineBasicBlock* Default) {
1906 Case& FrontCase = *CR.Range.first;
1907 Case& BackCase = *(CR.Range.second-1);
1909 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1910 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1913 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1917 if (!areJTsAllowed(TLI) || TSize <= 3)
1920 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1924 DOUT << "Lowering jump table\n"
1925 << "First entry: " << First << ". Last entry: " << Last << "\n"
1926 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1928 // Get the MachineFunction which holds the current MBB. This is used when
1929 // inserting any additional MBBs necessary to represent the switch.
1930 MachineFunction *CurMF = CurMBB->getParent();
1932 // Figure out which block is immediately after the current one.
1933 MachineBasicBlock *NextBlock = 0;
1934 MachineFunction::iterator BBI = CR.CaseBB;
1936 if (++BBI != CurMBB->getParent()->end())
1939 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1941 // Create a new basic block to hold the code for loading the address
1942 // of the jump table, and jumping to it. Update successor information;
1943 // we will either branch to the default case for the switch, or the jump
1945 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1946 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1947 CR.CaseBB->addSuccessor(Default);
1948 CR.CaseBB->addSuccessor(JumpTableBB);
1950 // Build a vector of destination BBs, corresponding to each target
1951 // of the jump table. If the value of the jump table slot corresponds to
1952 // a case statement, push the case's BB onto the vector, otherwise, push
1954 std::vector<MachineBasicBlock*> DestBBs;
1955 int64_t TEI = First;
1956 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1957 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1958 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1960 if ((Low <= TEI) && (TEI <= High)) {
1961 DestBBs.push_back(I->BB);
1965 DestBBs.push_back(Default);
1969 // Update successor info. Add one edge to each unique successor.
1970 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1971 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1972 E = DestBBs.end(); I != E; ++I) {
1973 if (!SuccsHandled[(*I)->getNumber()]) {
1974 SuccsHandled[(*I)->getNumber()] = true;
1975 JumpTableBB->addSuccessor(*I);
1979 // Create a jump table index for this jump table, or return an existing
1981 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1983 // Set the jump table information so that we can codegen it as a second
1984 // MachineBasicBlock
1985 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1986 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1987 (CR.CaseBB == CurMBB));
1988 if (CR.CaseBB == CurMBB)
1989 visitJumpTableHeader(JT, JTH);
1991 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1996 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1998 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1999 CaseRecVector& WorkList,
2001 MachineBasicBlock* Default) {
2002 // Get the MachineFunction which holds the current MBB. This is used when
2003 // inserting any additional MBBs necessary to represent the switch.
2004 MachineFunction *CurMF = CurMBB->getParent();
2006 // Figure out which block is immediately after the current one.
2007 MachineBasicBlock *NextBlock = 0;
2008 MachineFunction::iterator BBI = CR.CaseBB;
2010 if (++BBI != CurMBB->getParent()->end())
2013 Case& FrontCase = *CR.Range.first;
2014 Case& BackCase = *(CR.Range.second-1);
2015 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2017 // Size is the number of Cases represented by this range.
2018 unsigned Size = CR.Range.second - CR.Range.first;
2020 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2021 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
2023 CaseItr Pivot = CR.Range.first + Size/2;
2025 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2026 // (heuristically) allow us to emit JumpTable's later.
2028 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2032 uint64_t LSize = FrontCase.size();
2033 uint64_t RSize = TSize-LSize;
2034 DOUT << "Selecting best pivot: \n"
2035 << "First: " << First << ", Last: " << Last <<"\n"
2036 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
2037 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2039 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2040 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
2041 assert((RBegin-LEnd>=1) && "Invalid case distance");
2042 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2043 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
2044 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
2045 // Should always split in some non-trivial place
2047 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2048 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2049 << "Metric: " << Metric << "\n";
2050 if (FMetric < Metric) {
2053 DOUT << "Current metric set to: " << FMetric << "\n";
2059 if (areJTsAllowed(TLI)) {
2060 // If our case is dense we *really* should handle it earlier!
2061 assert((FMetric > 0) && "Should handle dense range earlier!");
2063 Pivot = CR.Range.first + Size/2;
2066 CaseRange LHSR(CR.Range.first, Pivot);
2067 CaseRange RHSR(Pivot, CR.Range.second);
2068 Constant *C = Pivot->Low;
2069 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2071 // We know that we branch to the LHS if the Value being switched on is
2072 // less than the Pivot value, C. We use this to optimize our binary
2073 // tree a bit, by recognizing that if SV is greater than or equal to the
2074 // LHS's Case Value, and that Case Value is exactly one less than the
2075 // Pivot's Value, then we can branch directly to the LHS's Target,
2076 // rather than creating a leaf node for it.
2077 if ((LHSR.second - LHSR.first) == 1 &&
2078 LHSR.first->High == CR.GE &&
2079 cast<ConstantInt>(C)->getSExtValue() ==
2080 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2081 TrueBB = LHSR.first->BB;
2083 TrueBB = new MachineBasicBlock(LLVMBB);
2084 CurMF->getBasicBlockList().insert(BBI, TrueBB);
2085 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2088 // Similar to the optimization above, if the Value being switched on is
2089 // known to be less than the Constant CR.LT, and the current Case Value
2090 // is CR.LT - 1, then we can branch directly to the target block for
2091 // the current Case Value, rather than emitting a RHS leaf node for it.
2092 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2093 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2094 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2095 FalseBB = RHSR.first->BB;
2097 FalseBB = new MachineBasicBlock(LLVMBB);
2098 CurMF->getBasicBlockList().insert(BBI, FalseBB);
2099 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2102 // Create a CaseBlock record representing a conditional branch to
2103 // the LHS node if the value being switched on SV is less than C.
2104 // Otherwise, branch to LHS.
2105 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2106 TrueBB, FalseBB, CR.CaseBB);
2108 if (CR.CaseBB == CurMBB)
2109 visitSwitchCase(CB);
2111 SwitchCases.push_back(CB);
2116 /// handleBitTestsSwitchCase - if current case range has few destination and
2117 /// range span less, than machine word bitwidth, encode case range into series
2118 /// of masks and emit bit tests with these masks.
2119 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2120 CaseRecVector& WorkList,
2122 MachineBasicBlock* Default){
2123 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
2125 Case& FrontCase = *CR.Range.first;
2126 Case& BackCase = *(CR.Range.second-1);
2128 // Get the MachineFunction which holds the current MBB. This is used when
2129 // inserting any additional MBBs necessary to represent the switch.
2130 MachineFunction *CurMF = CurMBB->getParent();
2132 unsigned numCmps = 0;
2133 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2135 // Single case counts one, case range - two.
2136 if (I->Low == I->High)
2142 // Count unique destinations
2143 SmallSet<MachineBasicBlock*, 4> Dests;
2144 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2145 Dests.insert(I->BB);
2146 if (Dests.size() > 3)
2147 // Don't bother the code below, if there are too much unique destinations
2150 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2151 << "Total number of comparisons: " << numCmps << "\n";
2153 // Compute span of values.
2154 Constant* minValue = FrontCase.Low;
2155 Constant* maxValue = BackCase.High;
2156 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2157 cast<ConstantInt>(minValue)->getSExtValue();
2158 DOUT << "Compare range: " << range << "\n"
2159 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2160 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2162 if (range>=IntPtrBits ||
2163 (!(Dests.size() == 1 && numCmps >= 3) &&
2164 !(Dests.size() == 2 && numCmps >= 5) &&
2165 !(Dests.size() >= 3 && numCmps >= 6)))
2168 DOUT << "Emitting bit tests\n";
2169 int64_t lowBound = 0;
2171 // Optimize the case where all the case values fit in a
2172 // word without having to subtract minValue. In this case,
2173 // we can optimize away the subtraction.
2174 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2175 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
2176 range = cast<ConstantInt>(maxValue)->getSExtValue();
2178 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2181 CaseBitsVector CasesBits;
2182 unsigned i, count = 0;
2184 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2185 MachineBasicBlock* Dest = I->BB;
2186 for (i = 0; i < count; ++i)
2187 if (Dest == CasesBits[i].BB)
2191 assert((count < 3) && "Too much destinations to test!");
2192 CasesBits.push_back(CaseBits(0, Dest, 0));
2196 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2197 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2199 for (uint64_t j = lo; j <= hi; j++) {
2200 CasesBits[i].Mask |= 1ULL << j;
2201 CasesBits[i].Bits++;
2205 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2207 SelectionDAGISel::BitTestInfo BTC;
2209 // Figure out which block is immediately after the current one.
2210 MachineFunction::iterator BBI = CR.CaseBB;
2213 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2216 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2217 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2218 << ", BB: " << CasesBits[i].BB << "\n";
2220 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2221 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2222 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2227 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2228 -1U, (CR.CaseBB == CurMBB),
2229 CR.CaseBB, Default, BTC);
2231 if (CR.CaseBB == CurMBB)
2232 visitBitTestHeader(BTB);
2234 BitTestCases.push_back(BTB);
2240 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2241 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2242 const SwitchInst& SI) {
2243 unsigned numCmps = 0;
2245 // Start with "simple" cases
2246 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2247 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2248 Cases.push_back(Case(SI.getSuccessorValue(i),
2249 SI.getSuccessorValue(i),
2252 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2254 // Merge case into clusters
2255 if (Cases.size()>=2)
2256 // Must recompute end() each iteration because it may be
2257 // invalidated by erase if we hold on to it
2258 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2259 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2260 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2261 MachineBasicBlock* nextBB = J->BB;
2262 MachineBasicBlock* currentBB = I->BB;
2264 // If the two neighboring cases go to the same destination, merge them
2265 // into a single case.
2266 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2274 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2275 if (I->Low != I->High)
2276 // A range counts double, since it requires two compares.
2283 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2284 // Figure out which block is immediately after the current one.
2285 MachineBasicBlock *NextBlock = 0;
2286 MachineFunction::iterator BBI = CurMBB;
2288 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2290 // If there is only the default destination, branch to it if it is not the
2291 // next basic block. Otherwise, just fall through.
2292 if (SI.getNumOperands() == 2) {
2293 // Update machine-CFG edges.
2295 // If this is not a fall-through branch, emit the branch.
2296 CurMBB->addSuccessor(Default);
2297 if (Default != NextBlock)
2298 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2299 DAG.getBasicBlock(Default)));
2304 // If there are any non-default case statements, create a vector of Cases
2305 // representing each one, and sort the vector so that we can efficiently
2306 // create a binary search tree from them.
2308 unsigned numCmps = Clusterify(Cases, SI);
2309 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2310 << ". Total compares: " << numCmps << "\n";
2312 // Get the Value to be switched on and default basic blocks, which will be
2313 // inserted into CaseBlock records, representing basic blocks in the binary
2315 Value *SV = SI.getOperand(0);
2317 // Push the initial CaseRec onto the worklist
2318 CaseRecVector WorkList;
2319 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2321 while (!WorkList.empty()) {
2322 // Grab a record representing a case range to process off the worklist
2323 CaseRec CR = WorkList.back();
2324 WorkList.pop_back();
2326 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2329 // If the range has few cases (two or less) emit a series of specific
2331 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2334 // If the switch has more than 5 blocks, and at least 40% dense, and the
2335 // target supports indirect branches, then emit a jump table rather than
2336 // lowering the switch to a binary tree of conditional branches.
2337 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2340 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2341 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2342 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2347 void SelectionDAGLowering::visitSub(User &I) {
2348 // -0.0 - X --> fneg
2349 const Type *Ty = I.getType();
2350 if (isa<VectorType>(Ty)) {
2351 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2352 const VectorType *DestTy = cast<VectorType>(I.getType());
2353 const Type *ElTy = DestTy->getElementType();
2354 if (ElTy->isFloatingPoint()) {
2355 unsigned VL = DestTy->getNumElements();
2356 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2357 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2359 SDOperand Op2 = getValue(I.getOperand(1));
2360 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2366 if (Ty->isFloatingPoint()) {
2367 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2368 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2369 SDOperand Op2 = getValue(I.getOperand(1));
2370 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2375 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2378 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2379 SDOperand Op1 = getValue(I.getOperand(0));
2380 SDOperand Op2 = getValue(I.getOperand(1));
2382 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2385 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2386 SDOperand Op1 = getValue(I.getOperand(0));
2387 SDOperand Op2 = getValue(I.getOperand(1));
2389 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2390 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2391 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2392 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2394 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2397 void SelectionDAGLowering::visitICmp(User &I) {
2398 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2399 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2400 predicate = IC->getPredicate();
2401 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2402 predicate = ICmpInst::Predicate(IC->getPredicate());
2403 SDOperand Op1 = getValue(I.getOperand(0));
2404 SDOperand Op2 = getValue(I.getOperand(1));
2405 ISD::CondCode Opcode;
2406 switch (predicate) {
2407 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2408 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2409 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2410 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2411 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2412 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2413 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2414 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2415 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2416 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2418 assert(!"Invalid ICmp predicate value");
2419 Opcode = ISD::SETEQ;
2422 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2425 void SelectionDAGLowering::visitFCmp(User &I) {
2426 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2427 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2428 predicate = FC->getPredicate();
2429 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2430 predicate = FCmpInst::Predicate(FC->getPredicate());
2431 SDOperand Op1 = getValue(I.getOperand(0));
2432 SDOperand Op2 = getValue(I.getOperand(1));
2433 ISD::CondCode Condition, FOC, FPC;
2434 switch (predicate) {
2435 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2436 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2437 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2438 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2439 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2440 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2441 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2442 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2443 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2444 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2445 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2446 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2447 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2448 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2449 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2450 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2452 assert(!"Invalid FCmp predicate value");
2453 FOC = FPC = ISD::SETFALSE;
2456 if (FiniteOnlyFPMath())
2460 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2463 void SelectionDAGLowering::visitVICmp(User &I) {
2464 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2465 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2466 predicate = IC->getPredicate();
2467 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2468 predicate = ICmpInst::Predicate(IC->getPredicate());
2469 SDOperand Op1 = getValue(I.getOperand(0));
2470 SDOperand Op2 = getValue(I.getOperand(1));
2471 ISD::CondCode Opcode;
2472 switch (predicate) {
2473 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2474 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2475 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2476 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2477 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2478 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2479 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2480 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2481 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2482 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2484 assert(!"Invalid ICmp predicate value");
2485 Opcode = ISD::SETEQ;
2488 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2491 void SelectionDAGLowering::visitVFCmp(User &I) {
2492 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2493 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2494 predicate = FC->getPredicate();
2495 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2496 predicate = FCmpInst::Predicate(FC->getPredicate());
2497 SDOperand Op1 = getValue(I.getOperand(0));
2498 SDOperand Op2 = getValue(I.getOperand(1));
2499 ISD::CondCode Condition, FOC, FPC;
2500 switch (predicate) {
2501 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2502 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2503 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2504 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2505 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2506 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2507 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2508 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2509 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2510 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2511 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2512 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2513 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2514 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2515 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2516 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2518 assert(!"Invalid VFCmp predicate value");
2519 FOC = FPC = ISD::SETFALSE;
2522 if (FiniteOnlyFPMath())
2527 MVT DestVT = TLI.getValueType(I.getType());
2529 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2532 void SelectionDAGLowering::visitSelect(User &I) {
2533 SDOperand Cond = getValue(I.getOperand(0));
2534 SDOperand TrueVal = getValue(I.getOperand(1));
2535 SDOperand FalseVal = getValue(I.getOperand(2));
2536 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2537 TrueVal, FalseVal));
2541 void SelectionDAGLowering::visitTrunc(User &I) {
2542 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2543 SDOperand N = getValue(I.getOperand(0));
2544 MVT DestVT = TLI.getValueType(I.getType());
2545 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2548 void SelectionDAGLowering::visitZExt(User &I) {
2549 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2550 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2551 SDOperand N = getValue(I.getOperand(0));
2552 MVT DestVT = TLI.getValueType(I.getType());
2553 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2556 void SelectionDAGLowering::visitSExt(User &I) {
2557 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2558 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2559 SDOperand N = getValue(I.getOperand(0));
2560 MVT DestVT = TLI.getValueType(I.getType());
2561 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2564 void SelectionDAGLowering::visitFPTrunc(User &I) {
2565 // FPTrunc is never a no-op cast, no need to check
2566 SDOperand N = getValue(I.getOperand(0));
2567 MVT DestVT = TLI.getValueType(I.getType());
2568 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2571 void SelectionDAGLowering::visitFPExt(User &I){
2572 // FPTrunc is never a no-op cast, no need to check
2573 SDOperand N = getValue(I.getOperand(0));
2574 MVT DestVT = TLI.getValueType(I.getType());
2575 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2578 void SelectionDAGLowering::visitFPToUI(User &I) {
2579 // FPToUI is never a no-op cast, no need to check
2580 SDOperand N = getValue(I.getOperand(0));
2581 MVT DestVT = TLI.getValueType(I.getType());
2582 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2585 void SelectionDAGLowering::visitFPToSI(User &I) {
2586 // FPToSI is never a no-op cast, no need to check
2587 SDOperand N = getValue(I.getOperand(0));
2588 MVT DestVT = TLI.getValueType(I.getType());
2589 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2592 void SelectionDAGLowering::visitUIToFP(User &I) {
2593 // UIToFP is never a no-op cast, no need to check
2594 SDOperand N = getValue(I.getOperand(0));
2595 MVT DestVT = TLI.getValueType(I.getType());
2596 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2599 void SelectionDAGLowering::visitSIToFP(User &I){
2600 // UIToFP is never a no-op cast, no need to check
2601 SDOperand N = getValue(I.getOperand(0));
2602 MVT DestVT = TLI.getValueType(I.getType());
2603 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2606 void SelectionDAGLowering::visitPtrToInt(User &I) {
2607 // What to do depends on the size of the integer and the size of the pointer.
2608 // We can either truncate, zero extend, or no-op, accordingly.
2609 SDOperand N = getValue(I.getOperand(0));
2610 MVT SrcVT = N.getValueType();
2611 MVT DestVT = TLI.getValueType(I.getType());
2613 if (DestVT.bitsLT(SrcVT))
2614 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2616 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2617 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2618 setValue(&I, Result);
2621 void SelectionDAGLowering::visitIntToPtr(User &I) {
2622 // What to do depends on the size of the integer and the size of the pointer.
2623 // We can either truncate, zero extend, or no-op, accordingly.
2624 SDOperand N = getValue(I.getOperand(0));
2625 MVT SrcVT = N.getValueType();
2626 MVT DestVT = TLI.getValueType(I.getType());
2627 if (DestVT.bitsLT(SrcVT))
2628 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2630 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2631 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2634 void SelectionDAGLowering::visitBitCast(User &I) {
2635 SDOperand N = getValue(I.getOperand(0));
2636 MVT DestVT = TLI.getValueType(I.getType());
2638 // BitCast assures us that source and destination are the same size so this
2639 // is either a BIT_CONVERT or a no-op.
2640 if (DestVT != N.getValueType())
2641 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2643 setValue(&I, N); // noop cast.
2646 void SelectionDAGLowering::visitInsertElement(User &I) {
2647 SDOperand InVec = getValue(I.getOperand(0));
2648 SDOperand InVal = getValue(I.getOperand(1));
2649 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2650 getValue(I.getOperand(2)));
2652 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2653 TLI.getValueType(I.getType()),
2654 InVec, InVal, InIdx));
2657 void SelectionDAGLowering::visitExtractElement(User &I) {
2658 SDOperand InVec = getValue(I.getOperand(0));
2659 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2660 getValue(I.getOperand(1)));
2661 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2662 TLI.getValueType(I.getType()), InVec, InIdx));
2665 void SelectionDAGLowering::visitShuffleVector(User &I) {
2666 SDOperand V1 = getValue(I.getOperand(0));
2667 SDOperand V2 = getValue(I.getOperand(1));
2668 SDOperand Mask = getValue(I.getOperand(2));
2670 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2671 TLI.getValueType(I.getType()),
2675 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2676 const Value *Op0 = I.getOperand(0);
2677 const Value *Op1 = I.getOperand(1);
2678 const Type *AggTy = I.getType();
2679 const Type *ValTy = Op1->getType();
2680 bool IntoUndef = isa<UndefValue>(Op0);
2681 bool FromUndef = isa<UndefValue>(Op1);
2683 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2684 I.idx_begin(), I.idx_end());
2686 SmallVector<MVT, 4> AggValueVTs;
2687 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2688 SmallVector<MVT, 4> ValValueVTs;
2689 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2691 unsigned NumAggValues = AggValueVTs.size();
2692 unsigned NumValValues = ValValueVTs.size();
2693 SmallVector<SDOperand, 4> Values(NumAggValues);
2695 SDOperand Agg = getValue(Op0);
2696 SDOperand Val = getValue(Op1);
2698 // Copy the beginning value(s) from the original aggregate.
2699 for (; i != LinearIndex; ++i)
2700 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2701 SDOperand(Agg.Val, Agg.ResNo + i);
2702 // Copy values from the inserted value(s).
2703 for (; i != LinearIndex + NumValValues; ++i)
2704 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2705 SDOperand(Val.Val, Val.ResNo + i - LinearIndex);
2706 // Copy remaining value(s) from the original aggregate.
2707 for (; i != NumAggValues; ++i)
2708 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2709 SDOperand(Agg.Val, Agg.ResNo + i);
2711 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2712 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2713 &Values[0], NumAggValues));
2716 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2717 const Value *Op0 = I.getOperand(0);
2718 const Type *AggTy = Op0->getType();
2719 const Type *ValTy = I.getType();
2720 bool OutOfUndef = isa<UndefValue>(Op0);
2722 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2723 I.idx_begin(), I.idx_end());
2725 SmallVector<MVT, 4> ValValueVTs;
2726 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2728 unsigned NumValValues = ValValueVTs.size();
2729 SmallVector<SDOperand, 4> Values(NumValValues);
2731 SDOperand Agg = getValue(Op0);
2732 // Copy out the selected value(s).
2733 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2734 Values[i - LinearIndex] =
2735 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(i)) :
2736 SDOperand(Agg.Val, Agg.ResNo + i - LinearIndex);
2738 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2739 DAG.getVTList(&ValValueVTs[0], NumValValues),
2740 &Values[0], NumValValues));
2744 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2745 SDOperand N = getValue(I.getOperand(0));
2746 const Type *Ty = I.getOperand(0)->getType();
2748 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2751 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2752 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2755 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2756 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2757 DAG.getIntPtrConstant(Offset));
2759 Ty = StTy->getElementType(Field);
2761 Ty = cast<SequentialType>(Ty)->getElementType();
2763 // If this is a constant subscript, handle it quickly.
2764 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2765 if (CI->getZExtValue() == 0) continue;
2767 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2768 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2769 DAG.getIntPtrConstant(Offs));
2773 // N = N + Idx * ElementSize;
2774 uint64_t ElementSize = TD->getABITypeSize(Ty);
2775 SDOperand IdxN = getValue(Idx);
2777 // If the index is smaller or larger than intptr_t, truncate or extend
2779 if (IdxN.getValueType().bitsLT(N.getValueType())) {
2780 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2781 } else if (IdxN.getValueType().bitsGT(N.getValueType()))
2782 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2784 // If this is a multiply by a power of two, turn it into a shl
2785 // immediately. This is a very common case.
2786 if (isPowerOf2_64(ElementSize)) {
2787 unsigned Amt = Log2_64(ElementSize);
2788 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2789 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2790 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2794 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2795 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2796 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2802 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2803 // If this is a fixed sized alloca in the entry block of the function,
2804 // allocate it statically on the stack.
2805 if (FuncInfo.StaticAllocaMap.count(&I))
2806 return; // getValue will auto-populate this.
2808 const Type *Ty = I.getAllocatedType();
2809 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2811 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2814 SDOperand AllocSize = getValue(I.getArraySize());
2815 MVT IntPtr = TLI.getPointerTy();
2816 if (IntPtr.bitsLT(AllocSize.getValueType()))
2817 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2818 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2819 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2821 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2822 DAG.getIntPtrConstant(TySize));
2824 // Handle alignment. If the requested alignment is less than or equal to
2825 // the stack alignment, ignore it. If the size is greater than or equal to
2826 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2827 unsigned StackAlign =
2828 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2829 if (Align <= StackAlign)
2832 // Round the size of the allocation up to the stack alignment size
2833 // by add SA-1 to the size.
2834 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2835 DAG.getIntPtrConstant(StackAlign-1));
2836 // Mask out the low bits for alignment purposes.
2837 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2838 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2840 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2841 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2843 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2845 DAG.setRoot(DSA.getValue(1));
2847 // Inform the Frame Information that we have just allocated a variable-sized
2849 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2852 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2853 const Value *SV = I.getOperand(0);
2854 SDOperand Ptr = getValue(SV);
2856 const Type *Ty = I.getType();
2857 bool isVolatile = I.isVolatile();
2858 unsigned Alignment = I.getAlignment();
2860 SmallVector<MVT, 4> ValueVTs;
2861 SmallVector<uint64_t, 4> Offsets;
2862 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2863 unsigned NumValues = ValueVTs.size();
2871 // Do not serialize non-volatile loads against each other.
2872 Root = DAG.getRoot();
2875 SmallVector<SDOperand, 4> Values(NumValues);
2876 SmallVector<SDOperand, 4> Chains(NumValues);
2877 MVT PtrVT = Ptr.getValueType();
2878 for (unsigned i = 0; i != NumValues; ++i) {
2879 SDOperand L = DAG.getLoad(ValueVTs[i], Root,
2880 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2881 DAG.getConstant(Offsets[i], PtrVT)),
2883 isVolatile, Alignment);
2885 Chains[i] = L.getValue(1);
2888 SDOperand Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2889 &Chains[0], NumValues);
2893 PendingLoads.push_back(Chain);
2895 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2896 DAG.getVTList(&ValueVTs[0], NumValues),
2897 &Values[0], NumValues));
2901 void SelectionDAGLowering::visitStore(StoreInst &I) {
2902 Value *SrcV = I.getOperand(0);
2903 SDOperand Src = getValue(SrcV);
2904 Value *PtrV = I.getOperand(1);
2905 SDOperand Ptr = getValue(PtrV);
2907 SmallVector<MVT, 4> ValueVTs;
2908 SmallVector<uint64_t, 4> Offsets;
2909 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2910 unsigned NumValues = ValueVTs.size();
2914 SDOperand Root = getRoot();
2915 SmallVector<SDOperand, 4> Chains(NumValues);
2916 MVT PtrVT = Ptr.getValueType();
2917 bool isVolatile = I.isVolatile();
2918 unsigned Alignment = I.getAlignment();
2919 for (unsigned i = 0; i != NumValues; ++i)
2920 Chains[i] = DAG.getStore(Root, SDOperand(Src.Val, Src.ResNo + i),
2921 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2922 DAG.getConstant(Offsets[i], PtrVT)),
2924 isVolatile, Alignment);
2926 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2929 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2931 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2932 unsigned Intrinsic) {
2933 bool HasChain = !I.doesNotAccessMemory();
2934 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2936 // Build the operand list.
2937 SmallVector<SDOperand, 8> Ops;
2938 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2940 // We don't need to serialize loads against other loads.
2941 Ops.push_back(DAG.getRoot());
2943 Ops.push_back(getRoot());
2947 // Add the intrinsic ID as an integer operand.
2948 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2950 // Add all operands of the call to the operand list.
2951 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2952 SDOperand Op = getValue(I.getOperand(i));
2953 assert(TLI.isTypeLegal(Op.getValueType()) &&
2954 "Intrinsic uses a non-legal type?");
2958 std::vector<MVT> VTs;
2959 if (I.getType() != Type::VoidTy) {
2960 MVT VT = TLI.getValueType(I.getType());
2961 if (VT.isVector()) {
2962 const VectorType *DestTy = cast<VectorType>(I.getType());
2963 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2965 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2966 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2969 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2973 VTs.push_back(MVT::Other);
2975 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2980 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2981 &Ops[0], Ops.size());
2982 else if (I.getType() != Type::VoidTy)
2983 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2984 &Ops[0], Ops.size());
2986 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2987 &Ops[0], Ops.size());
2990 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2992 PendingLoads.push_back(Chain);
2996 if (I.getType() != Type::VoidTy) {
2997 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2998 MVT VT = TLI.getValueType(PTy);
2999 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
3001 setValue(&I, Result);
3005 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3006 static GlobalVariable *ExtractTypeInfo (Value *V) {
3007 V = V->stripPointerCasts();
3008 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3009 assert ((GV || isa<ConstantPointerNull>(V)) &&
3010 "TypeInfo must be a global variable or NULL");
3014 /// addCatchInfo - Extract the personality and type infos from an eh.selector
3015 /// call, and add them to the specified machine basic block.
3016 static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3017 MachineBasicBlock *MBB) {
3018 // Inform the MachineModuleInfo of the personality for this landing pad.
3019 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3020 assert(CE->getOpcode() == Instruction::BitCast &&
3021 isa<Function>(CE->getOperand(0)) &&
3022 "Personality should be a function");
3023 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3025 // Gather all the type infos for this landing pad and pass them along to
3026 // MachineModuleInfo.
3027 std::vector<GlobalVariable *> TyInfo;
3028 unsigned N = I.getNumOperands();
3030 for (unsigned i = N - 1; i > 2; --i) {
3031 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3032 unsigned FilterLength = CI->getZExtValue();
3033 unsigned FirstCatch = i + FilterLength + !FilterLength;
3034 assert (FirstCatch <= N && "Invalid filter length");
3036 if (FirstCatch < N) {
3037 TyInfo.reserve(N - FirstCatch);
3038 for (unsigned j = FirstCatch; j < N; ++j)
3039 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3040 MMI->addCatchTypeInfo(MBB, TyInfo);
3044 if (!FilterLength) {
3046 MMI->addCleanup(MBB);
3049 TyInfo.reserve(FilterLength - 1);
3050 for (unsigned j = i + 1; j < FirstCatch; ++j)
3051 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3052 MMI->addFilterTypeInfo(MBB, TyInfo);
3061 TyInfo.reserve(N - 3);
3062 for (unsigned j = 3; j < N; ++j)
3063 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3064 MMI->addCatchTypeInfo(MBB, TyInfo);
3069 /// Inlined utility function to implement binary input atomic intrinsics for
3070 // visitIntrinsicCall: I is a call instruction
3071 // Op is the associated NodeType for I
3073 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3074 SDOperand Root = getRoot();
3075 SDOperand O2 = getValue(I.getOperand(2));
3076 SDOperand L = DAG.getAtomic(Op, Root,
3077 getValue(I.getOperand(1)),
3078 O2, O2.getValueType());
3080 DAG.setRoot(L.getValue(1));
3084 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3085 /// we want to emit this as a call to a named external function, return the name
3086 /// otherwise lower it and return null.
3088 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3089 switch (Intrinsic) {
3091 // By default, turn this into a target intrinsic node.
3092 visitTargetIntrinsic(I, Intrinsic);
3094 case Intrinsic::vastart: visitVAStart(I); return 0;
3095 case Intrinsic::vaend: visitVAEnd(I); return 0;
3096 case Intrinsic::vacopy: visitVACopy(I); return 0;
3097 case Intrinsic::returnaddress:
3098 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3099 getValue(I.getOperand(1))));
3101 case Intrinsic::frameaddress:
3102 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3103 getValue(I.getOperand(1))));
3105 case Intrinsic::setjmp:
3106 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3108 case Intrinsic::longjmp:
3109 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3111 case Intrinsic::memcpy_i32:
3112 case Intrinsic::memcpy_i64: {
3113 SDOperand Op1 = getValue(I.getOperand(1));
3114 SDOperand Op2 = getValue(I.getOperand(2));
3115 SDOperand Op3 = getValue(I.getOperand(3));
3116 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3117 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3118 I.getOperand(1), 0, I.getOperand(2), 0));
3121 case Intrinsic::memset_i32:
3122 case Intrinsic::memset_i64: {
3123 SDOperand Op1 = getValue(I.getOperand(1));
3124 SDOperand Op2 = getValue(I.getOperand(2));
3125 SDOperand Op3 = getValue(I.getOperand(3));
3126 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3127 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3128 I.getOperand(1), 0));
3131 case Intrinsic::memmove_i32:
3132 case Intrinsic::memmove_i64: {
3133 SDOperand Op1 = getValue(I.getOperand(1));
3134 SDOperand Op2 = getValue(I.getOperand(2));
3135 SDOperand Op3 = getValue(I.getOperand(3));
3136 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3138 // If the source and destination are known to not be aliases, we can
3139 // lower memmove as memcpy.
3140 uint64_t Size = -1ULL;
3141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3142 Size = C->getValue();
3143 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3144 AliasAnalysis::NoAlias) {
3145 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3146 I.getOperand(1), 0, I.getOperand(2), 0));
3150 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3151 I.getOperand(1), 0, I.getOperand(2), 0));
3154 case Intrinsic::dbg_stoppoint: {
3155 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3156 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3157 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3161 Ops[1] = getValue(SPI.getLineValue());
3162 Ops[2] = getValue(SPI.getColumnValue());
3164 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3165 assert(DD && "Not a debug information descriptor");
3166 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
3168 Ops[3] = DAG.getString(CompileUnit->getFileName());
3169 Ops[4] = DAG.getString(CompileUnit->getDirectory());
3171 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
3176 case Intrinsic::dbg_region_start: {
3177 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3178 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3179 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3180 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3181 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3182 DAG.getConstant(LabelID, MVT::i32),
3183 DAG.getConstant(0, MVT::i32)));
3188 case Intrinsic::dbg_region_end: {
3189 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3190 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3191 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3192 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3193 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3194 DAG.getConstant(LabelID, MVT::i32),
3195 DAG.getConstant(0, MVT::i32)));
3200 case Intrinsic::dbg_func_start: {
3201 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3203 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3204 Value *SP = FSI.getSubprogram();
3205 if (SP && MMI->Verify(SP)) {
3206 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3207 // what (most?) gdb expects.
3208 DebugInfoDesc *DD = MMI->getDescFor(SP);
3209 assert(DD && "Not a debug information descriptor");
3210 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3211 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3212 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
3213 CompileUnit->getFileName());
3214 // Record the source line but does create a label. It will be emitted
3215 // at asm emission time.
3216 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3221 case Intrinsic::dbg_declare: {
3222 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3223 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3224 Value *Variable = DI.getVariable();
3225 if (MMI && Variable && MMI->Verify(Variable))
3226 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3227 getValue(DI.getAddress()), getValue(Variable)));
3231 case Intrinsic::eh_exception: {
3232 if (!CurMBB->isLandingPad()) {
3233 // FIXME: Mark exception register as live in. Hack for PR1508.
3234 unsigned Reg = TLI.getExceptionAddressRegister();
3235 if (Reg) CurMBB->addLiveIn(Reg);
3237 // Insert the EXCEPTIONADDR instruction.
3238 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3240 Ops[0] = DAG.getRoot();
3241 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3243 DAG.setRoot(Op.getValue(1));
3247 case Intrinsic::eh_selector_i32:
3248 case Intrinsic::eh_selector_i64: {
3249 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3250 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3251 MVT::i32 : MVT::i64);
3254 if (CurMBB->isLandingPad())
3255 addCatchInfo(I, MMI, CurMBB);
3258 FuncInfo.CatchInfoLost.insert(&I);
3260 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3261 unsigned Reg = TLI.getExceptionSelectorRegister();
3262 if (Reg) CurMBB->addLiveIn(Reg);
3265 // Insert the EHSELECTION instruction.
3266 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3268 Ops[0] = getValue(I.getOperand(1));
3270 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3272 DAG.setRoot(Op.getValue(1));
3274 setValue(&I, DAG.getConstant(0, VT));
3280 case Intrinsic::eh_typeid_for_i32:
3281 case Intrinsic::eh_typeid_for_i64: {
3282 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3283 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3284 MVT::i32 : MVT::i64);
3287 // Find the type id for the given typeinfo.
3288 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3290 unsigned TypeID = MMI->getTypeIDFor(GV);
3291 setValue(&I, DAG.getConstant(TypeID, VT));
3293 // Return something different to eh_selector.
3294 setValue(&I, DAG.getConstant(1, VT));
3300 case Intrinsic::eh_return: {
3301 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3304 MMI->setCallsEHReturn(true);
3305 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3308 getValue(I.getOperand(1)),
3309 getValue(I.getOperand(2))));
3311 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3317 case Intrinsic::eh_unwind_init: {
3318 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3319 MMI->setCallsUnwindInit(true);
3325 case Intrinsic::eh_dwarf_cfa: {
3326 MVT VT = getValue(I.getOperand(1)).getValueType();
3328 if (VT.bitsGT(TLI.getPointerTy()))
3329 CfaArg = DAG.getNode(ISD::TRUNCATE,
3330 TLI.getPointerTy(), getValue(I.getOperand(1)));
3332 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3333 TLI.getPointerTy(), getValue(I.getOperand(1)));
3335 SDOperand Offset = DAG.getNode(ISD::ADD,
3337 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3338 TLI.getPointerTy()),
3340 setValue(&I, DAG.getNode(ISD::ADD,
3342 DAG.getNode(ISD::FRAMEADDR,
3345 TLI.getPointerTy())),
3350 case Intrinsic::sqrt:
3351 setValue(&I, DAG.getNode(ISD::FSQRT,
3352 getValue(I.getOperand(1)).getValueType(),
3353 getValue(I.getOperand(1))));
3355 case Intrinsic::powi:
3356 setValue(&I, DAG.getNode(ISD::FPOWI,
3357 getValue(I.getOperand(1)).getValueType(),
3358 getValue(I.getOperand(1)),
3359 getValue(I.getOperand(2))));
3361 case Intrinsic::sin:
3362 setValue(&I, DAG.getNode(ISD::FSIN,
3363 getValue(I.getOperand(1)).getValueType(),
3364 getValue(I.getOperand(1))));
3366 case Intrinsic::cos:
3367 setValue(&I, DAG.getNode(ISD::FCOS,
3368 getValue(I.getOperand(1)).getValueType(),
3369 getValue(I.getOperand(1))));
3371 case Intrinsic::pow:
3372 setValue(&I, DAG.getNode(ISD::FPOW,
3373 getValue(I.getOperand(1)).getValueType(),
3374 getValue(I.getOperand(1)),
3375 getValue(I.getOperand(2))));
3377 case Intrinsic::pcmarker: {
3378 SDOperand Tmp = getValue(I.getOperand(1));
3379 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3382 case Intrinsic::readcyclecounter: {
3383 SDOperand Op = getRoot();
3384 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3385 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3388 DAG.setRoot(Tmp.getValue(1));
3391 case Intrinsic::part_select: {
3392 // Currently not implemented: just abort
3393 assert(0 && "part_select intrinsic not implemented");
3396 case Intrinsic::part_set: {
3397 // Currently not implemented: just abort
3398 assert(0 && "part_set intrinsic not implemented");
3401 case Intrinsic::bswap:
3402 setValue(&I, DAG.getNode(ISD::BSWAP,
3403 getValue(I.getOperand(1)).getValueType(),
3404 getValue(I.getOperand(1))));
3406 case Intrinsic::cttz: {
3407 SDOperand Arg = getValue(I.getOperand(1));
3408 MVT Ty = Arg.getValueType();
3409 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3410 setValue(&I, result);
3413 case Intrinsic::ctlz: {
3414 SDOperand Arg = getValue(I.getOperand(1));
3415 MVT Ty = Arg.getValueType();
3416 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3417 setValue(&I, result);
3420 case Intrinsic::ctpop: {
3421 SDOperand Arg = getValue(I.getOperand(1));
3422 MVT Ty = Arg.getValueType();
3423 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3424 setValue(&I, result);
3427 case Intrinsic::stacksave: {
3428 SDOperand Op = getRoot();
3429 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3430 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3432 DAG.setRoot(Tmp.getValue(1));
3435 case Intrinsic::stackrestore: {
3436 SDOperand Tmp = getValue(I.getOperand(1));
3437 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3440 case Intrinsic::var_annotation:
3441 // Discard annotate attributes
3444 case Intrinsic::init_trampoline: {
3445 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3449 Ops[1] = getValue(I.getOperand(1));
3450 Ops[2] = getValue(I.getOperand(2));
3451 Ops[3] = getValue(I.getOperand(3));
3452 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3453 Ops[5] = DAG.getSrcValue(F);
3455 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3456 DAG.getNodeValueTypes(TLI.getPointerTy(),
3461 DAG.setRoot(Tmp.getValue(1));
3465 case Intrinsic::gcroot:
3467 Value *Alloca = I.getOperand(1);
3468 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3470 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3471 GCI->addStackRoot(FI->getIndex(), TypeMap);
3475 case Intrinsic::gcread:
3476 case Intrinsic::gcwrite:
3477 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3480 case Intrinsic::flt_rounds: {
3481 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3485 case Intrinsic::trap: {
3486 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3489 case Intrinsic::prefetch: {
3492 Ops[1] = getValue(I.getOperand(1));
3493 Ops[2] = getValue(I.getOperand(2));
3494 Ops[3] = getValue(I.getOperand(3));
3495 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3499 case Intrinsic::memory_barrier: {
3502 for (int x = 1; x < 6; ++x)
3503 Ops[x] = getValue(I.getOperand(x));
3505 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3508 case Intrinsic::atomic_lcs: {
3509 SDOperand Root = getRoot();
3510 SDOperand O3 = getValue(I.getOperand(3));
3511 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3512 getValue(I.getOperand(1)),
3513 getValue(I.getOperand(2)),
3514 O3, O3.getValueType());
3516 DAG.setRoot(L.getValue(1));
3519 case Intrinsic::atomic_las:
3520 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3521 case Intrinsic::atomic_lss:
3522 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3523 case Intrinsic::atomic_load_and:
3524 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3525 case Intrinsic::atomic_load_or:
3526 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3527 case Intrinsic::atomic_load_xor:
3528 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3529 case Intrinsic::atomic_load_min:
3530 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3531 case Intrinsic::atomic_load_max:
3532 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3533 case Intrinsic::atomic_load_umin:
3534 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3535 case Intrinsic::atomic_load_umax:
3536 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3537 case Intrinsic::atomic_swap:
3538 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
3543 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3545 MachineBasicBlock *LandingPad) {
3546 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3547 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3548 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3549 unsigned BeginLabel = 0, EndLabel = 0;
3551 TargetLowering::ArgListTy Args;
3552 TargetLowering::ArgListEntry Entry;
3553 Args.reserve(CS.arg_size());
3554 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3556 SDOperand ArgNode = getValue(*i);
3557 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3559 unsigned attrInd = i - CS.arg_begin() + 1;
3560 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3561 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3562 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3563 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3564 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3565 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3566 Entry.Alignment = CS.getParamAlignment(attrInd);
3567 Args.push_back(Entry);
3570 if (LandingPad && MMI) {
3571 // Insert a label before the invoke call to mark the try range. This can be
3572 // used to detect deletion of the invoke via the MachineModuleInfo.
3573 BeginLabel = MMI->NextLabelID();
3574 // Both PendingLoads and PendingExports must be flushed here;
3575 // this call might not return.
3577 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
3578 DAG.getConstant(BeginLabel, MVT::i32),
3579 DAG.getConstant(1, MVT::i32)));
3582 std::pair<SDOperand,SDOperand> Result =
3583 TLI.LowerCallTo(getRoot(), CS.getType(),
3584 CS.paramHasAttr(0, ParamAttr::SExt),
3585 CS.paramHasAttr(0, ParamAttr::ZExt),
3586 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3588 if (CS.getType() != Type::VoidTy)
3589 setValue(CS.getInstruction(), Result.first);
3590 DAG.setRoot(Result.second);
3592 if (LandingPad && MMI) {
3593 // Insert a label at the end of the invoke call to mark the try range. This
3594 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3595 EndLabel = MMI->NextLabelID();
3596 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3597 DAG.getConstant(EndLabel, MVT::i32),
3598 DAG.getConstant(1, MVT::i32)));
3600 // Inform MachineModuleInfo of range.
3601 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3606 void SelectionDAGLowering::visitCall(CallInst &I) {
3607 const char *RenameFn = 0;
3608 if (Function *F = I.getCalledFunction()) {
3609 if (F->isDeclaration()) {
3610 if (unsigned IID = F->getIntrinsicID()) {
3611 RenameFn = visitIntrinsicCall(I, IID);
3617 // Check for well-known libc/libm calls. If the function is internal, it
3618 // can't be a library call.
3619 unsigned NameLen = F->getNameLen();
3620 if (!F->hasInternalLinkage() && NameLen) {
3621 const char *NameStr = F->getNameStart();
3622 if (NameStr[0] == 'c' &&
3623 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3624 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3625 if (I.getNumOperands() == 3 && // Basic sanity checks.
3626 I.getOperand(1)->getType()->isFloatingPoint() &&
3627 I.getType() == I.getOperand(1)->getType() &&
3628 I.getType() == I.getOperand(2)->getType()) {
3629 SDOperand LHS = getValue(I.getOperand(1));
3630 SDOperand RHS = getValue(I.getOperand(2));
3631 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3635 } else if (NameStr[0] == 'f' &&
3636 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3637 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3638 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3639 if (I.getNumOperands() == 2 && // Basic sanity checks.
3640 I.getOperand(1)->getType()->isFloatingPoint() &&
3641 I.getType() == I.getOperand(1)->getType()) {
3642 SDOperand Tmp = getValue(I.getOperand(1));
3643 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3646 } else if (NameStr[0] == 's' &&
3647 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3648 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3649 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3650 if (I.getNumOperands() == 2 && // Basic sanity checks.
3651 I.getOperand(1)->getType()->isFloatingPoint() &&
3652 I.getType() == I.getOperand(1)->getType()) {
3653 SDOperand Tmp = getValue(I.getOperand(1));
3654 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3657 } else if (NameStr[0] == 'c' &&
3658 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3659 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3660 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3661 if (I.getNumOperands() == 2 && // Basic sanity checks.
3662 I.getOperand(1)->getType()->isFloatingPoint() &&
3663 I.getType() == I.getOperand(1)->getType()) {
3664 SDOperand Tmp = getValue(I.getOperand(1));
3665 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3670 } else if (isa<InlineAsm>(I.getOperand(0))) {
3677 Callee = getValue(I.getOperand(0));
3679 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3681 LowerCallTo(&I, Callee, I.isTailCall());
3685 void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3686 if (isa<UndefValue>(I.getOperand(0))) {
3687 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3688 setValue(&I, Undef);
3692 // To add support for individual return values with aggregate types,
3693 // we'd need a way to take a getresult index and determine which
3694 // values of the Call SDNode are associated with it.
3695 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3696 "Individual return values must not be aggregates!");
3698 SDOperand Call = getValue(I.getOperand(0));
3699 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3703 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3704 /// this value and returns the result as a ValueVT value. This uses
3705 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3706 /// If the Flag pointer is NULL, no flag is used.
3707 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3709 SDOperand *Flag) const {
3710 // Assemble the legal parts into the final values.
3711 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3712 SmallVector<SDOperand, 8> Parts;
3713 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3714 // Copy the legal parts from the registers.
3715 MVT ValueVT = ValueVTs[Value];
3716 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3717 MVT RegisterVT = RegVTs[Value];
3719 Parts.resize(NumRegs);
3720 for (unsigned i = 0; i != NumRegs; ++i) {
3723 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3725 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3726 *Flag = P.getValue(2);
3728 Chain = P.getValue(1);
3732 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3737 if (ValueVTs.size() == 1)
3740 return DAG.getNode(ISD::MERGE_VALUES,
3741 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3742 &Values[0], ValueVTs.size());
3745 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3746 /// specified value into the registers specified by this object. This uses
3747 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3748 /// If the Flag pointer is NULL, no flag is used.
3749 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3750 SDOperand &Chain, SDOperand *Flag) const {
3751 // Get the list of the values's legal parts.
3752 unsigned NumRegs = Regs.size();
3753 SmallVector<SDOperand, 8> Parts(NumRegs);
3754 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3755 MVT ValueVT = ValueVTs[Value];
3756 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3757 MVT RegisterVT = RegVTs[Value];
3759 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3760 &Parts[Part], NumParts, RegisterVT);
3764 // Copy the parts into the registers.
3765 SmallVector<SDOperand, 8> Chains(NumRegs);
3766 for (unsigned i = 0; i != NumRegs; ++i) {
3769 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3771 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3772 *Flag = Part.getValue(1);
3774 Chains[i] = Part.getValue(0);
3777 if (NumRegs == 1 || Flag)
3778 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3779 // flagged to it. That is the CopyToReg nodes and the user are considered
3780 // a single scheduling unit. If we create a TokenFactor and return it as
3781 // chain, then the TokenFactor is both a predecessor (operand) of the
3782 // user as well as a successor (the TF operands are flagged to the user).
3783 // c1, f1 = CopyToReg
3784 // c2, f2 = CopyToReg
3785 // c3 = TokenFactor c1, c2
3788 Chain = Chains[NumRegs-1];
3790 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3793 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3794 /// operand list. This adds the code marker and includes the number of
3795 /// values added into it.
3796 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3797 std::vector<SDOperand> &Ops) const {
3798 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3799 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3800 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3801 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3802 MVT RegisterVT = RegVTs[Value];
3803 for (unsigned i = 0; i != NumRegs; ++i)
3804 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3808 /// isAllocatableRegister - If the specified register is safe to allocate,
3809 /// i.e. it isn't a stack pointer or some other special register, return the
3810 /// register class for the register. Otherwise, return null.
3811 static const TargetRegisterClass *
3812 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3813 const TargetLowering &TLI,
3814 const TargetRegisterInfo *TRI) {
3815 MVT FoundVT = MVT::Other;
3816 const TargetRegisterClass *FoundRC = 0;
3817 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3818 E = TRI->regclass_end(); RCI != E; ++RCI) {
3819 MVT ThisVT = MVT::Other;
3821 const TargetRegisterClass *RC = *RCI;
3822 // If none of the the value types for this register class are valid, we
3823 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3824 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3826 if (TLI.isTypeLegal(*I)) {
3827 // If we have already found this register in a different register class,
3828 // choose the one with the largest VT specified. For example, on
3829 // PowerPC, we favor f64 register classes over f32.
3830 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3837 if (ThisVT == MVT::Other) continue;
3839 // NOTE: This isn't ideal. In particular, this might allocate the
3840 // frame pointer in functions that need it (due to them not being taken
3841 // out of allocation, because a variable sized allocation hasn't been seen
3842 // yet). This is a slight code pessimization, but should still work.
3843 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3844 E = RC->allocation_order_end(MF); I != E; ++I)
3846 // We found a matching register class. Keep looking at others in case
3847 // we find one with larger registers that this physreg is also in.
3858 /// AsmOperandInfo - This contains information for each constraint that we are
3860 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3861 /// CallOperand - If this is the result output operand or a clobber
3862 /// this is null, otherwise it is the incoming operand to the CallInst.
3863 /// This gets modified as the asm is processed.
3864 SDOperand CallOperand;
3866 /// AssignedRegs - If this is a register or register class operand, this
3867 /// contains the set of register corresponding to the operand.
3868 RegsForValue AssignedRegs;
3870 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3871 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3874 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3875 /// busy in OutputRegs/InputRegs.
3876 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3877 std::set<unsigned> &OutputRegs,
3878 std::set<unsigned> &InputRegs,
3879 const TargetRegisterInfo &TRI) const {
3881 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3882 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3885 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3886 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3891 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3893 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3894 const TargetRegisterInfo &TRI) {
3895 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3897 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3898 for (; *Aliases; ++Aliases)
3899 Regs.insert(*Aliases);
3902 } // end anon namespace.
3905 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3906 /// specified operand. We prefer to assign virtual registers, to allow the
3907 /// register allocator handle the assignment process. However, if the asm uses
3908 /// features that we can't model on machineinstrs, we have SDISel do the
3909 /// allocation. This produces generally horrible, but correct, code.
3911 /// OpInfo describes the operand.
3912 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3913 /// or any explicitly clobbered registers.
3914 /// Input and OutputRegs are the set of already allocated physical registers.
3916 void SelectionDAGLowering::
3917 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3918 std::set<unsigned> &OutputRegs,
3919 std::set<unsigned> &InputRegs) {
3920 // Compute whether this value requires an input register, an output register,
3922 bool isOutReg = false;
3923 bool isInReg = false;
3924 switch (OpInfo.Type) {
3925 case InlineAsm::isOutput:
3928 // If this is an early-clobber output, or if there is an input
3929 // constraint that matches this, we need to reserve the input register
3930 // so no other inputs allocate to it.
3931 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3933 case InlineAsm::isInput:
3937 case InlineAsm::isClobber:
3944 MachineFunction &MF = DAG.getMachineFunction();
3945 SmallVector<unsigned, 4> Regs;
3947 // If this is a constraint for a single physreg, or a constraint for a
3948 // register class, find it.
3949 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3950 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3951 OpInfo.ConstraintVT);
3953 unsigned NumRegs = 1;
3954 if (OpInfo.ConstraintVT != MVT::Other)
3955 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3957 MVT ValueVT = OpInfo.ConstraintVT;
3960 // If this is a constraint for a specific physical register, like {r17},
3962 if (PhysReg.first) {
3963 if (OpInfo.ConstraintVT == MVT::Other)
3964 ValueVT = *PhysReg.second->vt_begin();
3966 // Get the actual register value type. This is important, because the user
3967 // may have asked for (e.g.) the AX register in i32 type. We need to
3968 // remember that AX is actually i16 to get the right extension.
3969 RegVT = *PhysReg.second->vt_begin();
3971 // This is a explicit reference to a physical register.
3972 Regs.push_back(PhysReg.first);
3974 // If this is an expanded reference, add the rest of the regs to Regs.
3976 TargetRegisterClass::iterator I = PhysReg.second->begin();
3977 for (; *I != PhysReg.first; ++I)
3978 assert(I != PhysReg.second->end() && "Didn't find reg!");
3980 // Already added the first reg.
3982 for (; NumRegs; --NumRegs, ++I) {
3983 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
3987 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3988 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3989 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3993 // Otherwise, if this was a reference to an LLVM register class, create vregs
3994 // for this reference.
3995 std::vector<unsigned> RegClassRegs;
3996 const TargetRegisterClass *RC = PhysReg.second;
3998 // If this is an early clobber or tied register, our regalloc doesn't know
3999 // how to maintain the constraint. If it isn't, go ahead and create vreg
4000 // and let the regalloc do the right thing.
4001 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4002 // If there is some other early clobber and this is an input register,
4003 // then we are forced to pre-allocate the input reg so it doesn't
4004 // conflict with the earlyclobber.
4005 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
4006 RegVT = *PhysReg.second->vt_begin();
4008 if (OpInfo.ConstraintVT == MVT::Other)
4011 // Create the appropriate number of virtual registers.
4012 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4013 for (; NumRegs; --NumRegs)
4014 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4016 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4020 // Otherwise, we can't allocate it. Let the code below figure out how to
4021 // maintain these constraints.
4022 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4025 // This is a reference to a register class that doesn't directly correspond
4026 // to an LLVM register class. Allocate NumRegs consecutive, available,
4027 // registers from the class.
4028 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4029 OpInfo.ConstraintVT);
4032 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4033 unsigned NumAllocated = 0;
4034 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4035 unsigned Reg = RegClassRegs[i];
4036 // See if this register is available.
4037 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4038 (isInReg && InputRegs.count(Reg))) { // Already used.
4039 // Make sure we find consecutive registers.
4044 // Check to see if this register is allocatable (i.e. don't give out the
4047 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4048 if (!RC) { // Couldn't allocate this register.
4049 // Reset NumAllocated to make sure we return consecutive registers.
4055 // Okay, this register is good, we can use it.
4058 // If we allocated enough consecutive registers, succeed.
4059 if (NumAllocated == NumRegs) {
4060 unsigned RegStart = (i-NumAllocated)+1;
4061 unsigned RegEnd = i+1;
4062 // Mark all of the allocated registers used.
4063 for (unsigned i = RegStart; i != RegEnd; ++i)
4064 Regs.push_back(RegClassRegs[i]);
4066 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4067 OpInfo.ConstraintVT);
4068 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4073 // Otherwise, we couldn't allocate enough registers for this.
4077 /// visitInlineAsm - Handle a call to an InlineAsm object.
4079 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4080 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4082 /// ConstraintOperands - Information about all of the constraints.
4083 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4085 SDOperand Chain = getRoot();
4088 std::set<unsigned> OutputRegs, InputRegs;
4090 // Do a prepass over the constraints, canonicalizing them, and building up the
4091 // ConstraintOperands list.
4092 std::vector<InlineAsm::ConstraintInfo>
4093 ConstraintInfos = IA->ParseConstraints();
4095 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4096 // constraint. If so, we can't let the register allocator allocate any input
4097 // registers, because it will not know to avoid the earlyclobbered output reg.
4098 bool SawEarlyClobber = false;
4100 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4101 unsigned ResNo = 0; // ResNo - The result number of the next output.
4102 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4103 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4104 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4106 MVT OpVT = MVT::Other;
4108 // Compute the value type for each operand.
4109 switch (OpInfo.Type) {
4110 case InlineAsm::isOutput:
4111 // Indirect outputs just consume an argument.
4112 if (OpInfo.isIndirect) {
4113 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4116 // The return value of the call is this value. As such, there is no
4117 // corresponding argument.
4118 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4119 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4120 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4122 assert(ResNo == 0 && "Asm only has one result!");
4123 OpVT = TLI.getValueType(CS.getType());
4127 case InlineAsm::isInput:
4128 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4130 case InlineAsm::isClobber:
4135 // If this is an input or an indirect output, process the call argument.
4136 // BasicBlocks are labels, currently appearing only in asm's.
4137 if (OpInfo.CallOperandVal) {
4138 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4139 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4141 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4142 const Type *OpTy = OpInfo.CallOperandVal->getType();
4143 // If this is an indirect operand, the operand is a pointer to the
4145 if (OpInfo.isIndirect)
4146 OpTy = cast<PointerType>(OpTy)->getElementType();
4148 // If OpTy is not a single value, it may be a struct/union that we
4149 // can tile with integers.
4150 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4151 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4159 OpTy = IntegerType::get(BitSize);
4164 OpVT = TLI.getValueType(OpTy, true);
4168 OpInfo.ConstraintVT = OpVT;
4170 // Compute the constraint code and ConstraintType to use.
4171 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4173 // Keep track of whether we see an earlyclobber.
4174 SawEarlyClobber |= OpInfo.isEarlyClobber;
4176 // If we see a clobber of a register, it is an early clobber.
4177 if (!SawEarlyClobber &&
4178 OpInfo.Type == InlineAsm::isClobber &&
4179 OpInfo.ConstraintType == TargetLowering::C_Register) {
4180 // Note that we want to ignore things that we don't trick here, like
4181 // dirflag, fpsr, flags, etc.
4182 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4183 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4184 OpInfo.ConstraintVT);
4185 if (PhysReg.first || PhysReg.second) {
4186 // This is a register we know of.
4187 SawEarlyClobber = true;
4191 // If this is a memory input, and if the operand is not indirect, do what we
4192 // need to to provide an address for the memory input.
4193 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4194 !OpInfo.isIndirect) {
4195 assert(OpInfo.Type == InlineAsm::isInput &&
4196 "Can only indirectify direct input operands!");
4198 // Memory operands really want the address of the value. If we don't have
4199 // an indirect input, put it in the constpool if we can, otherwise spill
4200 // it to a stack slot.
4202 // If the operand is a float, integer, or vector constant, spill to a
4203 // constant pool entry to get its address.
4204 Value *OpVal = OpInfo.CallOperandVal;
4205 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4206 isa<ConstantVector>(OpVal)) {
4207 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4208 TLI.getPointerTy());
4210 // Otherwise, create a stack slot and emit a store to it before the
4212 const Type *Ty = OpVal->getType();
4213 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4214 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4215 MachineFunction &MF = DAG.getMachineFunction();
4216 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4217 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4218 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4219 OpInfo.CallOperand = StackSlot;
4222 // There is no longer a Value* corresponding to this operand.
4223 OpInfo.CallOperandVal = 0;
4224 // It is now an indirect operand.
4225 OpInfo.isIndirect = true;
4228 // If this constraint is for a specific register, allocate it before
4230 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4231 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4233 ConstraintInfos.clear();
4236 // Second pass - Loop over all of the operands, assigning virtual or physregs
4237 // to registerclass operands.
4238 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4239 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4241 // C_Register operands have already been allocated, Other/Memory don't need
4243 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4244 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4247 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4248 std::vector<SDOperand> AsmNodeOperands;
4249 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4250 AsmNodeOperands.push_back(
4251 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4254 // Loop over all of the inputs, copying the operand values into the
4255 // appropriate registers and processing the output regs.
4256 RegsForValue RetValRegs;
4258 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4259 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4261 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4262 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4264 switch (OpInfo.Type) {
4265 case InlineAsm::isOutput: {
4266 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4267 OpInfo.ConstraintType != TargetLowering::C_Register) {
4268 // Memory output, or 'other' output (e.g. 'X' constraint).
4269 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4271 // Add information to the INLINEASM node to know about this output.
4272 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4273 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4274 TLI.getPointerTy()));
4275 AsmNodeOperands.push_back(OpInfo.CallOperand);
4279 // Otherwise, this is a register or register class output.
4281 // Copy the output from the appropriate register. Find a register that
4283 if (OpInfo.AssignedRegs.Regs.empty()) {
4284 cerr << "Couldn't allocate output reg for contraint '"
4285 << OpInfo.ConstraintCode << "'!\n";
4289 // If this is an indirect operand, store through the pointer after the
4291 if (OpInfo.isIndirect) {
4292 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4293 OpInfo.CallOperandVal));
4295 // This is the result value of the call.
4296 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4297 // Concatenate this output onto the outputs list.
4298 RetValRegs.append(OpInfo.AssignedRegs);
4301 // Add information to the INLINEASM node to know that this register is
4303 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4307 case InlineAsm::isInput: {
4308 SDOperand InOperandVal = OpInfo.CallOperand;
4310 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4311 // If this is required to match an output register we have already set,
4312 // just use its register.
4313 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4315 // Scan until we find the definition we already emitted of this operand.
4316 // When we find it, create a RegsForValue operand.
4317 unsigned CurOp = 2; // The first operand.
4318 for (; OperandNo; --OperandNo) {
4319 // Advance to the next operand.
4321 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4322 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4323 (NumOps & 7) == 4 /*MEM*/) &&
4324 "Skipped past definitions?");
4325 CurOp += (NumOps>>3)+1;
4329 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4330 if ((NumOps & 7) == 2 /*REGDEF*/) {
4331 // Add NumOps>>3 registers to MatchedRegs.
4332 RegsForValue MatchedRegs;
4333 MatchedRegs.TLI = &TLI;
4334 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4335 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4336 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4338 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4339 MatchedRegs.Regs.push_back(Reg);
4342 // Use the produced MatchedRegs object to
4343 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4344 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4347 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4348 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4349 // Add information to the INLINEASM node to know about this input.
4350 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4351 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4352 TLI.getPointerTy()));
4353 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4358 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4359 assert(!OpInfo.isIndirect &&
4360 "Don't know how to handle indirect other inputs yet!");
4362 std::vector<SDOperand> Ops;
4363 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4366 cerr << "Invalid operand for inline asm constraint '"
4367 << OpInfo.ConstraintCode << "'!\n";
4371 // Add information to the INLINEASM node to know about this input.
4372 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4373 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4374 TLI.getPointerTy()));
4375 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4377 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4378 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4379 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4380 "Memory operands expect pointer values");
4382 // Add information to the INLINEASM node to know about this input.
4383 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4384 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4385 TLI.getPointerTy()));
4386 AsmNodeOperands.push_back(InOperandVal);
4390 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4391 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4392 "Unknown constraint type!");
4393 assert(!OpInfo.isIndirect &&
4394 "Don't know how to handle indirect register inputs yet!");
4396 // Copy the input into the appropriate registers.
4397 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4398 "Couldn't allocate input reg!");
4400 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4402 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4406 case InlineAsm::isClobber: {
4407 // Add the clobbered value to the operand list, so that the register
4408 // allocator is aware that the physreg got clobbered.
4409 if (!OpInfo.AssignedRegs.Regs.empty())
4410 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4417 // Finish up input operands.
4418 AsmNodeOperands[0] = Chain;
4419 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4421 Chain = DAG.getNode(ISD::INLINEASM,
4422 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4423 &AsmNodeOperands[0], AsmNodeOperands.size());
4424 Flag = Chain.getValue(1);
4426 // If this asm returns a register value, copy the result from that register
4427 // and set it as the value of the call.
4428 if (!RetValRegs.Regs.empty()) {
4429 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4431 // If any of the results of the inline asm is a vector, it may have the
4432 // wrong width/num elts. This can happen for register classes that can
4433 // contain multiple different value types. The preg or vreg allocated may
4434 // not have the same VT as was expected. Convert it to the right type with
4436 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4437 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4438 if (Val.Val->getValueType(i).isVector())
4439 Val = DAG.getNode(ISD::BIT_CONVERT,
4440 TLI.getValueType(ResSTy->getElementType(i)), Val);
4443 if (Val.getValueType().isVector())
4444 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4448 setValue(CS.getInstruction(), Val);
4451 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4453 // Process indirect outputs, first output all of the flagged copies out of
4455 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4456 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4457 Value *Ptr = IndirectStoresToEmit[i].second;
4458 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4459 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4462 // Emit the non-flagged stores from the physregs.
4463 SmallVector<SDOperand, 8> OutChains;
4464 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4465 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4466 getValue(StoresToEmit[i].second),
4467 StoresToEmit[i].second, 0));
4468 if (!OutChains.empty())
4469 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4470 &OutChains[0], OutChains.size());
4475 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4476 SDOperand Src = getValue(I.getOperand(0));
4478 MVT IntPtr = TLI.getPointerTy();
4480 if (IntPtr.bitsLT(Src.getValueType()))
4481 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4482 else if (IntPtr.bitsGT(Src.getValueType()))
4483 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4485 // Scale the source by the type size.
4486 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4487 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4488 Src, DAG.getIntPtrConstant(ElementSize));
4490 TargetLowering::ArgListTy Args;
4491 TargetLowering::ArgListEntry Entry;
4493 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4494 Args.push_back(Entry);
4496 std::pair<SDOperand,SDOperand> Result =
4497 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4498 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4499 setValue(&I, Result.first); // Pointers always fit in registers
4500 DAG.setRoot(Result.second);
4503 void SelectionDAGLowering::visitFree(FreeInst &I) {
4504 TargetLowering::ArgListTy Args;
4505 TargetLowering::ArgListEntry Entry;
4506 Entry.Node = getValue(I.getOperand(0));
4507 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4508 Args.push_back(Entry);
4509 MVT IntPtr = TLI.getPointerTy();
4510 std::pair<SDOperand,SDOperand> Result =
4511 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4512 CallingConv::C, true,
4513 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4514 DAG.setRoot(Result.second);
4517 // EmitInstrWithCustomInserter - This method should be implemented by targets
4518 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
4519 // instructions are special in various ways, which require special support to
4520 // insert. The specified MachineInstr is created but not inserted into any
4521 // basic blocks, and the scheduler passes ownership of it to this method.
4522 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4523 MachineBasicBlock *MBB) {
4524 cerr << "If a target marks an instruction with "
4525 << "'usesCustomDAGSchedInserter', it must implement "
4526 << "TargetLowering::EmitInstrWithCustomInserter!\n";
4531 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4532 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4533 getValue(I.getOperand(1)),
4534 DAG.getSrcValue(I.getOperand(1))));
4537 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4538 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4539 getValue(I.getOperand(0)),
4540 DAG.getSrcValue(I.getOperand(0)));
4542 DAG.setRoot(V.getValue(1));
4545 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4546 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4547 getValue(I.getOperand(1)),
4548 DAG.getSrcValue(I.getOperand(1))));
4551 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4552 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4553 getValue(I.getOperand(1)),
4554 getValue(I.getOperand(2)),
4555 DAG.getSrcValue(I.getOperand(1)),
4556 DAG.getSrcValue(I.getOperand(2))));
4559 /// TargetLowering::LowerArguments - This is the default LowerArguments
4560 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4561 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4562 /// integrated into SDISel.
4563 std::vector<SDOperand>
4564 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4565 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4566 std::vector<SDOperand> Ops;
4567 Ops.push_back(DAG.getRoot());
4568 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4569 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4571 // Add one result value for each formal argument.
4572 std::vector<MVT> RetVals;
4574 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4576 MVT VT = getValueType(I->getType());
4577 ISD::ArgFlagsTy Flags;
4578 unsigned OriginalAlignment =
4579 getTargetData()->getABITypeAlignment(I->getType());
4581 if (F.paramHasAttr(j, ParamAttr::ZExt))
4583 if (F.paramHasAttr(j, ParamAttr::SExt))
4585 if (F.paramHasAttr(j, ParamAttr::InReg))
4587 if (F.paramHasAttr(j, ParamAttr::StructRet))
4589 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4591 const PointerType *Ty = cast<PointerType>(I->getType());
4592 const Type *ElementTy = Ty->getElementType();
4593 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4594 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4595 // For ByVal, alignment should be passed from FE. BE will guess if
4596 // this info is not there but there are cases it cannot get right.
4597 if (F.getParamAlignment(j))
4598 FrameAlign = F.getParamAlignment(j);
4599 Flags.setByValAlign(FrameAlign);
4600 Flags.setByValSize(FrameSize);
4602 if (F.paramHasAttr(j, ParamAttr::Nest))
4604 Flags.setOrigAlign(OriginalAlignment);
4606 MVT RegisterVT = getRegisterType(VT);
4607 unsigned NumRegs = getNumRegisters(VT);
4608 for (unsigned i = 0; i != NumRegs; ++i) {
4609 RetVals.push_back(RegisterVT);
4610 ISD::ArgFlagsTy MyFlags = Flags;
4611 if (NumRegs > 1 && i == 0)
4613 // if it isn't first piece, alignment must be 1
4615 MyFlags.setOrigAlign(1);
4616 Ops.push_back(DAG.getArgFlags(MyFlags));
4620 RetVals.push_back(MVT::Other);
4623 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4624 DAG.getVTList(&RetVals[0], RetVals.size()),
4625 &Ops[0], Ops.size()).Val;
4627 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4628 // allows exposing the loads that may be part of the argument access to the
4629 // first DAGCombiner pass.
4630 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4632 // The number of results should match up, except that the lowered one may have
4633 // an extra flag result.
4634 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4635 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4636 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4637 && "Lowering produced unexpected number of results!");
4638 Result = TmpRes.Val;
4640 unsigned NumArgRegs = Result->getNumValues() - 1;
4641 DAG.setRoot(SDOperand(Result, NumArgRegs));
4643 // Set up the return result vector.
4647 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4649 MVT VT = getValueType(I->getType());
4650 MVT PartVT = getRegisterType(VT);
4652 unsigned NumParts = getNumRegisters(VT);
4653 SmallVector<SDOperand, 4> Parts(NumParts);
4654 for (unsigned j = 0; j != NumParts; ++j)
4655 Parts[j] = SDOperand(Result, i++);
4657 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4658 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4659 AssertOp = ISD::AssertSext;
4660 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4661 AssertOp = ISD::AssertZext;
4663 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4666 assert(i == NumArgRegs && "Argument register count mismatch!");
4671 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4672 /// implementation, which just inserts an ISD::CALL node, which is later custom
4673 /// lowered by the target to something concrete. FIXME: When all targets are
4674 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4675 std::pair<SDOperand, SDOperand>
4676 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4677 bool RetSExt, bool RetZExt, bool isVarArg,
4678 unsigned CallingConv, bool isTailCall,
4680 ArgListTy &Args, SelectionDAG &DAG) {
4681 SmallVector<SDOperand, 32> Ops;
4682 Ops.push_back(Chain); // Op#0 - Chain
4683 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4684 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4685 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4686 Ops.push_back(Callee);
4688 // Handle all of the outgoing arguments.
4689 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4690 MVT VT = getValueType(Args[i].Ty);
4691 SDOperand Op = Args[i].Node;
4692 ISD::ArgFlagsTy Flags;
4693 unsigned OriginalAlignment =
4694 getTargetData()->getABITypeAlignment(Args[i].Ty);
4700 if (Args[i].isInReg)
4704 if (Args[i].isByVal) {
4706 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4707 const Type *ElementTy = Ty->getElementType();
4708 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4709 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4710 // For ByVal, alignment should come from FE. BE will guess if this
4711 // info is not there but there are cases it cannot get right.
4712 if (Args[i].Alignment)
4713 FrameAlign = Args[i].Alignment;
4714 Flags.setByValAlign(FrameAlign);
4715 Flags.setByValSize(FrameSize);
4719 Flags.setOrigAlign(OriginalAlignment);
4721 MVT PartVT = getRegisterType(VT);
4722 unsigned NumParts = getNumRegisters(VT);
4723 SmallVector<SDOperand, 4> Parts(NumParts);
4724 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4727 ExtendKind = ISD::SIGN_EXTEND;
4728 else if (Args[i].isZExt)
4729 ExtendKind = ISD::ZERO_EXTEND;
4731 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4733 for (unsigned i = 0; i != NumParts; ++i) {
4734 // if it isn't first piece, alignment must be 1
4735 ISD::ArgFlagsTy MyFlags = Flags;
4736 if (NumParts > 1 && i == 0)
4739 MyFlags.setOrigAlign(1);
4741 Ops.push_back(Parts[i]);
4742 Ops.push_back(DAG.getArgFlags(MyFlags));
4746 // Figure out the result value types. We start by making a list of
4747 // the potentially illegal return value types.
4748 SmallVector<MVT, 4> LoweredRetTys;
4749 SmallVector<MVT, 4> RetTys;
4750 ComputeValueVTs(*this, RetTy, RetTys);
4752 // Then we translate that to a list of legal types.
4753 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4755 MVT RegisterVT = getRegisterType(VT);
4756 unsigned NumRegs = getNumRegisters(VT);
4757 for (unsigned i = 0; i != NumRegs; ++i)
4758 LoweredRetTys.push_back(RegisterVT);
4761 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4763 // Create the CALL node.
4764 SDOperand Res = DAG.getNode(ISD::CALL,
4765 DAG.getVTList(&LoweredRetTys[0],
4766 LoweredRetTys.size()),
4767 &Ops[0], Ops.size());
4768 Chain = Res.getValue(LoweredRetTys.size() - 1);
4770 // Gather up the call result into a single value.
4771 if (RetTy != Type::VoidTy) {
4772 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4775 AssertOp = ISD::AssertSext;
4777 AssertOp = ISD::AssertZext;
4779 SmallVector<SDOperand, 4> ReturnValues;
4781 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4783 MVT RegisterVT = getRegisterType(VT);
4784 unsigned NumRegs = getNumRegisters(VT);
4785 unsigned RegNoEnd = NumRegs + RegNo;
4786 SmallVector<SDOperand, 4> Results;
4787 for (; RegNo != RegNoEnd; ++RegNo)
4788 Results.push_back(Res.getValue(RegNo));
4789 SDOperand ReturnValue =
4790 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4792 ReturnValues.push_back(ReturnValue);
4794 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4795 DAG.getNode(ISD::MERGE_VALUES,
4796 DAG.getVTList(&RetTys[0], RetTys.size()),
4797 &ReturnValues[0], ReturnValues.size());
4800 return std::make_pair(Res, Chain);
4803 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4804 assert(0 && "LowerOperation not implemented for this target!");
4809 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4810 SelectionDAG &DAG) {
4811 assert(0 && "CustomPromoteOperation not implemented for this target!");
4816 //===----------------------------------------------------------------------===//
4817 // SelectionDAGISel code
4818 //===----------------------------------------------------------------------===//
4820 unsigned SelectionDAGISel::MakeReg(MVT VT) {
4821 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4824 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4825 AU.addRequired<AliasAnalysis>();
4826 AU.addRequired<CollectorModuleMetadata>();
4827 AU.setPreservesAll();
4830 bool SelectionDAGISel::runOnFunction(Function &Fn) {
4831 // Get alias analysis for load/store combining.
4832 AA = &getAnalysis<AliasAnalysis>();
4834 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4835 if (MF.getFunction()->hasCollector())
4836 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4839 RegInfo = &MF.getRegInfo();
4840 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4842 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4844 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4845 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4846 // Mark landing pad.
4847 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4849 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4850 SelectBasicBlock(I, MF, FuncInfo);
4852 // Add function live-ins to entry block live-in set.
4853 BasicBlock *EntryBB = &Fn.getEntryBlock();
4854 BB = FuncInfo.MBBMap[EntryBB];
4855 if (!RegInfo->livein_empty())
4856 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4857 E = RegInfo->livein_end(); I != E; ++I)
4858 BB->addLiveIn(I->first);
4861 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4862 "Not all catch info was assigned to a landing pad!");
4868 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4869 SDOperand Op = getValue(V);
4870 assert((Op.getOpcode() != ISD::CopyFromReg ||
4871 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4872 "Copy from a reg to the same reg!");
4873 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4875 RegsForValue RFV(TLI, Reg, V->getType());
4876 SDOperand Chain = DAG.getEntryNode();
4877 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4878 PendingExports.push_back(Chain);
4881 void SelectionDAGISel::
4882 LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4883 // If this is the entry block, emit arguments.
4884 Function &F = *LLVMBB->getParent();
4885 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4886 SDOperand OldRoot = SDL.DAG.getRoot();
4887 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4890 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4892 if (!AI->use_empty()) {
4893 SDL.setValue(AI, Args[a]);
4895 // If this argument is live outside of the entry block, insert a copy from
4896 // whereever we got it to the vreg that other BB's will reference it as.
4897 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4898 if (VMI != FuncInfo.ValueMap.end()) {
4899 SDL.CopyValueToVirtualRegister(AI, VMI->second);
4903 // Finally, if the target has anything special to do, allow it to do so.
4904 // FIXME: this should insert code into the DAG!
4905 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4908 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4909 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4910 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4911 if (isSelector(I)) {
4912 // Apply the catch info to DestBB.
4913 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4915 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4916 FLI.CatchInfoFound.insert(I);
4921 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4922 /// whether object offset >= 0.
4924 IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4925 if (!isa<FrameIndexSDNode>(Op)) return false;
4927 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4928 int FrameIdx = FrameIdxNode->getIndex();
4929 return MFI->isFixedObjectIndex(FrameIdx) &&
4930 MFI->getObjectOffset(FrameIdx) >= 0;
4933 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4934 /// possibly be overwritten when lowering the outgoing arguments in a tail
4935 /// call. Currently the implementation of this call is very conservative and
4936 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4937 /// virtual registers would be overwritten by direct lowering.
4938 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4939 MachineFrameInfo * MFI) {
4940 RegisterSDNode * OpReg = NULL;
4941 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4942 (Op.getOpcode()== ISD::CopyFromReg &&
4943 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4944 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4945 (Op.getOpcode() == ISD::LOAD &&
4946 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4947 (Op.getOpcode() == ISD::MERGE_VALUES &&
4948 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4949 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4955 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
4956 /// DAG and fixes their tailcall attribute operand.
4957 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4958 TargetLowering& TLI) {
4959 SDNode * Ret = NULL;
4960 SDOperand Terminator = DAG.getRoot();
4963 if (Terminator.getOpcode() == ISD::RET) {
4964 Ret = Terminator.Val;
4967 // Fix tail call attribute of CALL nodes.
4968 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4969 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4970 if (BI->getOpcode() == ISD::CALL) {
4971 SDOperand OpRet(Ret, 0);
4972 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4973 bool isMarkedTailCall =
4974 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4975 // If CALL node has tail call attribute set to true and the call is not
4976 // eligible (no RET or the target rejects) the attribute is fixed to
4977 // false. The TargetLowering::IsEligibleForTailCallOptimization function
4978 // must correctly identify tail call optimizable calls.
4979 if (!isMarkedTailCall) continue;
4981 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4982 // Not eligible. Mark CALL node as non tail call.
4983 SmallVector<SDOperand, 32> Ops;
4985 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4986 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4990 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4992 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4994 // Look for tail call clobbered arguments. Emit a series of
4995 // copyto/copyfrom virtual register nodes to protect them.
4996 SmallVector<SDOperand, 32> Ops;
4997 SDOperand Chain = OpCall.getOperand(0), InFlag;
4999 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5000 E = OpCall.Val->op_end(); I != E; I++, idx++) {
5002 if (idx > 4 && (idx % 2)) {
5003 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5004 getArgFlags().isByVal();
5005 MachineFunction &MF = DAG.getMachineFunction();
5006 MachineFrameInfo *MFI = MF.getFrameInfo();
5008 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
5009 MVT VT = Arg.getValueType();
5010 unsigned VReg = MF.getRegInfo().
5011 createVirtualRegister(TLI.getRegClassFor(VT));
5012 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5013 InFlag = Chain.getValue(1);
5014 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5015 Chain = Arg.getValue(1);
5016 InFlag = Arg.getValue(2);
5021 // Link in chain of CopyTo/CopyFromReg.
5023 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5029 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5030 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5031 FunctionLoweringInfo &FuncInfo) {
5032 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
5034 // Lower any arguments needed in this block if this is the entry block.
5035 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
5036 LowerArguments(LLVMBB, SDL);
5038 BB = FuncInfo.MBBMap[LLVMBB];
5039 SDL.setCurrentBasicBlock(BB);
5041 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
5043 if (MMI && BB->isLandingPad()) {
5044 // Add a label to mark the beginning of the landing pad. Deletion of the
5045 // landing pad can thus be detected via the MachineModuleInfo.
5046 unsigned LabelID = MMI->addLandingPad(BB);
5047 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
5048 DAG.getConstant(LabelID, MVT::i32),
5049 DAG.getConstant(1, MVT::i32)));
5051 // Mark exception register as live in.
5052 unsigned Reg = TLI.getExceptionAddressRegister();
5053 if (Reg) BB->addLiveIn(Reg);
5055 // Mark exception selector register as live in.
5056 Reg = TLI.getExceptionSelectorRegister();
5057 if (Reg) BB->addLiveIn(Reg);
5059 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5060 // function and list of typeids logically belong to the invoke (or, if you
5061 // like, the basic block containing the invoke), and need to be associated
5062 // with it in the dwarf exception handling tables. Currently however the
5063 // information is provided by an intrinsic (eh.selector) that can be moved
5064 // to unexpected places by the optimizers: if the unwind edge is critical,
5065 // then breaking it can result in the intrinsics being in the successor of
5066 // the landing pad, not the landing pad itself. This results in exceptions
5067 // not being caught because no typeids are associated with the invoke.
5068 // This may not be the only way things can go wrong, but it is the only way
5069 // we try to work around for the moment.
5070 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5072 if (Br && Br->isUnconditional()) { // Critical edge?
5073 BasicBlock::iterator I, E;
5074 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5079 // No catch info found - try to extract some from the successor.
5080 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
5084 // Lower all of the non-terminator instructions.
5085 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5089 // Ensure that all instructions which are used outside of their defining
5090 // blocks are available as virtual registers. Invoke is handled elsewhere.
5091 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
5092 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
5093 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
5094 if (VMI != FuncInfo.ValueMap.end())
5095 SDL.CopyValueToVirtualRegister(I, VMI->second);
5098 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5099 // ensure constants are generated when needed. Remember the virtual registers
5100 // that need to be added to the Machine PHI nodes as input. We cannot just
5101 // directly add them, because expansion might result in multiple MBB's for one
5102 // BB. As such, the start of the BB might correspond to a different MBB than
5105 TerminatorInst *TI = LLVMBB->getTerminator();
5107 // Emit constants only once even if used by multiple PHI nodes.
5108 std::map<Constant*, unsigned> ConstantsOut;
5110 // Vector bool would be better, but vector<bool> is really slow.
5111 std::vector<unsigned char> SuccsHandled;
5112 if (TI->getNumSuccessors())
5113 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5115 // Check successor nodes' PHI nodes that expect a constant to be available
5117 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5118 BasicBlock *SuccBB = TI->getSuccessor(succ);
5119 if (!isa<PHINode>(SuccBB->begin())) continue;
5120 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
5122 // If this terminator has multiple identical successors (common for
5123 // switches), only handle each succ once.
5124 unsigned SuccMBBNo = SuccMBB->getNumber();
5125 if (SuccsHandled[SuccMBBNo]) continue;
5126 SuccsHandled[SuccMBBNo] = true;
5128 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5131 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5132 // nodes and Machine PHI nodes, but the incoming operands have not been
5134 for (BasicBlock::iterator I = SuccBB->begin();
5135 (PN = dyn_cast<PHINode>(I)); ++I) {
5136 // Ignore dead phi's.
5137 if (PN->use_empty()) continue;
5140 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5142 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5143 unsigned &RegOut = ConstantsOut[C];
5145 RegOut = FuncInfo.CreateRegForValue(C);
5146 SDL.CopyValueToVirtualRegister(C, RegOut);
5150 Reg = FuncInfo.ValueMap[PHIOp];
5152 assert(isa<AllocaInst>(PHIOp) &&
5153 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5154 "Didn't codegen value into a register!??");
5155 Reg = FuncInfo.CreateRegForValue(PHIOp);
5156 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
5160 // Remember that this register needs to added to the machine PHI node as
5161 // the input for this MBB.
5162 MVT VT = TLI.getValueType(PN->getType());
5163 unsigned NumRegisters = TLI.getNumRegisters(VT);
5164 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5165 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5168 ConstantsOut.clear();
5170 // Lower the terminator after the copies are emitted.
5171 SDL.visit(*LLVMBB->getTerminator());
5173 // Copy over any CaseBlock records that may now exist due to SwitchInst
5174 // lowering, as well as any jump table information.
5175 SwitchCases.clear();
5176 SwitchCases = SDL.SwitchCases;
5178 JTCases = SDL.JTCases;
5179 BitTestCases.clear();
5180 BitTestCases = SDL.BitTestCases;
5182 // Make sure the root of the DAG is up-to-date.
5183 DAG.setRoot(SDL.getControlRoot());
5185 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5186 // with correct tailcall attribute so that the target can rely on the tailcall
5187 // attribute indicating whether the call is really eligible for tail call
5189 CheckDAGForTailCallsAndFixThem(DAG, TLI);
5192 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
5193 DOUT << "Lowered selection DAG:\n";
5196 // Run the DAG combiner in pre-legalize mode.
5197 DAG.Combine(false, *AA);
5199 DOUT << "Optimized lowered selection DAG:\n";
5202 // Second step, hack on the DAG until it only uses operations and types that
5203 // the target supports.
5204 #if 0 // Enable this some day.
5205 DAG.LegalizeTypes();
5206 // Someday even later, enable a dag combine pass here.
5210 DOUT << "Legalized selection DAG:\n";
5213 // Run the DAG combiner in post-legalize mode.
5214 DAG.Combine(true, *AA);
5216 DOUT << "Optimized legalized selection DAG:\n";
5219 if (ViewISelDAGs) DAG.viewGraph();
5221 // Third, instruction select all of the operations to machine code, adding the
5222 // code to the MachineBasicBlock.
5223 InstructionSelectBasicBlock(DAG);
5225 DOUT << "Selected machine code:\n";
5229 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5230 FunctionLoweringInfo &FuncInfo) {
5231 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5233 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5236 // First step, lower LLVM code to some DAG. This DAG may use operations and
5237 // types that are not supported by the target.
5238 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5240 // Second step, emit the lowered DAG as machine code.
5241 CodeGenAndEmitDAG(DAG);
5244 DOUT << "Total amount of phi nodes to update: "
5245 << PHINodesToUpdate.size() << "\n";
5246 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5247 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5248 << ", " << PHINodesToUpdate[i].second << ")\n";);
5250 // Next, now that we know what the last MBB the LLVM BB expanded is, update
5251 // PHI nodes in successors.
5252 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
5253 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5254 MachineInstr *PHI = PHINodesToUpdate[i].first;
5255 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5256 "This is not a machine PHI node that we are updating!");
5257 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5259 PHI->addOperand(MachineOperand::CreateMBB(BB));
5264 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5265 // Lower header first, if it wasn't already lowered
5266 if (!BitTestCases[i].Emitted) {
5267 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5269 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5270 // Set the current basic block to the mbb we wish to insert the code into
5271 BB = BitTestCases[i].Parent;
5272 HSDL.setCurrentBasicBlock(BB);
5274 HSDL.visitBitTestHeader(BitTestCases[i]);
5275 HSDAG.setRoot(HSDL.getRoot());
5276 CodeGenAndEmitDAG(HSDAG);
5279 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5280 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5282 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
5283 // Set the current basic block to the mbb we wish to insert the code into
5284 BB = BitTestCases[i].Cases[j].ThisBB;
5285 BSDL.setCurrentBasicBlock(BB);
5288 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5289 BitTestCases[i].Reg,
5290 BitTestCases[i].Cases[j]);
5292 BSDL.visitBitTestCase(BitTestCases[i].Default,
5293 BitTestCases[i].Reg,
5294 BitTestCases[i].Cases[j]);
5297 BSDAG.setRoot(BSDL.getRoot());
5298 CodeGenAndEmitDAG(BSDAG);
5302 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5303 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5304 MachineBasicBlock *PHIBB = PHI->getParent();
5305 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5306 "This is not a machine PHI node that we are updating!");
5307 // This is "default" BB. We have two jumps to it. From "header" BB and
5308 // from last "case" BB.
5309 if (PHIBB == BitTestCases[i].Default) {
5310 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5312 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5313 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5315 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5318 // One of "cases" BB.
5319 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5320 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5321 if (cBB->succ_end() !=
5322 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5323 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5325 PHI->addOperand(MachineOperand::CreateMBB(cBB));
5331 // If the JumpTable record is filled in, then we need to emit a jump table.
5332 // Updating the PHI nodes is tricky in this case, since we need to determine
5333 // whether the PHI is a successor of the range check MBB or the jump table MBB
5334 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5335 // Lower header first, if it wasn't already lowered
5336 if (!JTCases[i].first.Emitted) {
5337 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5339 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5340 // Set the current basic block to the mbb we wish to insert the code into
5341 BB = JTCases[i].first.HeaderBB;
5342 HSDL.setCurrentBasicBlock(BB);
5344 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5345 HSDAG.setRoot(HSDL.getRoot());
5346 CodeGenAndEmitDAG(HSDAG);
5349 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5351 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5352 // Set the current basic block to the mbb we wish to insert the code into
5353 BB = JTCases[i].second.MBB;
5354 JSDL.setCurrentBasicBlock(BB);
5356 JSDL.visitJumpTable(JTCases[i].second);
5357 JSDAG.setRoot(JSDL.getRoot());
5358 CodeGenAndEmitDAG(JSDAG);
5361 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5362 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5363 MachineBasicBlock *PHIBB = PHI->getParent();
5364 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5365 "This is not a machine PHI node that we are updating!");
5366 // "default" BB. We can go there only from header BB.
5367 if (PHIBB == JTCases[i].second.Default) {
5368 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5370 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5372 // JT BB. Just iterate over successors here
5373 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5374 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5376 PHI->addOperand(MachineOperand::CreateMBB(BB));
5381 // If the switch block involved a branch to one of the actual successors, we
5382 // need to update PHI nodes in that block.
5383 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5384 MachineInstr *PHI = PHINodesToUpdate[i].first;
5385 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5386 "This is not a machine PHI node that we are updating!");
5387 if (BB->isSuccessor(PHI->getParent())) {
5388 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5390 PHI->addOperand(MachineOperand::CreateMBB(BB));
5394 // If we generated any switch lowering information, build and codegen any
5395 // additional DAGs necessary.
5396 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5397 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5399 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5401 // Set the current basic block to the mbb we wish to insert the code into
5402 BB = SwitchCases[i].ThisBB;
5403 SDL.setCurrentBasicBlock(BB);
5406 SDL.visitSwitchCase(SwitchCases[i]);
5407 SDAG.setRoot(SDL.getRoot());
5408 CodeGenAndEmitDAG(SDAG);
5410 // Handle any PHI nodes in successors of this chunk, as if we were coming
5411 // from the original BB before switch expansion. Note that PHI nodes can
5412 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5413 // handle them the right number of times.
5414 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
5415 for (MachineBasicBlock::iterator Phi = BB->begin();
5416 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5417 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5418 for (unsigned pn = 0; ; ++pn) {
5419 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5420 if (PHINodesToUpdate[pn].first == Phi) {
5421 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5423 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5429 // Don't process RHS if same block as LHS.
5430 if (BB == SwitchCases[i].FalseBB)
5431 SwitchCases[i].FalseBB = 0;
5433 // If we haven't handled the RHS, do so now. Otherwise, we're done.
5434 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5435 SwitchCases[i].FalseBB = 0;
5437 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5442 //===----------------------------------------------------------------------===//
5443 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5444 /// target node in the graph.
5445 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5446 if (ViewSchedDAGs) DAG.viewGraph();
5448 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5452 RegisterScheduler::setDefault(Ctor);
5455 ScheduleDAG *SL = Ctor(this, &DAG, BB);
5458 if (ViewSUnitDAGs) SL->viewGraph();
5464 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5465 return new HazardRecognizer();
5468 //===----------------------------------------------------------------------===//
5469 // Helper functions used by the generated instruction selector.
5470 //===----------------------------------------------------------------------===//
5471 // Calls to these methods are generated by tblgen.
5473 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
5474 /// the dag combiner simplified the 255, we still want to match. RHS is the
5475 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5476 /// specified in the .td file (e.g. 255).
5477 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5478 int64_t DesiredMaskS) const {
5479 const APInt &ActualMask = RHS->getAPIntValue();
5480 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5482 // If the actual mask exactly matches, success!
5483 if (ActualMask == DesiredMask)
5486 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5487 if (ActualMask.intersects(~DesiredMask))
5490 // Otherwise, the DAG Combiner may have proven that the value coming in is
5491 // either already zero or is not demanded. Check for known zero input bits.
5492 APInt NeededMask = DesiredMask & ~ActualMask;
5493 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5496 // TODO: check to see if missing bits are just not demanded.
5498 // Otherwise, this pattern doesn't match.
5502 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
5503 /// the dag combiner simplified the 255, we still want to match. RHS is the
5504 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5505 /// specified in the .td file (e.g. 255).
5506 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5507 int64_t DesiredMaskS) const {
5508 const APInt &ActualMask = RHS->getAPIntValue();
5509 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5511 // If the actual mask exactly matches, success!
5512 if (ActualMask == DesiredMask)
5515 // If the actual AND mask is allowing unallowed bits, this doesn't match.
5516 if (ActualMask.intersects(~DesiredMask))
5519 // Otherwise, the DAG Combiner may have proven that the value coming in is
5520 // either already zero or is not demanded. Check for known zero input bits.
5521 APInt NeededMask = DesiredMask & ~ActualMask;
5523 APInt KnownZero, KnownOne;
5524 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5526 // If all the missing bits in the or are already known to be set, match!
5527 if ((NeededMask & KnownOne) == NeededMask)
5530 // TODO: check to see if missing bits are just not demanded.
5532 // Otherwise, this pattern doesn't match.
5537 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5538 /// by tblgen. Others should not call it.
5539 void SelectionDAGISel::
5540 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5541 std::vector<SDOperand> InOps;
5542 std::swap(InOps, Ops);
5544 Ops.push_back(InOps[0]); // input chain.
5545 Ops.push_back(InOps[1]); // input asm string.
5547 unsigned i = 2, e = InOps.size();
5548 if (InOps[e-1].getValueType() == MVT::Flag)
5549 --e; // Don't process a flag operand if it is here.
5552 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5553 if ((Flags & 7) != 4 /*MEM*/) {
5554 // Just skip over this operand, copying the operands verbatim.
5555 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5556 i += (Flags >> 3) + 1;
5558 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5559 // Otherwise, this is a memory operand. Ask the target to select it.
5560 std::vector<SDOperand> SelOps;
5561 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5562 cerr << "Could not match memory address. Inline asm failure!\n";
5566 // Add this to the output node.
5567 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5568 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5570 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5575 // Add the flag input back if present.
5576 if (e != InOps.size())
5577 Ops.push_back(InOps.back());
5580 char SelectionDAGISel::ID = 0;