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 "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuild.h"
17 #include "llvm/CodeGen/SelectionDAGISel.h"
18 #include "llvm/Analysis/AliasAnalysis.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/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
38 #include "llvm/CodeGen/SchedulerRegistry.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/DwarfWriter.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetFrameInfo.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/Timer.h"
57 DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
59 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
60 cl::desc("Enable verbose messages in the \"fast\" "
61 "instruction selector"));
63 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
64 cl::desc("Enable abort calls when \"fast\" instruction fails"));
66 SchedLiveInCopies("schedule-livein-copies",
67 cl::desc("Schedule copies of livein registers"),
72 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
73 cl::desc("Pop up a window to show dags before the first "
76 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before legalize types"));
79 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
80 cl::desc("Pop up a window to show dags before legalize"));
82 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
83 cl::desc("Pop up a window to show dags before the second "
86 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
87 cl::desc("Pop up a window to show dags before the post legalize types"
88 " dag combine pass"));
90 ViewISelDAGs("view-isel-dags", cl::Hidden,
91 cl::desc("Pop up a window to show isel dags as they are selected"));
93 ViewSchedDAGs("view-sched-dags", cl::Hidden,
94 cl::desc("Pop up a window to show sched dags as they are processed"));
96 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
97 cl::desc("Pop up a window to show SUnit dags after they are processed"));
99 static const bool ViewDAGCombine1 = false,
100 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
101 ViewDAGCombine2 = false,
102 ViewDAGCombineLT = false,
103 ViewISelDAGs = false, ViewSchedDAGs = false,
104 ViewSUnitDAGs = false;
107 //===---------------------------------------------------------------------===//
109 /// RegisterScheduler class - Track the registration of instruction schedulers.
111 //===---------------------------------------------------------------------===//
112 MachinePassRegistry RegisterScheduler::Registry;
114 //===---------------------------------------------------------------------===//
116 /// ISHeuristic command line option for instruction schedulers.
118 //===---------------------------------------------------------------------===//
119 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
120 RegisterPassParser<RegisterScheduler> >
121 ISHeuristic("pre-RA-sched",
122 cl::init(&createDefaultScheduler),
123 cl::desc("Instruction schedulers available (before register"
126 static RegisterScheduler
127 defaultListDAGScheduler("default", "Best scheduler for the target",
128 createDefaultScheduler);
131 //===--------------------------------------------------------------------===//
132 /// createDefaultScheduler - This creates an instruction scheduler appropriate
134 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
135 CodeGenOpt::Level OptLevel) {
136 const TargetLowering &TLI = IS->getTargetLowering();
138 if (OptLevel == CodeGenOpt::None)
139 return createFastDAGScheduler(IS, OptLevel);
140 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
141 return createTDListDAGScheduler(IS, OptLevel);
142 assert(TLI.getSchedulingPreference() ==
143 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
144 return createBURRListDAGScheduler(IS, OptLevel);
148 // EmitInstrWithCustomInserter - This method should be implemented by targets
149 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
150 // instructions are special in various ways, which require special support to
151 // insert. The specified MachineInstr is created but not inserted into any
152 // basic blocks, and the scheduler passes ownership of it to this method.
153 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
154 MachineBasicBlock *MBB) const {
156 cerr << "If a target marks an instruction with "
157 "'usesCustomDAGSchedInserter', it must implement "
158 "TargetLowering::EmitInstrWithCustomInserter!";
164 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
165 /// physical register has only a single copy use, then coalesced the copy
167 static void EmitLiveInCopy(MachineBasicBlock *MBB,
168 MachineBasicBlock::iterator &InsertPos,
169 unsigned VirtReg, unsigned PhysReg,
170 const TargetRegisterClass *RC,
171 DenseMap<MachineInstr*, unsigned> &CopyRegMap,
172 const MachineRegisterInfo &MRI,
173 const TargetRegisterInfo &TRI,
174 const TargetInstrInfo &TII) {
175 unsigned NumUses = 0;
176 MachineInstr *UseMI = NULL;
177 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
178 UE = MRI.use_end(); UI != UE; ++UI) {
184 // If the number of uses is not one, or the use is not a move instruction,
185 // don't coalesce. Also, only coalesce away a virtual register to virtual
187 bool Coalesced = false;
188 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
190 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
191 TargetRegisterInfo::isVirtualRegister(DstReg)) {
196 // Now find an ideal location to insert the copy.
197 MachineBasicBlock::iterator Pos = InsertPos;
198 while (Pos != MBB->begin()) {
199 MachineInstr *PrevMI = prior(Pos);
200 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
201 // copyRegToReg might emit multiple instructions to do a copy.
202 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
203 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
204 // This is what the BB looks like right now:
209 // We want to insert "r1025 = mov r1". Inserting this copy below the
210 // move to r1024 makes it impossible for that move to be coalesced.
217 break; // Woot! Found a good location.
221 bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
222 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
225 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
227 if (&*InsertPos == UseMI) ++InsertPos;
232 /// EmitLiveInCopies - If this is the first basic block in the function,
233 /// and if it has live ins that need to be copied into vregs, emit the
234 /// copies into the block.
235 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
236 const MachineRegisterInfo &MRI,
237 const TargetRegisterInfo &TRI,
238 const TargetInstrInfo &TII) {
239 if (SchedLiveInCopies) {
240 // Emit the copies at a heuristically-determined location in the block.
241 DenseMap<MachineInstr*, unsigned> CopyRegMap;
242 MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
243 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
244 E = MRI.livein_end(); LI != E; ++LI)
246 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
247 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
248 RC, CopyRegMap, MRI, TRI, TII);
251 // Emit the copies into the top of the block.
252 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
253 E = MRI.livein_end(); LI != E; ++LI)
255 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
256 bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
257 LI->second, LI->first, RC, RC);
258 assert(Emitted && "Unable to issue a live-in copy instruction!\n");
264 //===----------------------------------------------------------------------===//
265 // SelectionDAGISel code
266 //===----------------------------------------------------------------------===//
268 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
269 FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
270 FuncInfo(new FunctionLoweringInfo(TLI)),
271 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
272 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
278 SelectionDAGISel::~SelectionDAGISel() {
284 unsigned SelectionDAGISel::MakeReg(MVT VT) {
285 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
288 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
289 AU.addRequired<AliasAnalysis>();
290 AU.addRequired<GCModuleInfo>();
291 AU.addRequired<DwarfWriter>();
292 AU.setPreservesAll();
295 bool SelectionDAGISel::runOnFunction(Function &Fn) {
296 // Do some sanity-checking on the command-line options.
297 assert((!EnableFastISelVerbose || EnableFastISel) &&
298 "-fast-isel-verbose requires -fast-isel");
299 assert((!EnableFastISelAbort || EnableFastISel) &&
300 "-fast-isel-abort requires -fast-isel");
302 // Do not codegen any 'available_externally' functions at all, they have
303 // definitions outside the translation unit.
304 if (Fn.hasAvailableExternallyLinkage())
308 // Get alias analysis for load/store combining.
309 AA = &getAnalysis<AliasAnalysis>();
311 TargetMachine &TM = TLI.getTargetMachine();
312 MF = &MachineFunction::construct(&Fn, TM);
313 const TargetInstrInfo &TII = *TM.getInstrInfo();
314 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
316 if (MF->getFunction()->hasGC())
317 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction());
320 RegInfo = &MF->getRegInfo();
321 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
323 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
324 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
325 CurDAG->init(*MF, MMI, DW);
326 FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
329 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
330 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
332 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
334 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
336 // If the first basic block in the function has live ins that need to be
337 // copied into vregs, emit the copies into the top of the block before
338 // emitting the code for the block.
339 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
341 // Add function live-ins to entry block live-in set.
342 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
343 E = RegInfo->livein_end(); I != E; ++I)
344 MF->begin()->addLiveIn(I->first);
347 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
348 "Not all catch info was assigned to a landing pad!");
356 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
357 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
358 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
359 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
360 // Apply the catch info to DestBB.
361 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
363 if (!FLI.MBBMap[SrcBB]->isLandingPad())
364 FLI.CatchInfoFound.insert(EHSel);
369 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
370 /// whether object offset >= 0.
372 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) {
373 if (!isa<FrameIndexSDNode>(Op)) return false;
375 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
376 int FrameIdx = FrameIdxNode->getIndex();
377 return MFI->isFixedObjectIndex(FrameIdx) &&
378 MFI->getObjectOffset(FrameIdx) >= 0;
381 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
382 /// possibly be overwritten when lowering the outgoing arguments in a tail
383 /// call. Currently the implementation of this call is very conservative and
384 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
385 /// virtual registers would be overwritten by direct lowering.
386 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
387 MachineFrameInfo *MFI) {
388 RegisterSDNode * OpReg = NULL;
389 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
390 (Op.getOpcode()== ISD::CopyFromReg &&
391 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
392 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
393 (Op.getOpcode() == ISD::LOAD &&
394 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
395 (Op.getOpcode() == ISD::MERGE_VALUES &&
396 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
397 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
403 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
404 /// DAG and fixes their tailcall attribute operand.
405 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
406 const TargetLowering& TLI) {
408 SDValue Terminator = DAG.getRoot();
411 if (Terminator.getOpcode() == ISD::RET) {
412 Ret = Terminator.getNode();
415 // Fix tail call attribute of CALL nodes.
416 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
417 BI = DAG.allnodes_end(); BI != BE; ) {
419 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) {
420 SDValue OpRet(Ret, 0);
421 SDValue OpCall(BI, 0);
422 bool isMarkedTailCall = TheCall->isTailCall();
423 // If CALL node has tail call attribute set to true and the call is not
424 // eligible (no RET or the target rejects) the attribute is fixed to
425 // false. The TargetLowering::IsEligibleForTailCallOptimization function
426 // must correctly identify tail call optimizable calls.
427 if (!isMarkedTailCall) continue;
429 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) {
430 // Not eligible. Mark CALL node as non tail call. Note that we
431 // can modify the call node in place since calls are not CSE'd.
432 TheCall->setNotTailCall();
434 // Look for tail call clobbered arguments. Emit a series of
435 // copyto/copyfrom virtual register nodes to protect them.
436 SmallVector<SDValue, 32> Ops;
437 SDValue Chain = TheCall->getChain(), InFlag;
438 Ops.push_back(Chain);
439 Ops.push_back(TheCall->getCallee());
440 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) {
441 SDValue Arg = TheCall->getArg(i);
442 bool isByVal = TheCall->getArgFlags(i).isByVal();
443 MachineFunction &MF = DAG.getMachineFunction();
444 MachineFrameInfo *MFI = MF.getFrameInfo();
446 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
447 MVT VT = Arg.getValueType();
448 unsigned VReg = MF.getRegInfo().
449 createVirtualRegister(TLI.getRegClassFor(VT));
450 Chain = DAG.getCopyToReg(Chain, Arg.getDebugLoc(),
452 InFlag = Chain.getValue(1);
453 Arg = DAG.getCopyFromReg(Chain, Arg.getDebugLoc(),
455 Chain = Arg.getValue(1);
456 InFlag = Arg.getValue(2);
459 Ops.push_back(TheCall->getArgFlagsVal(i));
461 // Link in chain of CopyTo/CopyFromReg.
463 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
469 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
470 BasicBlock::iterator Begin,
471 BasicBlock::iterator End) {
472 SDL->setCurrentBasicBlock(BB);
474 // Lower all of the non-terminator instructions.
475 for (BasicBlock::iterator I = Begin; I != End; ++I)
476 if (!isa<TerminatorInst>(I))
479 // Ensure that all instructions which are used outside of their defining
480 // blocks are available as virtual registers. Invoke is handled elsewhere.
481 for (BasicBlock::iterator I = Begin; I != End; ++I)
482 if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
483 SDL->CopyToExportRegsIfNeeded(I);
485 // Handle PHI nodes in successor blocks.
486 if (End == LLVMBB->end()) {
487 HandlePHINodesInSuccessorBlocks(LLVMBB);
489 // Lower the terminator after the copies are emitted.
490 SDL->visit(*LLVMBB->getTerminator());
493 // Make sure the root of the DAG is up-to-date.
494 CurDAG->setRoot(SDL->getControlRoot());
496 // Check whether calls in this block are real tail calls. Fix up CALL nodes
497 // with correct tailcall attribute so that the target can rely on the tailcall
498 // attribute indicating whether the call is really eligible for tail call
500 if (PerformTailCallOpt)
501 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
503 // Final step, emit the lowered DAG as machine code.
508 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
509 SmallPtrSet<SDNode*, 128> VisitedNodes;
510 SmallVector<SDNode*, 128> Worklist;
512 Worklist.push_back(CurDAG->getRoot().getNode());
518 while (!Worklist.empty()) {
519 SDNode *N = Worklist.back();
522 // If we've already seen this node, ignore it.
523 if (!VisitedNodes.insert(N))
526 // Otherwise, add all chain operands to the worklist.
527 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
528 if (N->getOperand(i).getValueType() == MVT::Other)
529 Worklist.push_back(N->getOperand(i).getNode());
531 // If this is a CopyToReg with a vreg dest, process it.
532 if (N->getOpcode() != ISD::CopyToReg)
535 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
536 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
539 // Ignore non-scalar or non-integer values.
540 SDValue Src = N->getOperand(2);
541 MVT SrcVT = Src.getValueType();
542 if (!SrcVT.isInteger() || SrcVT.isVector())
545 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
546 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
547 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
549 // Only install this information if it tells us something.
550 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
551 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
552 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
553 if (DestReg >= FLI.LiveOutRegInfo.size())
554 FLI.LiveOutRegInfo.resize(DestReg+1);
555 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
556 LOI.NumSignBits = NumSignBits;
557 LOI.KnownOne = KnownOne;
558 LOI.KnownZero = KnownZero;
563 void SelectionDAGISel::CodeGenAndEmitDAG() {
564 std::string GroupName;
565 if (TimePassesIsEnabled)
566 GroupName = "Instruction Selection and Scheduling";
567 std::string BlockName;
568 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
569 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
571 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ":" +
572 BB->getBasicBlock()->getName();
574 DOUT << "Initial selection DAG:\n";
575 DEBUG(CurDAG->dump());
577 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
579 // Run the DAG combiner in pre-legalize mode.
580 if (TimePassesIsEnabled) {
581 NamedRegionTimer T("DAG Combining 1", GroupName);
582 CurDAG->Combine(Unrestricted, *AA, OptLevel);
584 CurDAG->Combine(Unrestricted, *AA, OptLevel);
587 DOUT << "Optimized lowered selection DAG:\n";
588 DEBUG(CurDAG->dump());
590 // Second step, hack on the DAG until it only uses operations and types that
591 // the target supports.
592 if (!DisableLegalizeTypes) {
593 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
597 if (TimePassesIsEnabled) {
598 NamedRegionTimer T("Type Legalization", GroupName);
599 Changed = CurDAG->LegalizeTypes();
601 Changed = CurDAG->LegalizeTypes();
604 DOUT << "Type-legalized selection DAG:\n";
605 DEBUG(CurDAG->dump());
608 if (ViewDAGCombineLT)
609 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
611 // Run the DAG combiner in post-type-legalize mode.
612 if (TimePassesIsEnabled) {
613 NamedRegionTimer T("DAG Combining after legalize types", GroupName);
614 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
616 CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
619 DOUT << "Optimized type-legalized selection DAG:\n";
620 DEBUG(CurDAG->dump());
623 if (TimePassesIsEnabled) {
624 NamedRegionTimer T("Vector Legalization", GroupName);
625 Changed = CurDAG->LegalizeVectors();
627 Changed = CurDAG->LegalizeVectors();
631 if (TimePassesIsEnabled) {
632 NamedRegionTimer T("Type Legalization 2", GroupName);
633 Changed = CurDAG->LegalizeTypes();
635 Changed = CurDAG->LegalizeTypes();
638 if (ViewDAGCombineLT)
639 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
641 // Run the DAG combiner in post-type-legalize mode.
642 if (TimePassesIsEnabled) {
643 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
644 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
646 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
649 DOUT << "Optimized vector-legalized selection DAG:\n";
650 DEBUG(CurDAG->dump());
654 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
656 if (TimePassesIsEnabled) {
657 NamedRegionTimer T("DAG Legalization", GroupName);
658 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
660 CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
663 DOUT << "Legalized selection DAG:\n";
664 DEBUG(CurDAG->dump());
666 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
668 // Run the DAG combiner in post-legalize mode.
669 if (TimePassesIsEnabled) {
670 NamedRegionTimer T("DAG Combining 2", GroupName);
671 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
673 CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
676 DOUT << "Optimized legalized selection DAG:\n";
677 DEBUG(CurDAG->dump());
679 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
681 if (OptLevel != CodeGenOpt::None)
682 ComputeLiveOutVRegInfo();
684 // Third, instruction select all of the operations to machine code, adding the
685 // code to the MachineBasicBlock.
686 if (TimePassesIsEnabled) {
687 NamedRegionTimer T("Instruction Selection", GroupName);
693 DOUT << "Selected selection DAG:\n";
694 DEBUG(CurDAG->dump());
696 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
698 // Schedule machine code.
699 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
700 if (TimePassesIsEnabled) {
701 NamedRegionTimer T("Instruction Scheduling", GroupName);
702 Scheduler->Run(CurDAG, BB, BB->end());
704 Scheduler->Run(CurDAG, BB, BB->end());
707 if (ViewSUnitDAGs) Scheduler->viewGraph();
709 // Emit machine code to BB. This can change 'BB' to the last block being
711 if (TimePassesIsEnabled) {
712 NamedRegionTimer T("Instruction Creation", GroupName);
713 BB = Scheduler->EmitSchedule();
715 BB = Scheduler->EmitSchedule();
718 // Free the scheduler state.
719 if (TimePassesIsEnabled) {
720 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
726 DOUT << "Selected machine code:\n";
730 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
732 MachineModuleInfo *MMI,
734 const TargetInstrInfo &TII) {
735 // Initialize the Fast-ISel state, if needed.
736 FastISel *FastIS = 0;
738 FastIS = TLI.createFastISel(MF, MMI, DW,
741 FuncInfo->StaticAllocaMap
743 , FuncInfo->CatchInfoLost
747 // Iterate over all basic blocks in the function.
748 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
749 BasicBlock *LLVMBB = &*I;
750 BB = FuncInfo->MBBMap[LLVMBB];
752 BasicBlock::iterator const Begin = LLVMBB->begin();
753 BasicBlock::iterator const End = LLVMBB->end();
754 BasicBlock::iterator BI = Begin;
756 // Lower any arguments needed in this block if this is the entry block.
757 bool SuppressFastISel = false;
758 if (LLVMBB == &Fn.getEntryBlock()) {
759 LowerArguments(LLVMBB);
761 // If any of the arguments has the byval attribute, forgo
762 // fast-isel in the entry block.
765 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
767 if (Fn.paramHasAttr(j, Attribute::ByVal)) {
768 if (EnableFastISelVerbose || EnableFastISelAbort)
769 cerr << "FastISel skips entry block due to byval argument\n";
770 SuppressFastISel = true;
776 if (MMI && BB->isLandingPad()) {
777 // Add a label to mark the beginning of the landing pad. Deletion of the
778 // landing pad can thus be detected via the MachineModuleInfo.
779 unsigned LabelID = MMI->addLandingPad(BB);
781 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
782 BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
784 // Mark exception register as live in.
785 unsigned Reg = TLI.getExceptionAddressRegister();
786 if (Reg) BB->addLiveIn(Reg);
788 // Mark exception selector register as live in.
789 Reg = TLI.getExceptionSelectorRegister();
790 if (Reg) BB->addLiveIn(Reg);
792 // FIXME: Hack around an exception handling flaw (PR1508): the personality
793 // function and list of typeids logically belong to the invoke (or, if you
794 // like, the basic block containing the invoke), and need to be associated
795 // with it in the dwarf exception handling tables. Currently however the
796 // information is provided by an intrinsic (eh.selector) that can be moved
797 // to unexpected places by the optimizers: if the unwind edge is critical,
798 // then breaking it can result in the intrinsics being in the successor of
799 // the landing pad, not the landing pad itself. This results in exceptions
800 // not being caught because no typeids are associated with the invoke.
801 // This may not be the only way things can go wrong, but it is the only way
802 // we try to work around for the moment.
803 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
805 if (Br && Br->isUnconditional()) { // Critical edge?
806 BasicBlock::iterator I, E;
807 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
808 if (isa<EHSelectorInst>(I))
812 // No catch info found - try to extract some from the successor.
813 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
817 // Before doing SelectionDAG ISel, see if FastISel has been requested.
818 if (FastIS && !SuppressFastISel) {
819 // Emit code for any incoming arguments. This must happen before
820 // beginning FastISel on the entry block.
821 if (LLVMBB == &Fn.getEntryBlock()) {
822 CurDAG->setRoot(SDL->getControlRoot());
826 FastIS->startNewBlock(BB);
827 // Do FastISel on as many instructions as possible.
828 for (; BI != End; ++BI) {
829 // Just before the terminator instruction, insert instructions to
830 // feed PHI nodes in successor blocks.
831 if (isa<TerminatorInst>(BI))
832 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
833 if (EnableFastISelVerbose || EnableFastISelAbort) {
834 cerr << "FastISel miss: ";
837 assert(!EnableFastISelAbort &&
838 "FastISel didn't handle a PHI in a successor");
842 // First try normal tablegen-generated "fast" selection.
843 if (FastIS->SelectInstruction(BI))
846 // Next, try calling the target to attempt to handle the instruction.
847 if (FastIS->TargetSelectInstruction(BI))
850 // Then handle certain instructions as single-LLVM-Instruction blocks.
851 if (isa<CallInst>(BI)) {
852 if (EnableFastISelVerbose || EnableFastISelAbort) {
853 cerr << "FastISel missed call: ";
857 if (BI->getType() != Type::VoidTy) {
858 unsigned &R = FuncInfo->ValueMap[BI];
860 R = FuncInfo->CreateRegForValue(BI);
863 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
864 SelectBasicBlock(LLVMBB, BI, next(BI));
865 // If the instruction was codegen'd with multiple blocks,
866 // inform the FastISel object where to resume inserting.
867 FastIS->setCurrentBlock(BB);
871 // Otherwise, give up on FastISel for the rest of the block.
872 // For now, be a little lenient about non-branch terminators.
873 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
874 if (EnableFastISelVerbose || EnableFastISelAbort) {
875 cerr << "FastISel miss: ";
878 if (EnableFastISelAbort)
879 // The "fast" selector couldn't handle something and bailed.
880 // For the purpose of debugging, just abort.
881 llvm_unreachable("FastISel didn't select the entire block");
887 // Run SelectionDAG instruction selection on the remainder of the block
888 // not handled by FastISel. If FastISel is not run, this is the entire
891 // If FastISel is run and it has known DebugLoc then use it.
892 if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
893 SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
894 SelectBasicBlock(LLVMBB, BI, End);
904 SelectionDAGISel::FinishBasicBlock() {
906 DOUT << "Target-post-processed machine code:\n";
909 DOUT << "Total amount of phi nodes to update: "
910 << SDL->PHINodesToUpdate.size() << "\n";
911 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
912 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
913 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
915 // Next, now that we know what the last MBB the LLVM BB expanded is, update
916 // PHI nodes in successors.
917 if (SDL->SwitchCases.empty() &&
918 SDL->JTCases.empty() &&
919 SDL->BitTestCases.empty()) {
920 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
921 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
922 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
923 "This is not a machine PHI node that we are updating!");
924 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
926 PHI->addOperand(MachineOperand::CreateMBB(BB));
928 SDL->PHINodesToUpdate.clear();
932 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
933 // Lower header first, if it wasn't already lowered
934 if (!SDL->BitTestCases[i].Emitted) {
935 // Set the current basic block to the mbb we wish to insert the code into
936 BB = SDL->BitTestCases[i].Parent;
937 SDL->setCurrentBasicBlock(BB);
939 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
940 CurDAG->setRoot(SDL->getRoot());
945 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
946 // Set the current basic block to the mbb we wish to insert the code into
947 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
948 SDL->setCurrentBasicBlock(BB);
951 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
952 SDL->BitTestCases[i].Reg,
953 SDL->BitTestCases[i].Cases[j]);
955 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
956 SDL->BitTestCases[i].Reg,
957 SDL->BitTestCases[i].Cases[j]);
960 CurDAG->setRoot(SDL->getRoot());
966 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
967 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
968 MachineBasicBlock *PHIBB = PHI->getParent();
969 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
970 "This is not a machine PHI node that we are updating!");
971 // This is "default" BB. We have two jumps to it. From "header" BB and
972 // from last "case" BB.
973 if (PHIBB == SDL->BitTestCases[i].Default) {
974 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
976 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
977 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
979 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
982 // One of "cases" BB.
983 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
985 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
986 if (cBB->succ_end() !=
987 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
988 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
990 PHI->addOperand(MachineOperand::CreateMBB(cBB));
995 SDL->BitTestCases.clear();
997 // If the JumpTable record is filled in, then we need to emit a jump table.
998 // Updating the PHI nodes is tricky in this case, since we need to determine
999 // whether the PHI is a successor of the range check MBB or the jump table MBB
1000 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
1001 // Lower header first, if it wasn't already lowered
1002 if (!SDL->JTCases[i].first.Emitted) {
1003 // Set the current basic block to the mbb we wish to insert the code into
1004 BB = SDL->JTCases[i].first.HeaderBB;
1005 SDL->setCurrentBasicBlock(BB);
1007 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
1008 CurDAG->setRoot(SDL->getRoot());
1009 CodeGenAndEmitDAG();
1013 // Set the current basic block to the mbb we wish to insert the code into
1014 BB = SDL->JTCases[i].second.MBB;
1015 SDL->setCurrentBasicBlock(BB);
1017 SDL->visitJumpTable(SDL->JTCases[i].second);
1018 CurDAG->setRoot(SDL->getRoot());
1019 CodeGenAndEmitDAG();
1023 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
1024 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
1025 MachineBasicBlock *PHIBB = PHI->getParent();
1026 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1027 "This is not a machine PHI node that we are updating!");
1028 // "default" BB. We can go there only from header BB.
1029 if (PHIBB == SDL->JTCases[i].second.Default) {
1030 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1032 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
1034 // JT BB. Just iterate over successors here
1035 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
1036 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
1038 PHI->addOperand(MachineOperand::CreateMBB(BB));
1042 SDL->JTCases.clear();
1044 // If the switch block involved a branch to one of the actual successors, we
1045 // need to update PHI nodes in that block.
1046 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
1047 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
1048 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1049 "This is not a machine PHI node that we are updating!");
1050 if (BB->isSuccessor(PHI->getParent())) {
1051 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
1053 PHI->addOperand(MachineOperand::CreateMBB(BB));
1057 // If we generated any switch lowering information, build and codegen any
1058 // additional DAGs necessary.
1059 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
1060 // Set the current basic block to the mbb we wish to insert the code into
1061 BB = SDL->SwitchCases[i].ThisBB;
1062 SDL->setCurrentBasicBlock(BB);
1065 SDL->visitSwitchCase(SDL->SwitchCases[i]);
1066 CurDAG->setRoot(SDL->getRoot());
1067 CodeGenAndEmitDAG();
1070 // Handle any PHI nodes in successors of this chunk, as if we were coming
1071 // from the original BB before switch expansion. Note that PHI nodes can
1072 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1073 // handle them the right number of times.
1074 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
1075 for (MachineBasicBlock::iterator Phi = BB->begin();
1076 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1077 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1078 for (unsigned pn = 0; ; ++pn) {
1079 assert(pn != SDL->PHINodesToUpdate.size() &&
1080 "Didn't find PHI entry!");
1081 if (SDL->PHINodesToUpdate[pn].first == Phi) {
1082 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1084 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
1090 // Don't process RHS if same block as LHS.
1091 if (BB == SDL->SwitchCases[i].FalseBB)
1092 SDL->SwitchCases[i].FalseBB = 0;
1094 // If we haven't handled the RHS, do so now. Otherwise, we're done.
1095 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1096 SDL->SwitchCases[i].FalseBB = 0;
1098 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1100 SDL->SwitchCases.clear();
1102 SDL->PHINodesToUpdate.clear();
1106 /// Create the scheduler. If a specific scheduler was specified
1107 /// via the SchedulerRegistry, use it, otherwise select the
1108 /// one preferred by the target.
1110 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1111 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1115 RegisterScheduler::setDefault(Ctor);
1118 return Ctor(this, OptLevel);
1121 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1122 return new ScheduleHazardRecognizer();
1125 //===----------------------------------------------------------------------===//
1126 // Helper functions used by the generated instruction selector.
1127 //===----------------------------------------------------------------------===//
1128 // Calls to these methods are generated by tblgen.
1130 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1131 /// the dag combiner simplified the 255, we still want to match. RHS is the
1132 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1133 /// specified in the .td file (e.g. 255).
1134 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1135 int64_t DesiredMaskS) const {
1136 const APInt &ActualMask = RHS->getAPIntValue();
1137 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1139 // If the actual mask exactly matches, success!
1140 if (ActualMask == DesiredMask)
1143 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1144 if (ActualMask.intersects(~DesiredMask))
1147 // Otherwise, the DAG Combiner may have proven that the value coming in is
1148 // either already zero or is not demanded. Check for known zero input bits.
1149 APInt NeededMask = DesiredMask & ~ActualMask;
1150 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1153 // TODO: check to see if missing bits are just not demanded.
1155 // Otherwise, this pattern doesn't match.
1159 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1160 /// the dag combiner simplified the 255, we still want to match. RHS is the
1161 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1162 /// specified in the .td file (e.g. 255).
1163 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1164 int64_t DesiredMaskS) const {
1165 const APInt &ActualMask = RHS->getAPIntValue();
1166 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1168 // If the actual mask exactly matches, success!
1169 if (ActualMask == DesiredMask)
1172 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1173 if (ActualMask.intersects(~DesiredMask))
1176 // Otherwise, the DAG Combiner may have proven that the value coming in is
1177 // either already zero or is not demanded. Check for known zero input bits.
1178 APInt NeededMask = DesiredMask & ~ActualMask;
1180 APInt KnownZero, KnownOne;
1181 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1183 // If all the missing bits in the or are already known to be set, match!
1184 if ((NeededMask & KnownOne) == NeededMask)
1187 // TODO: check to see if missing bits are just not demanded.
1189 // Otherwise, this pattern doesn't match.
1194 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1195 /// by tblgen. Others should not call it.
1196 void SelectionDAGISel::
1197 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1198 std::vector<SDValue> InOps;
1199 std::swap(InOps, Ops);
1201 Ops.push_back(InOps[0]); // input chain.
1202 Ops.push_back(InOps[1]); // input asm string.
1204 unsigned i = 2, e = InOps.size();
1205 if (InOps[e-1].getValueType() == MVT::Flag)
1206 --e; // Don't process a flag operand if it is here.
1209 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1210 if ((Flags & 7) != 4 /*MEM*/) {
1211 // Just skip over this operand, copying the operands verbatim.
1212 Ops.insert(Ops.end(), InOps.begin()+i,
1213 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1214 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1216 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1217 "Memory operand with multiple values?");
1218 // Otherwise, this is a memory operand. Ask the target to select it.
1219 std::vector<SDValue> SelOps;
1220 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1221 llvm_report_error("Could not match memory address. Inline asm"
1225 // Add this to the output node.
1226 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
1227 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1229 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1234 // Add the flag input back if present.
1235 if (e != InOps.size())
1236 Ops.push_back(InOps.back());
1239 /// findFlagUse - Return use of MVT::Flag value produced by the specified
1242 static SDNode *findFlagUse(SDNode *N) {
1243 unsigned FlagResNo = N->getNumValues()-1;
1244 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1245 SDUse &Use = I.getUse();
1246 if (Use.getResNo() == FlagResNo)
1247 return Use.getUser();
1252 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1253 /// This function recursively traverses up the operand chain, ignoring
1255 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1257 SmallPtrSet<SDNode*, 16> &Visited) {
1258 if (Use->getNodeId() < Def->getNodeId() ||
1259 !Visited.insert(Use))
1262 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1263 SDNode *N = Use->getOperand(i).getNode();
1265 if (Use == ImmedUse || Use == Root)
1266 continue; // We are not looking for immediate use.
1271 // Traverse up the operand chain.
1272 if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1278 /// isNonImmUse - Start searching from Root up the DAG to check is Def can
1279 /// be reached. Return true if that's the case. However, ignore direct uses
1280 /// by ImmedUse (which would be U in the example illustrated in
1281 /// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1283 /// FIXME: to be really generic, we should allow direct use by any node
1284 /// that is being folded. But realisticly since we only fold loads which
1285 /// have one non-chain use, we only need to watch out for load/op/store
1286 /// and load/op/cmp case where the root (store / cmp) may reach the load via
1287 /// its chain operand.
1288 static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1289 SmallPtrSet<SDNode*, 16> Visited;
1290 return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1293 /// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1294 /// U can be folded during instruction selection that starts at Root and
1295 /// folding N is profitable.
1296 bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1297 SDNode *Root) const {
1298 if (OptLevel == CodeGenOpt::None) return false;
1300 // If Root use can somehow reach N through a path that that doesn't contain
1301 // U then folding N would create a cycle. e.g. In the following
1302 // diagram, Root can reach N through X. If N is folded into into Root, then
1303 // X is both a predecessor and a successor of U.
1314 // * indicates nodes to be folded together.
1316 // If Root produces a flag, then it gets (even more) interesting. Since it
1317 // will be "glued" together with its flag use in the scheduler, we need to
1318 // check if it might reach N.
1337 // If FU (flag use) indirectly reaches N (the load), and Root folds N
1338 // (call it Fold), then X is a predecessor of FU and a successor of
1339 // Fold. But since Fold and FU are flagged together, this will create
1340 // a cycle in the scheduling graph.
1342 MVT VT = Root->getValueType(Root->getNumValues()-1);
1343 while (VT == MVT::Flag) {
1344 SDNode *FU = findFlagUse(Root);
1348 VT = Root->getValueType(Root->getNumValues()-1);
1351 return !isNonImmUse(Root, N, U);
1355 char SelectionDAGISel::ID = 0;