LLVM API Documentation
00001 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This implements the SelectionDAGISel class. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #define DEBUG_TYPE "isel" 00015 #include "llvm/CodeGen/SelectionDAGISel.h" 00016 #include "SelectionDAGBuild.h" 00017 #include "llvm/Analysis/AliasAnalysis.h" 00018 #include "llvm/Constants.h" 00019 #include "llvm/CallingConv.h" 00020 #include "llvm/DerivedTypes.h" 00021 #include "llvm/Function.h" 00022 #include "llvm/GlobalVariable.h" 00023 #include "llvm/InlineAsm.h" 00024 #include "llvm/Instructions.h" 00025 #include "llvm/Intrinsics.h" 00026 #include "llvm/IntrinsicInst.h" 00027 #include "llvm/CodeGen/FastISel.h" 00028 #include "llvm/CodeGen/GCStrategy.h" 00029 #include "llvm/CodeGen/GCMetadata.h" 00030 #include "llvm/CodeGen/MachineFunction.h" 00031 #include "llvm/CodeGen/MachineFrameInfo.h" 00032 #include "llvm/CodeGen/MachineInstrBuilder.h" 00033 #include "llvm/CodeGen/MachineJumpTableInfo.h" 00034 #include "llvm/CodeGen/MachineModuleInfo.h" 00035 #include "llvm/CodeGen/MachineRegisterInfo.h" 00036 #include "llvm/CodeGen/ScheduleDAGSDNodes.h" 00037 #include "llvm/CodeGen/ScheduleHazardRecognizer.h" 00038 #include "llvm/CodeGen/SchedulerRegistry.h" 00039 #include "llvm/CodeGen/SelectionDAG.h" 00040 #include "llvm/CodeGen/DwarfWriter.h" 00041 #include "llvm/Target/TargetRegisterInfo.h" 00042 #include "llvm/Target/TargetData.h" 00043 #include "llvm/Target/TargetFrameInfo.h" 00044 #include "llvm/Target/TargetInstrInfo.h" 00045 #include "llvm/Target/TargetLowering.h" 00046 #include "llvm/Target/TargetMachine.h" 00047 #include "llvm/Target/TargetOptions.h" 00048 #include "llvm/Support/Compiler.h" 00049 #include "llvm/Support/Debug.h" 00050 #include "llvm/Support/MathExtras.h" 00051 #include "llvm/Support/Timer.h" 00052 #include <algorithm> 00053 using namespace llvm; 00054 00055 static cl::opt<bool> 00056 EnableValueProp("enable-value-prop", cl::Hidden); 00057 static cl::opt<bool> 00058 DisableLegalizeTypes("disable-legalize-types", cl::Hidden); 00059 #ifndef NDEBUG 00060 static cl::opt<bool> 00061 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden, 00062 cl::desc("Enable verbose messages in the \"fast\" " 00063 "instruction selector")); 00064 static cl::opt<bool> 00065 EnableFastISelAbort("fast-isel-abort", cl::Hidden, 00066 cl::desc("Enable abort calls when \"fast\" instruction fails")); 00067 #else 00068 static const bool EnableFastISelVerbose = false, 00069 EnableFastISelAbort = false; 00070 #endif 00071 static cl::opt<bool> 00072 SchedLiveInCopies("schedule-livein-copies", 00073 cl::desc("Schedule copies of livein registers"), 00074 cl::init(false)); 00075 00076 #ifndef NDEBUG 00077 static cl::opt<bool> 00078 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, 00079 cl::desc("Pop up a window to show dags before the first " 00080 "dag combine pass")); 00081 static cl::opt<bool> 00082 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, 00083 cl::desc("Pop up a window to show dags before legalize types")); 00084 static cl::opt<bool> 00085 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, 00086 cl::desc("Pop up a window to show dags before legalize")); 00087 static cl::opt<bool> 00088 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, 00089 cl::desc("Pop up a window to show dags before the second " 00090 "dag combine pass")); 00091 static cl::opt<bool> 00092 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, 00093 cl::desc("Pop up a window to show dags before the post legalize types" 00094 " dag combine pass")); 00095 static cl::opt<bool> 00096 ViewISelDAGs("view-isel-dags", cl::Hidden, 00097 cl::desc("Pop up a window to show isel dags as they are selected")); 00098 static cl::opt<bool> 00099 ViewSchedDAGs("view-sched-dags", cl::Hidden, 00100 cl::desc("Pop up a window to show sched dags as they are processed")); 00101 static cl::opt<bool> 00102 ViewSUnitDAGs("view-sunit-dags", cl::Hidden, 00103 cl::desc("Pop up a window to show SUnit dags after they are processed")); 00104 #else 00105 static const bool ViewDAGCombine1 = false, 00106 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false, 00107 ViewDAGCombine2 = false, 00108 ViewDAGCombineLT = false, 00109 ViewISelDAGs = false, ViewSchedDAGs = false, 00110 ViewSUnitDAGs = false; 00111 #endif 00112 00113 //===---------------------------------------------------------------------===// 00114 /// 00115 /// RegisterScheduler class - Track the registration of instruction schedulers. 00116 /// 00117 //===---------------------------------------------------------------------===// 00118 MachinePassRegistry RegisterScheduler::Registry; 00119 00120 //===---------------------------------------------------------------------===// 00121 /// 00122 /// ISHeuristic command line option for instruction schedulers. 00123 /// 00124 //===---------------------------------------------------------------------===// 00125 static cl::opt<RegisterScheduler::FunctionPassCtor, false, 00126 RegisterPassParser<RegisterScheduler> > 00127 ISHeuristic("pre-RA-sched", 00128 cl::init(&createDefaultScheduler), 00129 cl::desc("Instruction schedulers available (before register" 00130 " allocation):")); 00131 00132 static RegisterScheduler 00133 defaultListDAGScheduler("default", "Best scheduler for the target", 00134 createDefaultScheduler); 00135 00136 namespace llvm { 00137 //===--------------------------------------------------------------------===// 00138 /// createDefaultScheduler - This creates an instruction scheduler appropriate 00139 /// for the target. 00140 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS, 00141 bool Fast) { 00142 const TargetLowering &TLI = IS->getTargetLowering(); 00143 00144 if (Fast) 00145 return createFastDAGScheduler(IS, Fast); 00146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) 00147 return createTDListDAGScheduler(IS, Fast); 00148 assert(TLI.getSchedulingPreference() == 00149 TargetLowering::SchedulingForRegPressure && "Unknown sched type!"); 00150 return createBURRListDAGScheduler(IS, Fast); 00151 } 00152 } 00153 00154 // EmitInstrWithCustomInserter - This method should be implemented by targets 00155 // that mark instructions with the 'usesCustomDAGSchedInserter' flag. These 00156 // instructions are special in various ways, which require special support to 00157 // insert. The specified MachineInstr is created but not inserted into any 00158 // basic blocks, and the scheduler passes ownership of it to this method. 00159 MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 00160 MachineBasicBlock *MBB) { 00161 cerr << "If a target marks an instruction with " 00162 << "'usesCustomDAGSchedInserter', it must implement " 00163 << "TargetLowering::EmitInstrWithCustomInserter!\n"; 00164 abort(); 00165 return 0; 00166 } 00167 00168 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the 00169 /// physical register has only a single copy use, then coalesced the copy 00170 /// if possible. 00171 static void EmitLiveInCopy(MachineBasicBlock *MBB, 00172 MachineBasicBlock::iterator &InsertPos, 00173 unsigned VirtReg, unsigned PhysReg, 00174 const TargetRegisterClass *RC, 00175 DenseMap<MachineInstr*, unsigned> &CopyRegMap, 00176 const MachineRegisterInfo &MRI, 00177 const TargetRegisterInfo &TRI, 00178 const TargetInstrInfo &TII) { 00179 unsigned NumUses = 0; 00180 MachineInstr *UseMI = NULL; 00181 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg), 00182 UE = MRI.use_end(); UI != UE; ++UI) { 00183 UseMI = &*UI; 00184 if (++NumUses > 1) 00185 break; 00186 } 00187 00188 // If the number of uses is not one, or the use is not a move instruction, 00189 // don't coalesce. Also, only coalesce away a virtual register to virtual 00190 // register copy. 00191 bool Coalesced = false; 00192 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg; 00193 if (NumUses == 1 && 00194 TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) && 00195 TargetRegisterInfo::isVirtualRegister(DstReg)) { 00196 VirtReg = DstReg; 00197 Coalesced = true; 00198 } 00199 00200 // Now find an ideal location to insert the copy. 00201 MachineBasicBlock::iterator Pos = InsertPos; 00202 while (Pos != MBB->begin()) { 00203 MachineInstr *PrevMI = prior(Pos); 00204 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI); 00205 // copyRegToReg might emit multiple instructions to do a copy. 00206 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second; 00207 if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg)) 00208 // This is what the BB looks like right now: 00209 // r1024 = mov r0 00210 // ... 00211 // r1 = mov r1024 00212 // 00213 // We want to insert "r1025 = mov r1". Inserting this copy below the 00214 // move to r1024 makes it impossible for that move to be coalesced. 00215 // 00216 // r1025 = mov r1 00217 // r1024 = mov r0 00218 // ... 00219 // r1 = mov 1024 00220 // r2 = mov 1025 00221 break; // Woot! Found a good location. 00222 --Pos; 00223 } 00224 00225 TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC); 00226 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg)); 00227 if (Coalesced) { 00228 if (&*InsertPos == UseMI) ++InsertPos; 00229 MBB->erase(UseMI); 00230 } 00231 } 00232 00233 /// EmitLiveInCopies - If this is the first basic block in the function, 00234 /// and if it has live ins that need to be copied into vregs, emit the 00235 /// copies into the block. 00236 static void EmitLiveInCopies(MachineBasicBlock *EntryMBB, 00237 const MachineRegisterInfo &MRI, 00238 const TargetRegisterInfo &TRI, 00239 const TargetInstrInfo &TII) { 00240 if (SchedLiveInCopies) { 00241 // Emit the copies at a heuristically-determined location in the block. 00242 DenseMap<MachineInstr*, unsigned> CopyRegMap; 00243 MachineBasicBlock::iterator InsertPos = EntryMBB->begin(); 00244 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(), 00245 E = MRI.livein_end(); LI != E; ++LI) 00246 if (LI->second) { 00247 const TargetRegisterClass *RC = MRI.getRegClass(LI->second); 00248 EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first, 00249 RC, CopyRegMap, MRI, TRI, TII); 00250 } 00251 } else { 00252 // Emit the copies into the top of the block. 00253 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(), 00254 E = MRI.livein_end(); LI != E; ++LI) 00255 if (LI->second) { 00256 const TargetRegisterClass *RC = MRI.getRegClass(LI->second); 00257 TII.copyRegToReg(*EntryMBB, EntryMBB->begin(), 00258 LI->second, LI->first, RC, RC); 00259 } 00260 } 00261 } 00262 00263 //===----------------------------------------------------------------------===// 00264 // SelectionDAGISel code 00265 //===----------------------------------------------------------------------===// 00266 00267 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, bool fast) : 00268 FunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()), 00269 FuncInfo(new FunctionLoweringInfo(TLI)), 00270 CurDAG(new SelectionDAG(TLI, *FuncInfo)), 00271 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)), 00272 GFI(), 00273 Fast(fast), 00274 DAGSize(0) 00275 {} 00276 00277 SelectionDAGISel::~SelectionDAGISel() { 00278 delete SDL; 00279 delete CurDAG; 00280 delete FuncInfo; 00281 } 00282 00283 unsigned SelectionDAGISel::MakeReg(MVT VT) { 00284 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT)); 00285 } 00286 00287 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { 00288 AU.addRequired<AliasAnalysis>(); 00289 AU.addRequired<GCModuleInfo>(); 00290 AU.addRequired<DwarfWriter>(); 00291 AU.setPreservesAll(); 00292 } 00293 00294 bool SelectionDAGISel::runOnFunction(Function &Fn) { 00295 // Do some sanity-checking on the command-line options. 00296 assert((!EnableFastISelVerbose || EnableFastISel) && 00297 "-fast-isel-verbose requires -fast-isel"); 00298 assert((!EnableFastISelAbort || EnableFastISel) && 00299 "-fast-isel-abort requires -fast-isel"); 00300 00301 // Get alias analysis for load/store combining. 00302 AA = &getAnalysis<AliasAnalysis>(); 00303 00304 TargetMachine &TM = TLI.getTargetMachine(); 00305 MF = &MachineFunction::construct(&Fn, TM); 00306 const TargetInstrInfo &TII = *TM.getInstrInfo(); 00307 const TargetRegisterInfo &TRI = *TM.getRegisterInfo(); 00308 00309 if (MF->getFunction()->hasGC()) 00310 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF->getFunction()); 00311 else 00312 GFI = 0; 00313 RegInfo = &MF->getRegInfo(); 00314 DOUT << "\n\n\n=== " << Fn.getName() << "\n"; 00315 00316 MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 00317 DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>(); 00318 CurDAG->init(*MF, MMI, DW); 00319 FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel); 00320 SDL->init(GFI, *AA); 00321 00322 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 00323 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator())) 00324 // Mark landing pad. 00325 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad(); 00326 00327 SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII); 00328 00329 // If the first basic block in the function has live ins that need to be 00330 // copied into vregs, emit the copies into the top of the block before 00331 // emitting the code for the block. 00332 EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII); 00333 00334 // Add function live-ins to entry block live-in set. 00335 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(), 00336 E = RegInfo->livein_end(); I != E; ++I) 00337 MF->begin()->addLiveIn(I->first); 00338 00339 #ifndef NDEBUG 00340 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() && 00341 "Not all catch info was assigned to a landing pad!"); 00342 #endif 00343 00344 FuncInfo->clear(); 00345 00346 return true; 00347 } 00348 00349 static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB, 00350 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) { 00351 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I) 00352 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) { 00353 // Apply the catch info to DestBB. 00354 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]); 00355 #ifndef NDEBUG 00356 if (!FLI.MBBMap[SrcBB]->isLandingPad()) 00357 FLI.CatchInfoFound.insert(EHSel); 00358 #endif 00359 } 00360 } 00361 00362 /// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and 00363 /// whether object offset >= 0. 00364 static bool 00365 IsFixedFrameObjectWithPosOffset(MachineFrameInfo *MFI, SDValue Op) { 00366 if (!isa<FrameIndexSDNode>(Op)) return false; 00367 00368 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op); 00369 int FrameIdx = FrameIdxNode->getIndex(); 00370 return MFI->isFixedObjectIndex(FrameIdx) && 00371 MFI->getObjectOffset(FrameIdx) >= 0; 00372 } 00373 00374 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could 00375 /// possibly be overwritten when lowering the outgoing arguments in a tail 00376 /// call. Currently the implementation of this call is very conservative and 00377 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with 00378 /// virtual registers would be overwritten by direct lowering. 00379 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op, 00380 MachineFrameInfo *MFI) { 00381 RegisterSDNode * OpReg = NULL; 00382 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS || 00383 (Op.getOpcode()== ISD::CopyFromReg && 00384 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) && 00385 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) || 00386 (Op.getOpcode() == ISD::LOAD && 00387 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) || 00388 (Op.getOpcode() == ISD::MERGE_VALUES && 00389 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD && 00390 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()). 00391 getOperand(1)))) 00392 return true; 00393 return false; 00394 } 00395 00396 /// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the 00397 /// DAG and fixes their tailcall attribute operand. 00398 static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 00399 const TargetLowering& TLI) { 00400 SDNode * Ret = NULL; 00401 SDValue Terminator = DAG.getRoot(); 00402 00403 // Find RET node. 00404 if (Terminator.getOpcode() == ISD::RET) { 00405 Ret = Terminator.getNode(); 00406 } 00407 00408 // Fix tail call attribute of CALL nodes. 00409 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(), 00410 BI = DAG.allnodes_end(); BI != BE; ) { 00411 --BI; 00412 if (CallSDNode *TheCall = dyn_cast<CallSDNode>(BI)) { 00413 SDValue OpRet(Ret, 0); 00414 SDValue OpCall(BI, 0); 00415 bool isMarkedTailCall = TheCall->isTailCall(); 00416 // If CALL node has tail call attribute set to true and the call is not 00417 // eligible (no RET or the target rejects) the attribute is fixed to 00418 // false. The TargetLowering::IsEligibleForTailCallOptimization function 00419 // must correctly identify tail call optimizable calls. 00420 if (!isMarkedTailCall) continue; 00421 if (Ret==NULL || 00422 !TLI.IsEligibleForTailCallOptimization(TheCall, OpRet, DAG)) { 00423 // Not eligible. Mark CALL node as non tail call. Note that we 00424 // can modify the call node in place since calls are not CSE'd. 00425 TheCall->setNotTailCall(); 00426 } else { 00427 // Look for tail call clobbered arguments. Emit a series of 00428 // copyto/copyfrom virtual register nodes to protect them. 00429 SmallVector<SDValue, 32> Ops; 00430 SDValue Chain = TheCall->getChain(), InFlag; 00431 Ops.push_back(Chain); 00432 Ops.push_back(TheCall->getCallee()); 00433 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; ++i) { 00434 SDValue Arg = TheCall->getArg(i); 00435 bool isByVal = TheCall->getArgFlags(i).isByVal(); 00436 MachineFunction &MF = DAG.getMachineFunction(); 00437 MachineFrameInfo *MFI = MF.getFrameInfo(); 00438 if (!isByVal && 00439 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) { 00440 MVT VT = Arg.getValueType(); 00441 unsigned VReg = MF.getRegInfo(). 00442 createVirtualRegister(TLI.getRegClassFor(VT)); 00443 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag); 00444 InFlag = Chain.getValue(1); 00445 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag); 00446 Chain = Arg.getValue(1); 00447 InFlag = Arg.getValue(2); 00448 } 00449 Ops.push_back(Arg); 00450 Ops.push_back(TheCall->getArgFlagsVal(i)); 00451 } 00452 // Link in chain of CopyTo/CopyFromReg. 00453 Ops[0] = Chain; 00454 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size()); 00455 } 00456 } 00457 } 00458 } 00459 00460 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, 00461 BasicBlock::iterator Begin, 00462 BasicBlock::iterator End) { 00463 SDL->setCurrentBasicBlock(BB); 00464 00465 // Lower all of the non-terminator instructions. 00466 for (BasicBlock::iterator I = Begin; I != End; ++I) 00467 if (!isa<TerminatorInst>(I)) 00468 SDL->visit(*I); 00469 00470 // Ensure that all instructions which are used outside of their defining 00471 // blocks are available as virtual registers. Invoke is handled elsewhere. 00472 for (BasicBlock::iterator I = Begin; I != End; ++I) 00473 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) { 00474 DenseMap<const Value*,unsigned>::iterator VMI =FuncInfo->ValueMap.find(I); 00475 if (VMI != FuncInfo->ValueMap.end()) 00476 SDL->CopyValueToVirtualRegister(I, VMI->second); 00477 } 00478 00479 // Handle PHI nodes in successor blocks. 00480 if (End == LLVMBB->end()) { 00481 HandlePHINodesInSuccessorBlocks(LLVMBB); 00482 00483 // Lower the terminator after the copies are emitted. 00484 SDL->visit(*LLVMBB->getTerminator()); 00485 } 00486 00487 // Make sure the root of the DAG is up-to-date. 00488 CurDAG->setRoot(SDL->getControlRoot()); 00489 00490 // Check whether calls in this block are real tail calls. Fix up CALL nodes 00491 // with correct tailcall attribute so that the target can rely on the tailcall 00492 // attribute indicating whether the call is really eligible for tail call 00493 // optimization. 00494 if (PerformTailCallOpt) 00495 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI); 00496 00497 // Final step, emit the lowered DAG as machine code. 00498 CodeGenAndEmitDAG(); 00499 SDL->clear(); 00500 } 00501 00502 void SelectionDAGISel::ComputeLiveOutVRegInfo() { 00503 SmallPtrSet<SDNode*, 128> VisitedNodes; 00504 SmallVector<SDNode*, 128> Worklist; 00505 00506 Worklist.push_back(CurDAG->getRoot().getNode()); 00507 00508 APInt Mask; 00509 APInt KnownZero; 00510 APInt KnownOne; 00511 00512 while (!Worklist.empty()) { 00513 SDNode *N = Worklist.back(); 00514 Worklist.pop_back(); 00515 00516 // If we've already seen this node, ignore it. 00517 if (!VisitedNodes.insert(N)) 00518 continue; 00519 00520 // Otherwise, add all chain operands to the worklist. 00521 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 00522 if (N->getOperand(i).getValueType() == MVT::Other) 00523 Worklist.push_back(N->getOperand(i).getNode()); 00524 00525 // If this is a CopyToReg with a vreg dest, process it. 00526 if (N->getOpcode() != ISD::CopyToReg) 00527 continue; 00528 00529 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg(); 00530 if (!TargetRegisterInfo::isVirtualRegister(DestReg)) 00531 continue; 00532 00533 // Ignore non-scalar or non-integer values. 00534 SDValue Src = N->getOperand(2); 00535 MVT SrcVT = Src.getValueType(); 00536 if (!SrcVT.isInteger() || SrcVT.isVector()) 00537 continue; 00538 00539 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src); 00540 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits()); 00541 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne); 00542 00543 // Only install this information if it tells us something. 00544 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) { 00545 DestReg -= TargetRegisterInfo::FirstVirtualRegister; 00546 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo(); 00547 if (DestReg >= FLI.LiveOutRegInfo.size()) 00548 FLI.LiveOutRegInfo.resize(DestReg+1); 00549 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg]; 00550 LOI.NumSignBits = NumSignBits; 00551 LOI.KnownOne = NumSignBits; 00552 LOI.KnownZero = NumSignBits; 00553 } 00554 } 00555 } 00556 00557 void SelectionDAGISel::CodeGenAndEmitDAG() { 00558 std::string GroupName; 00559 if (TimePassesIsEnabled) 00560 GroupName = "Instruction Selection and Scheduling"; 00561 std::string BlockName; 00562 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs || 00563 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs || 00564 ViewSUnitDAGs) 00565 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' + 00566 BB->getBasicBlock()->getName(); 00567 00568 DOUT << "Initial selection DAG:\n"; 00569 DEBUG(CurDAG->dump()); 00570 00571 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName); 00572 00573 // Run the DAG combiner in pre-legalize mode. 00574 if (TimePassesIsEnabled) { 00575 NamedRegionTimer T("DAG Combining 1", GroupName); 00576 CurDAG->Combine(Unrestricted, *AA, Fast); 00577 } else { 00578 CurDAG->Combine(Unrestricted, *AA, Fast); 00579 } 00580 00581 DOUT << "Optimized lowered selection DAG:\n"; 00582 DEBUG(CurDAG->dump()); 00583 00584 // Second step, hack on the DAG until it only uses operations and types that 00585 // the target supports. 00586 if (!DisableLegalizeTypes) { 00587 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " + 00588 BlockName); 00589 00590 bool Changed; 00591 if (TimePassesIsEnabled) { 00592 NamedRegionTimer T("Type Legalization", GroupName); 00593 Changed = CurDAG->LegalizeTypes(); 00594 } else { 00595 Changed = CurDAG->LegalizeTypes(); 00596 } 00597 00598 DOUT << "Type-legalized selection DAG:\n"; 00599 DEBUG(CurDAG->dump()); 00600 00601 if (Changed) { 00602 if (ViewDAGCombineLT) 00603 CurDAG->viewGraph("dag-combine-lt input for " + BlockName); 00604 00605 // Run the DAG combiner in post-type-legalize mode. 00606 if (TimePassesIsEnabled) { 00607 NamedRegionTimer T("DAG Combining after legalize types", GroupName); 00608 CurDAG->Combine(NoIllegalTypes, *AA, Fast); 00609 } else { 00610 CurDAG->Combine(NoIllegalTypes, *AA, Fast); 00611 } 00612 00613 DOUT << "Optimized type-legalized selection DAG:\n"; 00614 DEBUG(CurDAG->dump()); 00615 } 00616 } 00617 00618 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName); 00619 00620 if (TimePassesIsEnabled) { 00621 NamedRegionTimer T("DAG Legalization", GroupName); 00622 CurDAG->Legalize(DisableLegalizeTypes); 00623 } else { 00624 CurDAG->Legalize(DisableLegalizeTypes); 00625 } 00626 00627 DOUT << "Legalized selection DAG:\n"; 00628 DEBUG(CurDAG->dump()); 00629 00630 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName); 00631 00632 // Run the DAG combiner in post-legalize mode. 00633 if (TimePassesIsEnabled) { 00634 NamedRegionTimer T("DAG Combining 2", GroupName); 00635 CurDAG->Combine(NoIllegalOperations, *AA, Fast); 00636 } else { 00637 CurDAG->Combine(NoIllegalOperations, *AA, Fast); 00638 } 00639 00640 DOUT << "Optimized legalized selection DAG:\n"; 00641 DEBUG(CurDAG->dump()); 00642 00643 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName); 00644 00645 if (!Fast && EnableValueProp) 00646 ComputeLiveOutVRegInfo(); 00647 00648 // Third, instruction select all of the operations to machine code, adding the 00649 // code to the MachineBasicBlock. 00650 if (TimePassesIsEnabled) { 00651 NamedRegionTimer T("Instruction Selection", GroupName); 00652 InstructionSelect(); 00653 } else { 00654 InstructionSelect(); 00655 } 00656 00657 DOUT << "Selected selection DAG:\n"; 00658 DEBUG(CurDAG->dump()); 00659 00660 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName); 00661 00662 // Schedule machine code. 00663 ScheduleDAG *Scheduler; 00664 if (TimePassesIsEnabled) { 00665 NamedRegionTimer T("Instruction Scheduling", GroupName); 00666 Scheduler = Schedule(); 00667 } else { 00668 Scheduler = Schedule(); 00669 } 00670 00671 if (ViewSUnitDAGs) Scheduler->viewGraph(); 00672 00673 // Emit machine code to BB. This can change 'BB' to the last block being 00674 // inserted into. 00675 if (TimePassesIsEnabled) { 00676 NamedRegionTimer T("Instruction Creation", GroupName); 00677 BB = Scheduler->EmitSchedule(); 00678 } else { 00679 BB = Scheduler->EmitSchedule(); 00680 } 00681 00682 // Free the scheduler state. 00683 if (TimePassesIsEnabled) { 00684 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName); 00685 delete Scheduler; 00686 } else { 00687 delete Scheduler; 00688 } 00689 00690 DOUT << "Selected machine code:\n"; 00691 DEBUG(BB->dump()); 00692 } 00693 00694 void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, 00695 MachineFunction &MF, 00696 MachineModuleInfo *MMI, 00697 DwarfWriter *DW, 00698 const TargetInstrInfo &TII) { 00699 // Initialize the Fast-ISel state, if needed. 00700 FastISel *FastIS = 0; 00701 if (EnableFastISel) 00702 FastIS = TLI.createFastISel(MF, MMI, DW, 00703 FuncInfo->ValueMap, 00704 FuncInfo->MBBMap, 00705 FuncInfo->StaticAllocaMap 00706 #ifndef NDEBUG 00707 , FuncInfo->CatchInfoLost 00708 #endif 00709 ); 00710 00711 // Iterate over all basic blocks in the function. 00712 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { 00713 BasicBlock *LLVMBB = &*I; 00714 BB = FuncInfo->MBBMap[LLVMBB]; 00715 00716 BasicBlock::iterator const Begin = LLVMBB->begin(); 00717 BasicBlock::iterator const End = LLVMBB->end(); 00718 BasicBlock::iterator BI = Begin; 00719 00720 // Lower any arguments needed in this block if this is the entry block. 00721 bool SuppressFastISel = false; 00722 if (LLVMBB == &Fn.getEntryBlock()) { 00723 LowerArguments(LLVMBB); 00724 00725 // If any of the arguments has the byval attribute, forgo 00726 // fast-isel in the entry block. 00727 if (FastIS) { 00728 unsigned j = 1; 00729 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(); 00730 I != E; ++I, ++j) 00731 if (Fn.paramHasAttr(j, Attribute::ByVal)) { 00732 if (EnableFastISelVerbose || EnableFastISelAbort) 00733 cerr << "FastISel skips entry block due to byval argument\n"; 00734 SuppressFastISel = true; 00735 break; 00736 } 00737 } 00738 } 00739 00740 if (MMI && BB->isLandingPad()) { 00741 // Add a label to mark the beginning of the landing pad. Deletion of the 00742 // landing pad can thus be detected via the MachineModuleInfo. 00743 unsigned LabelID = MMI->addLandingPad(BB); 00744 00745 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL); 00746 BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID); 00747 00748 // Mark exception register as live in. 00749 unsigned Reg = TLI.getExceptionAddressRegister(); 00750 if (Reg) BB->addLiveIn(Reg); 00751 00752 // Mark exception selector register as live in. 00753 Reg = TLI.getExceptionSelectorRegister(); 00754 if (Reg) BB->addLiveIn(Reg); 00755 00756 // FIXME: Hack around an exception handling flaw (PR1508): the personality 00757 // function and list of typeids logically belong to the invoke (or, if you 00758 // like, the basic block containing the invoke), and need to be associated 00759 // with it in the dwarf exception handling tables. Currently however the 00760 // information is provided by an intrinsic (eh.selector) that can be moved 00761 // to unexpected places by the optimizers: if the unwind edge is critical, 00762 // then breaking it can result in the intrinsics being in the successor of 00763 // the landing pad, not the landing pad itself. This results in exceptions 00764 // not being caught because no typeids are associated with the invoke. 00765 // This may not be the only way things can go wrong, but it is the only way 00766 // we try to work around for the moment. 00767 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator()); 00768 00769 if (Br && Br->isUnconditional()) { // Critical edge? 00770 BasicBlock::iterator I, E; 00771 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I) 00772 if (isa<EHSelectorInst>(I)) 00773 break; 00774 00775 if (I == E) 00776 // No catch info found - try to extract some from the successor. 00777 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo); 00778 } 00779 } 00780 00781 // Before doing SelectionDAG ISel, see if FastISel has been requested. 00782 if (FastIS && !SuppressFastISel) { 00783 // Emit code for any incoming arguments. This must happen before 00784 // beginning FastISel on the entry block. 00785 if (LLVMBB == &Fn.getEntryBlock()) { 00786 CurDAG->setRoot(SDL->getControlRoot()); 00787 CodeGenAndEmitDAG(); 00788 SDL->clear(); 00789 } 00790 FastIS->startNewBlock(BB); 00791 // Do FastISel on as many instructions as possible. 00792 for (; BI != End; ++BI) { 00793 // Just before the terminator instruction, insert instructions to 00794 // feed PHI nodes in successor blocks. 00795 if (isa<TerminatorInst>(BI)) 00796 if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) { 00797 if (EnableFastISelVerbose || EnableFastISelAbort) { 00798 cerr << "FastISel miss: "; 00799 BI->dump(); 00800 } 00801 if (EnableFastISelAbort) 00802 assert(0 && "FastISel didn't handle a PHI in a successor"); 00803 break; 00804 } 00805 00806 // First try normal tablegen-generated "fast" selection. 00807 if (FastIS->SelectInstruction(BI)) 00808 continue; 00809 00810 // Next, try calling the target to attempt to handle the instruction. 00811 if (FastIS->TargetSelectInstruction(BI)) 00812 continue; 00813 00814 // Then handle certain instructions as single-LLVM-Instruction blocks. 00815 if (isa<CallInst>(BI)) { 00816 if (EnableFastISelVerbose || EnableFastISelAbort) { 00817 cerr << "FastISel missed call: "; 00818 BI->dump(); 00819 } 00820 00821 if (BI->getType() != Type::VoidTy) { 00822 unsigned &R = FuncInfo->ValueMap[BI]; 00823 if (!R) 00824 R = FuncInfo->CreateRegForValue(BI); 00825 } 00826 00827 SelectBasicBlock(LLVMBB, BI, next(BI)); 00828 // If the instruction was codegen'd with multiple blocks, 00829 // inform the FastISel object where to resume inserting. 00830 FastIS->setCurrentBlock(BB); 00831 continue; 00832 } 00833 00834 // Otherwise, give up on FastISel for the rest of the block. 00835 // For now, be a little lenient about non-branch terminators. 00836 if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) { 00837 if (EnableFastISelVerbose || EnableFastISelAbort) { 00838 cerr << "FastISel miss: "; 00839 BI->dump(); 00840 } 00841 if (EnableFastISelAbort) 00842 // The "fast" selector couldn't handle something and bailed. 00843 // For the purpose of debugging, just abort. 00844 assert(0 && "FastISel didn't select the entire block"); 00845 } 00846 break; 00847 } 00848 } 00849 00850 // Run SelectionDAG instruction selection on the remainder of the block 00851 // not handled by FastISel. If FastISel is not run, this is the entire 00852 // block. 00853 if (BI != End) 00854 SelectBasicBlock(LLVMBB, BI, End); 00855 00856 FinishBasicBlock(); 00857 } 00858 00859 delete FastIS; 00860 } 00861 00862 void 00863 SelectionDAGISel::FinishBasicBlock() { 00864 00865 DOUT << "Target-post-processed machine code:\n"; 00866 DEBUG(BB->dump()); 00867 00868 DOUT << "Total amount of phi nodes to update: " 00869 << SDL->PHINodesToUpdate.size() << "\n"; 00870 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) 00871 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first 00872 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";); 00873 00874 // Next, now that we know what the last MBB the LLVM BB expanded is, update 00875 // PHI nodes in successors. 00876 if (SDL->SwitchCases.empty() && 00877 SDL->JTCases.empty() && 00878 SDL->BitTestCases.empty()) { 00879 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) { 00880 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first; 00881 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 00882 "This is not a machine PHI node that we are updating!"); 00883 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second, 00884 false)); 00885 PHI->addOperand(MachineOperand::CreateMBB(BB)); 00886 } 00887 SDL->PHINodesToUpdate.clear(); 00888 return; 00889 } 00890 00891 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) { 00892 // Lower header first, if it wasn't already lowered 00893 if (!SDL->BitTestCases[i].Emitted) { 00894 // Set the current basic block to the mbb we wish to insert the code into 00895 BB = SDL->BitTestCases[i].Parent; 00896 SDL->setCurrentBasicBlock(BB); 00897 // Emit the code 00898 SDL->visitBitTestHeader(SDL->BitTestCases[i]); 00899 CurDAG->setRoot(SDL->getRoot()); 00900 CodeGenAndEmitDAG(); 00901 SDL->clear(); 00902 } 00903 00904 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) { 00905 // Set the current basic block to the mbb we wish to insert the code into 00906 BB = SDL->BitTestCases[i].Cases[j].ThisBB; 00907 SDL->setCurrentBasicBlock(BB); 00908 // Emit the code 00909 if (j+1 != ej) 00910 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB, 00911 SDL->BitTestCases[i].Reg, 00912 SDL->BitTestCases[i].Cases[j]); 00913 else 00914 SDL->visitBitTestCase(SDL->BitTestCases[i].Default, 00915 SDL->BitTestCases[i].Reg, 00916 SDL->BitTestCases[i].Cases[j]); 00917 00918 00919 CurDAG->setRoot(SDL->getRoot()); 00920 CodeGenAndEmitDAG(); 00921 SDL->clear(); 00922 } 00923 00924 // Update PHI Nodes 00925 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) { 00926 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first; 00927 MachineBasicBlock *PHIBB = PHI->getParent(); 00928 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 00929 "This is not a machine PHI node that we are updating!"); 00930 // This is "default" BB. We have two jumps to it. From "header" BB and 00931 // from last "case" BB. 00932 if (PHIBB == SDL->BitTestCases[i].Default) { 00933 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 00934 false)); 00935 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent)); 00936 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 00937 false)); 00938 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases. 00939 back().ThisBB)); 00940 } 00941 // One of "cases" BB. 00942 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); 00943 j != ej; ++j) { 00944 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB; 00945 if (cBB->succ_end() != 00946 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) { 00947 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 00948 false)); 00949 PHI->addOperand(MachineOperand::CreateMBB(cBB)); 00950 } 00951 } 00952 } 00953 } 00954 SDL->BitTestCases.clear(); 00955 00956 // If the JumpTable record is filled in, then we need to emit a jump table. 00957 // Updating the PHI nodes is tricky in this case, since we need to determine 00958 // whether the PHI is a successor of the range check MBB or the jump table MBB 00959 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) { 00960 // Lower header first, if it wasn't already lowered 00961 if (!SDL->JTCases[i].first.Emitted) { 00962 // Set the current basic block to the mbb we wish to insert the code into 00963 BB = SDL->JTCases[i].first.HeaderBB; 00964 SDL->setCurrentBasicBlock(BB); 00965 // Emit the code 00966 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first); 00967 CurDAG->setRoot(SDL->getRoot()); 00968 CodeGenAndEmitDAG(); 00969 SDL->clear(); 00970 } 00971 00972 // Set the current basic block to the mbb we wish to insert the code into 00973 BB = SDL->JTCases[i].second.MBB; 00974 SDL->setCurrentBasicBlock(BB); 00975 // Emit the code 00976 SDL->visitJumpTable(SDL->JTCases[i].second); 00977 CurDAG->setRoot(SDL->getRoot()); 00978 CodeGenAndEmitDAG(); 00979 SDL->clear(); 00980 00981 // Update PHI Nodes 00982 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) { 00983 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first; 00984 MachineBasicBlock *PHIBB = PHI->getParent(); 00985 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 00986 "This is not a machine PHI node that we are updating!"); 00987 // "default" BB. We can go there only from header BB. 00988 if (PHIBB == SDL->JTCases[i].second.Default) { 00989 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 00990 false)); 00991 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB)); 00992 } 00993 // JT BB. Just iterate over successors here 00994 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) { 00995 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, 00996 false)); 00997 PHI->addOperand(MachineOperand::CreateMBB(BB)); 00998 } 00999 } 01000 } 01001 SDL->JTCases.clear(); 01002 01003 // If the switch block involved a branch to one of the actual successors, we 01004 // need to update PHI nodes in that block. 01005 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) { 01006 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first; 01007 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 01008 "This is not a machine PHI node that we are updating!"); 01009 if (BB->isSuccessor(PHI->getParent())) { 01010 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second, 01011 false)); 01012 PHI->addOperand(MachineOperand::CreateMBB(BB)); 01013 } 01014 } 01015 01016 // If we generated any switch lowering information, build and codegen any 01017 // additional DAGs necessary. 01018 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) { 01019 // Set the current basic block to the mbb we wish to insert the code into 01020 BB = SDL->SwitchCases[i].ThisBB; 01021 SDL->setCurrentBasicBlock(BB); 01022 01023 // Emit the code 01024 SDL->visitSwitchCase(SDL->SwitchCases[i]); 01025 CurDAG->setRoot(SDL->getRoot()); 01026 CodeGenAndEmitDAG(); 01027 SDL->clear(); 01028 01029 // Handle any PHI nodes in successors of this chunk, as if we were coming 01030 // from the original BB before switch expansion. Note that PHI nodes can 01031 // occur multiple times in PHINodesToUpdate. We have to be very careful to 01032 // handle them the right number of times. 01033 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS. 01034 for (MachineBasicBlock::iterator Phi = BB->begin(); 01035 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){ 01036 // This value for this PHI node is recorded in PHINodesToUpdate, get it. 01037 for (unsigned pn = 0; ; ++pn) { 01038 assert(pn != SDL->PHINodesToUpdate.size() && 01039 "Didn't find PHI entry!"); 01040 if (SDL->PHINodesToUpdate[pn].first == Phi) { 01041 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn]. 01042 second, false)); 01043 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB)); 01044 break; 01045 } 01046 } 01047 } 01048 01049 // Don't process RHS if same block as LHS. 01050 if (BB == SDL->SwitchCases[i].FalseBB) 01051 SDL->SwitchCases[i].FalseBB = 0; 01052 01053 // If we haven't handled the RHS, do so now. Otherwise, we're done. 01054 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB; 01055 SDL->SwitchCases[i].FalseBB = 0; 01056 } 01057 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0); 01058 } 01059 SDL->SwitchCases.clear(); 01060 01061 SDL->PHINodesToUpdate.clear(); 01062 } 01063 01064 01065 /// Schedule - Pick a safe ordering for instructions for each 01066 /// target node in the graph. 01067 /// 01068 ScheduleDAG *SelectionDAGISel::Schedule() { 01069 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault(); 01070 01071 if (!Ctor) { 01072 Ctor = ISHeuristic; 01073 RegisterScheduler::setDefault(Ctor); 01074 } 01075 01076 ScheduleDAG *Scheduler = Ctor(this, Fast); 01077 Scheduler->Run(CurDAG, BB, BB->end(), BB->end()); 01078 01079 return Scheduler; 01080 } 01081 01082 01083 ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() { 01084 return new ScheduleHazardRecognizer(); 01085 } 01086 01087 //===----------------------------------------------------------------------===// 01088 // Helper functions used by the generated instruction selector. 01089 //===----------------------------------------------------------------------===// 01090 // Calls to these methods are generated by tblgen. 01091 01092 /// CheckAndMask - The isel is trying to match something like (and X, 255). If 01093 /// the dag combiner simplified the 255, we still want to match. RHS is the 01094 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 01095 /// specified in the .td file (e.g. 255). 01096 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 01097 int64_t DesiredMaskS) const { 01098 const APInt &ActualMask = RHS->getAPIntValue(); 01099 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 01100 01101 // If the actual mask exactly matches, success! 01102 if (ActualMask == DesiredMask) 01103 return true; 01104 01105 // If the actual AND mask is allowing unallowed bits, this doesn't match. 01106 if (ActualMask.intersects(~DesiredMask)) 01107 return false; 01108 01109 // Otherwise, the DAG Combiner may have proven that the value coming in is 01110 // either already zero or is not demanded. Check for known zero input bits. 01111 APInt NeededMask = DesiredMask & ~ActualMask; 01112 if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) 01113 return true; 01114 01115 // TODO: check to see if missing bits are just not demanded. 01116 01117 // Otherwise, this pattern doesn't match. 01118 return false; 01119 } 01120 01121 /// CheckOrMask - The isel is trying to match something like (or X, 255). If 01122 /// the dag combiner simplified the 255, we still want to match. RHS is the 01123 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 01124 /// specified in the .td file (e.g. 255). 01125 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 01126 int64_t DesiredMaskS) const { 01127 const APInt &ActualMask = RHS->getAPIntValue(); 01128 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 01129 01130 // If the actual mask exactly matches, success! 01131 if (ActualMask == DesiredMask) 01132 return true; 01133 01134 // If the actual AND mask is allowing unallowed bits, this doesn't match. 01135 if (ActualMask.intersects(~DesiredMask)) 01136 return false; 01137 01138 // Otherwise, the DAG Combiner may have proven that the value coming in is 01139 // either already zero or is not demanded. Check for known zero input bits. 01140 APInt NeededMask = DesiredMask & ~ActualMask; 01141 01142 APInt KnownZero, KnownOne; 01143 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne); 01144 01145 // If all the missing bits in the or are already known to be set, match! 01146 if ((NeededMask & KnownOne) == NeededMask) 01147 return true; 01148 01149 // TODO: check to see if missing bits are just not demanded. 01150 01151 // Otherwise, this pattern doesn't match. 01152 return false; 01153 } 01154 01155 01156 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 01157 /// by tblgen. Others should not call it. 01158 void SelectionDAGISel:: 01159 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) { 01160 std::vector<SDValue> InOps; 01161 std::swap(InOps, Ops); 01162 01163 Ops.push_back(InOps[0]); // input chain. 01164 Ops.push_back(InOps[1]); // input asm string. 01165 01166 unsigned i = 2, e = InOps.size(); 01167 if (InOps[e-1].getValueType() == MVT::Flag) 01168 --e; // Don't process a flag operand if it is here. 01169 01170 while (i != e) { 01171 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); 01172 if ((Flags & 7) != 4 /*MEM*/) { 01173 // Just skip over this operand, copying the operands verbatim. 01174 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1); 01175 i += (Flags >> 3) + 1; 01176 } else { 01177 assert((Flags >> 3) == 1 && "Memory operand with multiple values?"); 01178 // Otherwise, this is a memory operand. Ask the target to select it. 01179 std::vector<SDValue> SelOps; 01180 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) { 01181 cerr << "Could not match memory address. Inline asm failure!\n"; 01182 exit(1); 01183 } 01184 01185 // Add this to the output node. 01186 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy(); 01187 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3), 01188 IntPtrTy)); 01189 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 01190 i += 2; 01191 } 01192 } 01193 01194 // Add the flag input back if present. 01195 if (e != InOps.size()) 01196 Ops.push_back(InOps.back()); 01197 } 01198 01199 char SelectionDAGISel::ID = 0;