SelectionDAGISel.cpp revision 30a71f593f2dc9af3ef7fa13720496d5c9d6fc1a
1//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This implements the SelectionDAGISel class. 11// 12//===----------------------------------------------------------------------===// 13 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" 48#include <algorithm> 49using namespace llvm; 50 51#ifndef NDEBUG 52static cl::opt<bool> 53ViewISelDAGs("view-isel-dags", cl::Hidden, 54 cl::desc("Pop up a window to show isel dags as they are selected")); 55static cl::opt<bool> 56ViewSchedDAGs("view-sched-dags", cl::Hidden, 57 cl::desc("Pop up a window to show sched dags as they are processed")); 58static cl::opt<bool> 59ViewSUnitDAGs("view-sunit-dags", cl::Hidden, 60 cl::desc("Pop up a window to show SUnit dags after they are processed")); 61#else 62static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0; 63#endif 64 65//===---------------------------------------------------------------------===// 66/// 67/// RegisterScheduler class - Track the registration of instruction schedulers. 68/// 69//===---------------------------------------------------------------------===// 70MachinePassRegistry RegisterScheduler::Registry; 71 72//===---------------------------------------------------------------------===// 73/// 74/// ISHeuristic command line option for instruction schedulers. 75/// 76//===---------------------------------------------------------------------===// 77namespace { 78 cl::opt<RegisterScheduler::FunctionPassCtor, false, 79 RegisterPassParser<RegisterScheduler> > 80 ISHeuristic("pre-RA-sched", 81 cl::init(&createDefaultScheduler), 82 cl::desc("Instruction schedulers available (before register" 83 " allocation):")); 84 85 static RegisterScheduler 86 defaultListDAGScheduler("default", " Best scheduler for the target", 87 createDefaultScheduler); 88} // namespace 89 90namespace { struct SDISelAsmOperandInfo; } 91 92namespace { 93 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of 94 /// MVT::ValueTypes that represent all the individual underlying 95 /// non-aggregate types that comprise it. 96 static void ComputeValueVTs(const TargetLowering &TLI, 97 const Type *Ty, 98 SmallVectorImpl<MVT::ValueType> &ValueVTs) { 99 // Given a struct type, recursively traverse the elements. 100 if (const StructType *STy = dyn_cast<StructType>(Ty)) { 101 for (StructType::element_iterator EI = STy->element_begin(), 102 EB = STy->element_end(); 103 EI != EB; ++EI) 104 ComputeValueVTs(TLI, *EI, ValueVTs); 105 return; 106 } 107 // Given an array type, recursively traverse the elements. 108 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 109 const Type *EltTy = ATy->getElementType(); 110 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 111 ComputeValueVTs(TLI, EltTy, ValueVTs); 112 return; 113 } 114 // Base case: we can get an MVT::ValueType for this LLVM IR type. 115 MVT::ValueType VT = TLI.getValueType(Ty); 116 ValueVTs.push_back(VT); 117 } 118 119 /// RegsForValue - This struct represents the physical registers that a 120 /// particular value is assigned and the type information about the value. 121 /// This is needed because values can be promoted into larger registers and 122 /// expanded into multiple smaller registers than the value. 123 struct VISIBILITY_HIDDEN RegsForValue { 124 /// TLI - The TargetLowering object. 125 const TargetLowering *TLI; 126 127 /// Regs - This list holds the register (for legal and promoted values) 128 /// or register set (for expanded values) that the value should be assigned 129 /// to. 130 std::vector<unsigned> Regs; 131 132 /// RegVTs - The value types of the registers. This is the same size 133 /// as ValueVTs; every register contributing to a given value must 134 /// have the same type. When Regs contains all virtual registers, the 135 /// contents of RegVTs is redundant with TLI's getRegisterType member 136 /// function, however when Regs contains physical registers, it is 137 /// necessary to have a separate record of the types. 138 /// 139 SmallVector<MVT::ValueType, 4> RegVTs; 140 141 /// ValueVTs - The value types of the values, which may be promoted 142 /// or synthesized from one or more registers. 143 SmallVector<MVT::ValueType, 4> ValueVTs; 144 145 RegsForValue() : TLI(0) {} 146 147 RegsForValue(const TargetLowering &tli, 148 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt) 149 : TLI(&tli), Regs(1, Reg), RegVTs(1, regvt), ValueVTs(1, valuevt) {} 150 RegsForValue(const TargetLowering &tli, 151 const std::vector<unsigned> ®s, 152 MVT::ValueType regvt, MVT::ValueType valuevt) 153 : TLI(&tli), Regs(regs), RegVTs(1, regvt), ValueVTs(1, valuevt) {} 154 RegsForValue(const TargetLowering &tli, 155 const std::vector<unsigned> ®s, 156 const SmallVector<MVT::ValueType, 4> ®vts, 157 const SmallVector<MVT::ValueType, 4> &valuevts) 158 : TLI(&tli), Regs(regs), RegVTs(regvts), ValueVTs(valuevts) {} 159 RegsForValue(const TargetLowering &tli, 160 unsigned Reg, const Type *Ty) : TLI(&tli) { 161 ComputeValueVTs(tli, Ty, ValueVTs); 162 163 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) { 164 MVT::ValueType ValueVT = ValueVTs[Value]; 165 unsigned NumRegs = TLI->getNumRegisters(ValueVT); 166 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT); 167 for (unsigned i = 0; i != NumRegs; ++i) 168 Regs.push_back(Reg + i); 169 RegVTs.push_back(RegisterVT); 170 Reg += NumRegs; 171 } 172 } 173 174 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 175 /// this value and returns the result as a ValueVTs value. This uses 176 /// Chain/Flag as the input and updates them for the output Chain/Flag. 177 /// If the Flag pointer is NULL, no flag is used. 178 SDOperand getCopyFromRegs(SelectionDAG &DAG, 179 SDOperand &Chain, SDOperand *Flag) const; 180 181 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 182 /// specified value into the registers specified by this object. This uses 183 /// Chain/Flag as the input and updates them for the output Chain/Flag. 184 /// If the Flag pointer is NULL, no flag is used. 185 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG, 186 SDOperand &Chain, SDOperand *Flag) const; 187 188 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 189 /// operand list. This adds the code marker and includes the number of 190 /// values added into it. 191 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG, 192 std::vector<SDOperand> &Ops) const; 193 }; 194} 195 196namespace llvm { 197 //===--------------------------------------------------------------------===// 198 /// createDefaultScheduler - This creates an instruction scheduler appropriate 199 /// for the target. 200 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS, 201 SelectionDAG *DAG, 202 MachineBasicBlock *BB) { 203 TargetLowering &TLI = IS->getTargetLowering(); 204 205 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) { 206 return createTDListDAGScheduler(IS, DAG, BB); 207 } else { 208 assert(TLI.getSchedulingPreference() == 209 TargetLowering::SchedulingForRegPressure && "Unknown sched type!"); 210 return createBURRListDAGScheduler(IS, DAG, BB); 211 } 212 } 213 214 215 //===--------------------------------------------------------------------===// 216 /// FunctionLoweringInfo - This contains information that is global to a 217 /// function that is used when lowering a region of the function. 218 class FunctionLoweringInfo { 219 public: 220 TargetLowering &TLI; 221 Function &Fn; 222 MachineFunction &MF; 223 MachineRegisterInfo &RegInfo; 224 225 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF); 226 227 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry. 228 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap; 229 230 /// ValueMap - Since we emit code for the function a basic block at a time, 231 /// we must remember which virtual registers hold the values for 232 /// cross-basic-block values. 233 DenseMap<const Value*, unsigned> ValueMap; 234 235 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in 236 /// the entry block. This allows the allocas to be efficiently referenced 237 /// anywhere in the function. 238 std::map<const AllocaInst*, int> StaticAllocaMap; 239 240#ifndef NDEBUG 241 SmallSet<Instruction*, 8> CatchInfoLost; 242 SmallSet<Instruction*, 8> CatchInfoFound; 243#endif 244 245 unsigned MakeReg(MVT::ValueType VT) { 246 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT)); 247 } 248 249 /// isExportedInst - Return true if the specified value is an instruction 250 /// exported from its block. 251 bool isExportedInst(const Value *V) { 252 return ValueMap.count(V); 253 } 254 255 unsigned CreateRegForValue(const Value *V); 256 257 unsigned InitializeRegForValue(const Value *V) { 258 unsigned &R = ValueMap[V]; 259 assert(R == 0 && "Already initialized this value register!"); 260 return R = CreateRegForValue(V); 261 } 262 }; 263} 264 265/// isSelector - Return true if this instruction is a call to the 266/// eh.selector intrinsic. 267static bool isSelector(Instruction *I) { 268 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 269 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 || 270 II->getIntrinsicID() == Intrinsic::eh_selector_i64); 271 return false; 272} 273 274/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by 275/// PHI nodes or outside of the basic block that defines it, or used by a 276/// switch or atomic instruction, which may expand to multiple basic blocks. 277static bool isUsedOutsideOfDefiningBlock(Instruction *I) { 278 if (isa<PHINode>(I)) return true; 279 BasicBlock *BB = I->getParent(); 280 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) 281 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) || 282 // FIXME: Remove switchinst special case. 283 isa<SwitchInst>(*UI)) 284 return true; 285 return false; 286} 287 288/// isOnlyUsedInEntryBlock - If the specified argument is only used in the 289/// entry block, return true. This includes arguments used by switches, since 290/// the switch may expand into multiple basic blocks. 291static bool isOnlyUsedInEntryBlock(Argument *A) { 292 BasicBlock *Entry = A->getParent()->begin(); 293 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI) 294 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI)) 295 return false; // Use not in entry block. 296 return true; 297} 298 299FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli, 300 Function &fn, MachineFunction &mf) 301 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) { 302 303 // Create a vreg for each argument register that is not dead and is used 304 // outside of the entry block for the function. 305 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end(); 306 AI != E; ++AI) 307 if (!isOnlyUsedInEntryBlock(AI)) 308 InitializeRegForValue(AI); 309 310 // Initialize the mapping of values to registers. This is only set up for 311 // instruction values that are used outside of the block that defines 312 // them. 313 Function::iterator BB = Fn.begin(), EB = Fn.end(); 314 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 315 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 316 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) { 317 const Type *Ty = AI->getAllocatedType(); 318 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty); 319 unsigned Align = 320 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 321 AI->getAlignment()); 322 323 TySize *= CUI->getZExtValue(); // Get total allocated size. 324 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects. 325 StaticAllocaMap[AI] = 326 MF.getFrameInfo()->CreateStackObject(TySize, Align); 327 } 328 329 for (; BB != EB; ++BB) 330 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 331 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I)) 332 if (!isa<AllocaInst>(I) || 333 !StaticAllocaMap.count(cast<AllocaInst>(I))) 334 InitializeRegForValue(I); 335 336 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This 337 // also creates the initial PHI MachineInstrs, though none of the input 338 // operands are populated. 339 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) { 340 MachineBasicBlock *MBB = new MachineBasicBlock(BB); 341 MBBMap[BB] = MBB; 342 MF.getBasicBlockList().push_back(MBB); 343 344 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as 345 // appropriate. 346 PHINode *PN; 347 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){ 348 if (PN->use_empty()) continue; 349 350 MVT::ValueType VT = TLI.getValueType(PN->getType()); 351 unsigned NumRegisters = TLI.getNumRegisters(VT); 352 unsigned PHIReg = ValueMap[PN]; 353 assert(PHIReg && "PHI node does not have an assigned virtual register!"); 354 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo(); 355 for (unsigned i = 0; i != NumRegisters; ++i) 356 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i); 357 } 358 } 359} 360 361/// CreateRegForValue - Allocate the appropriate number of virtual registers of 362/// the correctly promoted or expanded types. Assign these registers 363/// consecutive vreg numbers and return the first assigned number. 364unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) { 365 const Type *Ty = V->getType(); 366 SmallVector<MVT::ValueType, 4> ValueVTs; 367 ComputeValueVTs(TLI, Ty, ValueVTs); 368 369 unsigned FirstReg = 0; 370 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) { 371 MVT::ValueType ValueVT = ValueVTs[Value]; 372 unsigned NumRegs = TLI.getNumRegisters(ValueVT); 373 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT); 374 375 for (unsigned i = 0; i != NumRegs; ++i) { 376 unsigned R = MakeReg(RegisterVT); 377 if (!FirstReg) FirstReg = R; 378 } 379 } 380 return FirstReg; 381} 382 383//===----------------------------------------------------------------------===// 384/// SelectionDAGLowering - This is the common target-independent lowering 385/// implementation that is parameterized by a TargetLowering object. 386/// Also, targets can overload any lowering method. 387/// 388namespace llvm { 389class SelectionDAGLowering { 390 MachineBasicBlock *CurMBB; 391 392 DenseMap<const Value*, SDOperand> NodeMap; 393 394 /// PendingLoads - Loads are not emitted to the program immediately. We bunch 395 /// them up and then emit token factor nodes when possible. This allows us to 396 /// get simple disambiguation between loads without worrying about alias 397 /// analysis. 398 std::vector<SDOperand> PendingLoads; 399 400 /// PendingExports - CopyToReg nodes that copy values to virtual registers 401 /// for export to other blocks need to be emitted before any terminator 402 /// instruction, but they have no other ordering requirements. We bunch them 403 /// up and the emit a single tokenfactor for them just before terminator 404 /// instructions. 405 std::vector<SDOperand> PendingExports; 406 407 /// Case - A struct to record the Value for a switch case, and the 408 /// case's target basic block. 409 struct Case { 410 Constant* Low; 411 Constant* High; 412 MachineBasicBlock* BB; 413 414 Case() : Low(0), High(0), BB(0) { } 415 Case(Constant* low, Constant* high, MachineBasicBlock* bb) : 416 Low(low), High(high), BB(bb) { } 417 uint64_t size() const { 418 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue(); 419 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue(); 420 return (rHigh - rLow + 1ULL); 421 } 422 }; 423 424 struct CaseBits { 425 uint64_t Mask; 426 MachineBasicBlock* BB; 427 unsigned Bits; 428 429 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits): 430 Mask(mask), BB(bb), Bits(bits) { } 431 }; 432 433 typedef std::vector<Case> CaseVector; 434 typedef std::vector<CaseBits> CaseBitsVector; 435 typedef CaseVector::iterator CaseItr; 436 typedef std::pair<CaseItr, CaseItr> CaseRange; 437 438 /// CaseRec - A struct with ctor used in lowering switches to a binary tree 439 /// of conditional branches. 440 struct CaseRec { 441 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) : 442 CaseBB(bb), LT(lt), GE(ge), Range(r) {} 443 444 /// CaseBB - The MBB in which to emit the compare and branch 445 MachineBasicBlock *CaseBB; 446 /// LT, GE - If nonzero, we know the current case value must be less-than or 447 /// greater-than-or-equal-to these Constants. 448 Constant *LT; 449 Constant *GE; 450 /// Range - A pair of iterators representing the range of case values to be 451 /// processed at this point in the binary search tree. 452 CaseRange Range; 453 }; 454 455 typedef std::vector<CaseRec> CaseRecVector; 456 457 /// The comparison function for sorting the switch case values in the vector. 458 /// WARNING: Case ranges should be disjoint! 459 struct CaseCmp { 460 bool operator () (const Case& C1, const Case& C2) { 461 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High)); 462 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low); 463 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High); 464 return CI1->getValue().slt(CI2->getValue()); 465 } 466 }; 467 468 struct CaseBitsCmp { 469 bool operator () (const CaseBits& C1, const CaseBits& C2) { 470 return C1.Bits > C2.Bits; 471 } 472 }; 473 474 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI); 475 476public: 477 // TLI - This is information that describes the available target features we 478 // need for lowering. This indicates when operations are unavailable, 479 // implemented with a libcall, etc. 480 TargetLowering &TLI; 481 SelectionDAG &DAG; 482 const TargetData *TD; 483 AliasAnalysis &AA; 484 485 /// SwitchCases - Vector of CaseBlock structures used to communicate 486 /// SwitchInst code generation information. 487 std::vector<SelectionDAGISel::CaseBlock> SwitchCases; 488 /// JTCases - Vector of JumpTable structures used to communicate 489 /// SwitchInst code generation information. 490 std::vector<SelectionDAGISel::JumpTableBlock> JTCases; 491 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases; 492 493 /// FuncInfo - Information about the function as a whole. 494 /// 495 FunctionLoweringInfo &FuncInfo; 496 497 /// GCI - Garbage collection metadata for the function. 498 CollectorMetadata *GCI; 499 500 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli, 501 AliasAnalysis &aa, 502 FunctionLoweringInfo &funcinfo, 503 CollectorMetadata *gci) 504 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa), 505 FuncInfo(funcinfo), GCI(gci) { 506 } 507 508 /// getRoot - Return the current virtual root of the Selection DAG, 509 /// flushing any PendingLoad items. This must be done before emitting 510 /// a store or any other node that may need to be ordered after any 511 /// prior load instructions. 512 /// 513 SDOperand getRoot() { 514 if (PendingLoads.empty()) 515 return DAG.getRoot(); 516 517 if (PendingLoads.size() == 1) { 518 SDOperand Root = PendingLoads[0]; 519 DAG.setRoot(Root); 520 PendingLoads.clear(); 521 return Root; 522 } 523 524 // Otherwise, we have to make a token factor node. 525 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, 526 &PendingLoads[0], PendingLoads.size()); 527 PendingLoads.clear(); 528 DAG.setRoot(Root); 529 return Root; 530 } 531 532 /// getControlRoot - Similar to getRoot, but instead of flushing all the 533 /// PendingLoad items, flush all the PendingExports items. It is necessary 534 /// to do this before emitting a terminator instruction. 535 /// 536 SDOperand getControlRoot() { 537 SDOperand Root = DAG.getRoot(); 538 539 if (PendingExports.empty()) 540 return Root; 541 542 // Turn all of the CopyToReg chains into one factored node. 543 if (Root.getOpcode() != ISD::EntryToken) { 544 unsigned i = 0, e = PendingExports.size(); 545 for (; i != e; ++i) { 546 assert(PendingExports[i].Val->getNumOperands() > 1); 547 if (PendingExports[i].Val->getOperand(0) == Root) 548 break; // Don't add the root if we already indirectly depend on it. 549 } 550 551 if (i == e) 552 PendingExports.push_back(Root); 553 } 554 555 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, 556 &PendingExports[0], 557 PendingExports.size()); 558 PendingExports.clear(); 559 DAG.setRoot(Root); 560 return Root; 561 } 562 563 void CopyValueToVirtualRegister(Value *V, unsigned Reg); 564 565 void visit(Instruction &I) { visit(I.getOpcode(), I); } 566 567 void visit(unsigned Opcode, User &I) { 568 // Note: this doesn't use InstVisitor, because it has to work with 569 // ConstantExpr's in addition to instructions. 570 switch (Opcode) { 571 default: assert(0 && "Unknown instruction type encountered!"); 572 abort(); 573 // Build the switch statement using the Instruction.def file. 574#define HANDLE_INST(NUM, OPCODE, CLASS) \ 575 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I); 576#include "llvm/Instruction.def" 577 } 578 } 579 580 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; } 581 582 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr, 583 const Value *SV, SDOperand Root, 584 bool isVolatile, unsigned Alignment); 585 586 SDOperand getValue(const Value *V); 587 588 void setValue(const Value *V, SDOperand NewN) { 589 SDOperand &N = NodeMap[V]; 590 assert(N.Val == 0 && "Already set a value for this node!"); 591 N = NewN; 592 } 593 594 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber, 595 std::set<unsigned> &OutputRegs, 596 std::set<unsigned> &InputRegs); 597 598 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB, 599 MachineBasicBlock *FBB, MachineBasicBlock *CurBB, 600 unsigned Opc); 601 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB); 602 void ExportFromCurrentBlock(Value *V); 603 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall, 604 MachineBasicBlock *LandingPad = NULL); 605 606 // Terminator instructions. 607 void visitRet(ReturnInst &I); 608 void visitBr(BranchInst &I); 609 void visitSwitch(SwitchInst &I); 610 void visitUnreachable(UnreachableInst &I) { /* noop */ } 611 612 // Helpers for visitSwitch 613 bool handleSmallSwitchRange(CaseRec& CR, 614 CaseRecVector& WorkList, 615 Value* SV, 616 MachineBasicBlock* Default); 617 bool handleJTSwitchCase(CaseRec& CR, 618 CaseRecVector& WorkList, 619 Value* SV, 620 MachineBasicBlock* Default); 621 bool handleBTSplitSwitchCase(CaseRec& CR, 622 CaseRecVector& WorkList, 623 Value* SV, 624 MachineBasicBlock* Default); 625 bool handleBitTestsSwitchCase(CaseRec& CR, 626 CaseRecVector& WorkList, 627 Value* SV, 628 MachineBasicBlock* Default); 629 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB); 630 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B); 631 void visitBitTestCase(MachineBasicBlock* NextMBB, 632 unsigned Reg, 633 SelectionDAGISel::BitTestCase &B); 634 void visitJumpTable(SelectionDAGISel::JumpTable &JT); 635 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT, 636 SelectionDAGISel::JumpTableHeader &JTH); 637 638 // These all get lowered before this pass. 639 void visitInvoke(InvokeInst &I); 640 void visitUnwind(UnwindInst &I); 641 642 void visitBinary(User &I, unsigned OpCode); 643 void visitShift(User &I, unsigned Opcode); 644 void visitAdd(User &I) { 645 if (I.getType()->isFPOrFPVector()) 646 visitBinary(I, ISD::FADD); 647 else 648 visitBinary(I, ISD::ADD); 649 } 650 void visitSub(User &I); 651 void visitMul(User &I) { 652 if (I.getType()->isFPOrFPVector()) 653 visitBinary(I, ISD::FMUL); 654 else 655 visitBinary(I, ISD::MUL); 656 } 657 void visitURem(User &I) { visitBinary(I, ISD::UREM); } 658 void visitSRem(User &I) { visitBinary(I, ISD::SREM); } 659 void visitFRem(User &I) { visitBinary(I, ISD::FREM); } 660 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); } 661 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); } 662 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); } 663 void visitAnd (User &I) { visitBinary(I, ISD::AND); } 664 void visitOr (User &I) { visitBinary(I, ISD::OR); } 665 void visitXor (User &I) { visitBinary(I, ISD::XOR); } 666 void visitShl (User &I) { visitShift(I, ISD::SHL); } 667 void visitLShr(User &I) { visitShift(I, ISD::SRL); } 668 void visitAShr(User &I) { visitShift(I, ISD::SRA); } 669 void visitICmp(User &I); 670 void visitFCmp(User &I); 671 // Visit the conversion instructions 672 void visitTrunc(User &I); 673 void visitZExt(User &I); 674 void visitSExt(User &I); 675 void visitFPTrunc(User &I); 676 void visitFPExt(User &I); 677 void visitFPToUI(User &I); 678 void visitFPToSI(User &I); 679 void visitUIToFP(User &I); 680 void visitSIToFP(User &I); 681 void visitPtrToInt(User &I); 682 void visitIntToPtr(User &I); 683 void visitBitCast(User &I); 684 685 void visitExtractElement(User &I); 686 void visitInsertElement(User &I); 687 void visitShuffleVector(User &I); 688 689 void visitGetElementPtr(User &I); 690 void visitSelect(User &I); 691 692 void visitMalloc(MallocInst &I); 693 void visitFree(FreeInst &I); 694 void visitAlloca(AllocaInst &I); 695 void visitLoad(LoadInst &I); 696 void visitStore(StoreInst &I); 697 void visitPHI(PHINode &I) { } // PHI nodes are handled specially. 698 void visitCall(CallInst &I); 699 void visitInlineAsm(CallSite CS); 700 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic); 701 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic); 702 703 void visitVAStart(CallInst &I); 704 void visitVAArg(VAArgInst &I); 705 void visitVAEnd(CallInst &I); 706 void visitVACopy(CallInst &I); 707 708 void visitGetResult(GetResultInst &I); 709 710 void visitUserOp1(Instruction &I) { 711 assert(0 && "UserOp1 should not exist at instruction selection time!"); 712 abort(); 713 } 714 void visitUserOp2(Instruction &I) { 715 assert(0 && "UserOp2 should not exist at instruction selection time!"); 716 abort(); 717 } 718}; 719} // end namespace llvm 720 721 722/// getCopyFromParts - Create a value that contains the specified legal parts 723/// combined into the value they represent. If the parts combine to a type 724/// larger then ValueVT then AssertOp can be used to specify whether the extra 725/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 726/// (ISD::AssertSext). 727static SDOperand getCopyFromParts(SelectionDAG &DAG, 728 const SDOperand *Parts, 729 unsigned NumParts, 730 MVT::ValueType PartVT, 731 MVT::ValueType ValueVT, 732 ISD::NodeType AssertOp = ISD::DELETED_NODE) { 733 assert(NumParts > 0 && "No parts to assemble!"); 734 TargetLowering &TLI = DAG.getTargetLoweringInfo(); 735 SDOperand Val = Parts[0]; 736 737 if (NumParts > 1) { 738 // Assemble the value from multiple parts. 739 if (!MVT::isVector(ValueVT)) { 740 unsigned PartBits = MVT::getSizeInBits(PartVT); 741 unsigned ValueBits = MVT::getSizeInBits(ValueVT); 742 743 // Assemble the power of 2 part. 744 unsigned RoundParts = NumParts & (NumParts - 1) ? 745 1 << Log2_32(NumParts) : NumParts; 746 unsigned RoundBits = PartBits * RoundParts; 747 MVT::ValueType RoundVT = RoundBits == ValueBits ? 748 ValueVT : MVT::getIntegerType(RoundBits); 749 SDOperand Lo, Hi; 750 751 if (RoundParts > 2) { 752 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2); 753 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT); 754 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2, 755 PartVT, HalfVT); 756 } else { 757 Lo = Parts[0]; 758 Hi = Parts[1]; 759 } 760 if (TLI.isBigEndian()) 761 std::swap(Lo, Hi); 762 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi); 763 764 if (RoundParts < NumParts) { 765 // Assemble the trailing non-power-of-2 part. 766 unsigned OddParts = NumParts - RoundParts; 767 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits); 768 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT); 769 770 // Combine the round and odd parts. 771 Lo = Val; 772 if (TLI.isBigEndian()) 773 std::swap(Lo, Hi); 774 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits); 775 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi); 776 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi, 777 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()), 778 TLI.getShiftAmountTy())); 779 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo); 780 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi); 781 } 782 } else { 783 // Handle a multi-element vector. 784 MVT::ValueType IntermediateVT, RegisterVT; 785 unsigned NumIntermediates; 786 unsigned NumRegs = 787 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates, 788 RegisterVT); 789 790 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 791 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 792 assert(RegisterVT == Parts[0].getValueType() && 793 "Part type doesn't match part!"); 794 795 // Assemble the parts into intermediate operands. 796 SmallVector<SDOperand, 8> Ops(NumIntermediates); 797 if (NumIntermediates == NumParts) { 798 // If the register was not expanded, truncate or copy the value, 799 // as appropriate. 800 for (unsigned i = 0; i != NumParts; ++i) 801 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1, 802 PartVT, IntermediateVT); 803 } else if (NumParts > 0) { 804 // If the intermediate type was expanded, build the intermediate operands 805 // from the parts. 806 assert(NumParts % NumIntermediates == 0 && 807 "Must expand into a divisible number of parts!"); 808 unsigned Factor = NumParts / NumIntermediates; 809 for (unsigned i = 0; i != NumIntermediates; ++i) 810 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor, 811 PartVT, IntermediateVT); 812 } 813 814 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate 815 // operands. 816 Val = DAG.getNode(MVT::isVector(IntermediateVT) ? 817 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 818 ValueVT, &Ops[0], NumIntermediates); 819 } 820 } 821 822 // There is now one part, held in Val. Correct it to match ValueVT. 823 PartVT = Val.getValueType(); 824 825 if (PartVT == ValueVT) 826 return Val; 827 828 if (MVT::isVector(PartVT)) { 829 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!"); 830 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val); 831 } 832 833 if (MVT::isVector(ValueVT)) { 834 assert(MVT::getVectorElementType(ValueVT) == PartVT && 835 MVT::getVectorNumElements(ValueVT) == 1 && 836 "Only trivial scalar-to-vector conversions should get here!"); 837 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val); 838 } 839 840 if (MVT::isInteger(PartVT) && 841 MVT::isInteger(ValueVT)) { 842 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) { 843 // For a truncate, see if we have any information to 844 // indicate whether the truncated bits will always be 845 // zero or sign-extension. 846 if (AssertOp != ISD::DELETED_NODE) 847 Val = DAG.getNode(AssertOp, PartVT, Val, 848 DAG.getValueType(ValueVT)); 849 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val); 850 } else { 851 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val); 852 } 853 } 854 855 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) { 856 if (ValueVT < Val.getValueType()) 857 // FP_ROUND's are always exact here. 858 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val, 859 DAG.getIntPtrConstant(1)); 860 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val); 861 } 862 863 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT)) 864 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val); 865 866 assert(0 && "Unknown mismatch!"); 867 return SDOperand(); 868} 869 870/// getCopyToParts - Create a series of nodes that contain the specified value 871/// split into legal parts. If the parts contain more bits than Val, then, for 872/// integers, ExtendKind can be used to specify how to generate the extra bits. 873static void getCopyToParts(SelectionDAG &DAG, 874 SDOperand Val, 875 SDOperand *Parts, 876 unsigned NumParts, 877 MVT::ValueType PartVT, 878 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 879 TargetLowering &TLI = DAG.getTargetLoweringInfo(); 880 MVT::ValueType PtrVT = TLI.getPointerTy(); 881 MVT::ValueType ValueVT = Val.getValueType(); 882 unsigned PartBits = MVT::getSizeInBits(PartVT); 883 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!"); 884 885 if (!NumParts) 886 return; 887 888 if (!MVT::isVector(ValueVT)) { 889 if (PartVT == ValueVT) { 890 assert(NumParts == 1 && "No-op copy with multiple parts!"); 891 Parts[0] = Val; 892 return; 893 } 894 895 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) { 896 // If the parts cover more bits than the value has, promote the value. 897 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) { 898 assert(NumParts == 1 && "Do not know what to promote to!"); 899 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val); 900 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) { 901 ValueVT = MVT::getIntegerType(NumParts * PartBits); 902 Val = DAG.getNode(ExtendKind, ValueVT, Val); 903 } else { 904 assert(0 && "Unknown mismatch!"); 905 } 906 } else if (PartBits == MVT::getSizeInBits(ValueVT)) { 907 // Different types of the same size. 908 assert(NumParts == 1 && PartVT != ValueVT); 909 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val); 910 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) { 911 // If the parts cover less bits than value has, truncate the value. 912 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) { 913 ValueVT = MVT::getIntegerType(NumParts * PartBits); 914 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val); 915 } else { 916 assert(0 && "Unknown mismatch!"); 917 } 918 } 919 920 // The value may have changed - recompute ValueVT. 921 ValueVT = Val.getValueType(); 922 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) && 923 "Failed to tile the value with PartVT!"); 924 925 if (NumParts == 1) { 926 assert(PartVT == ValueVT && "Type conversion failed!"); 927 Parts[0] = Val; 928 return; 929 } 930 931 // Expand the value into multiple parts. 932 if (NumParts & (NumParts - 1)) { 933 // The number of parts is not a power of 2. Split off and copy the tail. 934 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) && 935 "Do not know what to expand to!"); 936 unsigned RoundParts = 1 << Log2_32(NumParts); 937 unsigned RoundBits = RoundParts * PartBits; 938 unsigned OddParts = NumParts - RoundParts; 939 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val, 940 DAG.getConstant(RoundBits, 941 TLI.getShiftAmountTy())); 942 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT); 943 if (TLI.isBigEndian()) 944 // The odd parts were reversed by getCopyToParts - unreverse them. 945 std::reverse(Parts + RoundParts, Parts + NumParts); 946 NumParts = RoundParts; 947 ValueVT = MVT::getIntegerType(NumParts * PartBits); 948 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val); 949 } 950 951 // The number of parts is a power of 2. Repeatedly bisect the value using 952 // EXTRACT_ELEMENT. 953 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, 954 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)), 955 Val); 956 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 957 for (unsigned i = 0; i < NumParts; i += StepSize) { 958 unsigned ThisBits = StepSize * PartBits / 2; 959 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits); 960 SDOperand &Part0 = Parts[i]; 961 SDOperand &Part1 = Parts[i+StepSize/2]; 962 963 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0, 964 DAG.getConstant(1, PtrVT)); 965 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0, 966 DAG.getConstant(0, PtrVT)); 967 968 if (ThisBits == PartBits && ThisVT != PartVT) { 969 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0); 970 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1); 971 } 972 } 973 } 974 975 if (TLI.isBigEndian()) 976 std::reverse(Parts, Parts + NumParts); 977 978 return; 979 } 980 981 // Vector ValueVT. 982 if (NumParts == 1) { 983 if (PartVT != ValueVT) { 984 if (MVT::isVector(PartVT)) { 985 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val); 986 } else { 987 assert(MVT::getVectorElementType(ValueVT) == PartVT && 988 MVT::getVectorNumElements(ValueVT) == 1 && 989 "Only trivial vector-to-scalar conversions should get here!"); 990 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val, 991 DAG.getConstant(0, PtrVT)); 992 } 993 } 994 995 Parts[0] = Val; 996 return; 997 } 998 999 // Handle a multi-element vector. 1000 MVT::ValueType IntermediateVT, RegisterVT; 1001 unsigned NumIntermediates; 1002 unsigned NumRegs = 1003 DAG.getTargetLoweringInfo() 1004 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates, 1005 RegisterVT); 1006 unsigned NumElements = MVT::getVectorNumElements(ValueVT); 1007 1008 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 1009 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 1010 1011 // Split the vector into intermediate operands. 1012 SmallVector<SDOperand, 8> Ops(NumIntermediates); 1013 for (unsigned i = 0; i != NumIntermediates; ++i) 1014 if (MVT::isVector(IntermediateVT)) 1015 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, 1016 IntermediateVT, Val, 1017 DAG.getConstant(i * (NumElements / NumIntermediates), 1018 PtrVT)); 1019 else 1020 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 1021 IntermediateVT, Val, 1022 DAG.getConstant(i, PtrVT)); 1023 1024 // Split the intermediate operands into legal parts. 1025 if (NumParts == NumIntermediates) { 1026 // If the register was not expanded, promote or copy the value, 1027 // as appropriate. 1028 for (unsigned i = 0; i != NumParts; ++i) 1029 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT); 1030 } else if (NumParts > 0) { 1031 // If the intermediate type was expanded, split each the value into 1032 // legal parts. 1033 assert(NumParts % NumIntermediates == 0 && 1034 "Must expand into a divisible number of parts!"); 1035 unsigned Factor = NumParts / NumIntermediates; 1036 for (unsigned i = 0; i != NumIntermediates; ++i) 1037 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT); 1038 } 1039} 1040 1041 1042SDOperand SelectionDAGLowering::getValue(const Value *V) { 1043 SDOperand &N = NodeMap[V]; 1044 if (N.Val) return N; 1045 1046 const Type *VTy = V->getType(); 1047 MVT::ValueType VT = TLI.getValueType(VTy, true); 1048 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) { 1049 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1050 visit(CE->getOpcode(), *CE); 1051 SDOperand N1 = NodeMap[V]; 1052 assert(N1.Val && "visit didn't populate the ValueMap!"); 1053 return N1; 1054 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) { 1055 return N = DAG.getGlobalAddress(GV, VT); 1056 } else if (isa<ConstantPointerNull>(C)) { 1057 return N = DAG.getConstant(0, TLI.getPointerTy()); 1058 } else if (isa<UndefValue>(C)) { 1059 if (!isa<VectorType>(VTy)) 1060 return N = DAG.getNode(ISD::UNDEF, VT); 1061 1062 // Create a BUILD_VECTOR of undef nodes. 1063 const VectorType *PTy = cast<VectorType>(VTy); 1064 unsigned NumElements = PTy->getNumElements(); 1065 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 1066 1067 SmallVector<SDOperand, 8> Ops; 1068 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT)); 1069 1070 // Create a VConstant node with generic Vector type. 1071 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements); 1072 return N = DAG.getNode(ISD::BUILD_VECTOR, VT, 1073 &Ops[0], Ops.size()); 1074 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 1075 return N = DAG.getConstantFP(CFP->getValueAPF(), VT); 1076 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) { 1077 unsigned NumElements = PTy->getNumElements(); 1078 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 1079 1080 // Now that we know the number and type of the elements, push a 1081 // Constant or ConstantFP node onto the ops list for each element of 1082 // the vector constant. 1083 SmallVector<SDOperand, 8> Ops; 1084 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) { 1085 for (unsigned i = 0; i != NumElements; ++i) 1086 Ops.push_back(getValue(CP->getOperand(i))); 1087 } else { 1088 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1089 SDOperand Op; 1090 if (MVT::isFloatingPoint(PVT)) 1091 Op = DAG.getConstantFP(0, PVT); 1092 else 1093 Op = DAG.getConstant(0, PVT); 1094 Ops.assign(NumElements, Op); 1095 } 1096 1097 // Create a BUILD_VECTOR node. 1098 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements); 1099 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], 1100 Ops.size()); 1101 } else { 1102 // Canonicalize all constant ints to be unsigned. 1103 return N = DAG.getConstant(cast<ConstantInt>(C)->getValue(),VT); 1104 } 1105 } 1106 1107 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1108 std::map<const AllocaInst*, int>::iterator SI = 1109 FuncInfo.StaticAllocaMap.find(AI); 1110 if (SI != FuncInfo.StaticAllocaMap.end()) 1111 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 1112 } 1113 1114 unsigned InReg = FuncInfo.ValueMap[V]; 1115 assert(InReg && "Value not in map!"); 1116 1117 RegsForValue RFV(TLI, InReg, VTy); 1118 SDOperand Chain = DAG.getEntryNode(); 1119 1120 return RFV.getCopyFromRegs(DAG, Chain, NULL); 1121} 1122 1123 1124void SelectionDAGLowering::visitRet(ReturnInst &I) { 1125 if (I.getNumOperands() == 0) { 1126 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot())); 1127 return; 1128 } 1129 SmallVector<SDOperand, 8> NewValues; 1130 NewValues.push_back(getControlRoot()); 1131 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 1132 SDOperand RetOp = getValue(I.getOperand(i)); 1133 MVT::ValueType VT = RetOp.getValueType(); 1134 1135 // FIXME: C calling convention requires the return type to be promoted to 1136 // at least 32-bit. But this is not necessary for non-C calling conventions. 1137 if (MVT::isInteger(VT)) { 1138 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32); 1139 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT)) 1140 VT = MinVT; 1141 } 1142 1143 unsigned NumParts = TLI.getNumRegisters(VT); 1144 MVT::ValueType PartVT = TLI.getRegisterType(VT); 1145 SmallVector<SDOperand, 4> Parts(NumParts); 1146 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1147 1148 const Function *F = I.getParent()->getParent(); 1149 if (F->paramHasAttr(0, ParamAttr::SExt)) 1150 ExtendKind = ISD::SIGN_EXTEND; 1151 else if (F->paramHasAttr(0, ParamAttr::ZExt)) 1152 ExtendKind = ISD::ZERO_EXTEND; 1153 1154 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind); 1155 1156 for (unsigned i = 0; i < NumParts; ++i) { 1157 NewValues.push_back(Parts[i]); 1158 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy())); 1159 } 1160 } 1161 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, 1162 &NewValues[0], NewValues.size())); 1163} 1164 1165/// ExportFromCurrentBlock - If this condition isn't known to be exported from 1166/// the current basic block, add it to ValueMap now so that we'll get a 1167/// CopyTo/FromReg. 1168void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) { 1169 // No need to export constants. 1170 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1171 1172 // Already exported? 1173 if (FuncInfo.isExportedInst(V)) return; 1174 1175 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1176 CopyValueToVirtualRegister(V, Reg); 1177} 1178 1179bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V, 1180 const BasicBlock *FromBB) { 1181 // The operands of the setcc have to be in this block. We don't know 1182 // how to export them from some other block. 1183 if (Instruction *VI = dyn_cast<Instruction>(V)) { 1184 // Can export from current BB. 1185 if (VI->getParent() == FromBB) 1186 return true; 1187 1188 // Is already exported, noop. 1189 return FuncInfo.isExportedInst(V); 1190 } 1191 1192 // If this is an argument, we can export it if the BB is the entry block or 1193 // if it is already exported. 1194 if (isa<Argument>(V)) { 1195 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1196 return true; 1197 1198 // Otherwise, can only export this if it is already exported. 1199 return FuncInfo.isExportedInst(V); 1200 } 1201 1202 // Otherwise, constants can always be exported. 1203 return true; 1204} 1205 1206static bool InBlock(const Value *V, const BasicBlock *BB) { 1207 if (const Instruction *I = dyn_cast<Instruction>(V)) 1208 return I->getParent() == BB; 1209 return true; 1210} 1211 1212/// FindMergedConditions - If Cond is an expression like 1213void SelectionDAGLowering::FindMergedConditions(Value *Cond, 1214 MachineBasicBlock *TBB, 1215 MachineBasicBlock *FBB, 1216 MachineBasicBlock *CurBB, 1217 unsigned Opc) { 1218 // If this node is not part of the or/and tree, emit it as a branch. 1219 Instruction *BOp = dyn_cast<Instruction>(Cond); 1220 1221 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1222 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1223 BOp->getParent() != CurBB->getBasicBlock() || 1224 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1225 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1226 const BasicBlock *BB = CurBB->getBasicBlock(); 1227 1228 // If the leaf of the tree is a comparison, merge the condition into 1229 // the caseblock. 1230 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) && 1231 // The operands of the cmp have to be in this block. We don't know 1232 // how to export them from some other block. If this is the first block 1233 // of the sequence, no exporting is needed. 1234 (CurBB == CurMBB || 1235 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1236 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) { 1237 BOp = cast<Instruction>(Cond); 1238 ISD::CondCode Condition; 1239 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1240 switch (IC->getPredicate()) { 1241 default: assert(0 && "Unknown icmp predicate opcode!"); 1242 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break; 1243 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break; 1244 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break; 1245 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break; 1246 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break; 1247 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break; 1248 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break; 1249 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break; 1250 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break; 1251 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break; 1252 } 1253 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 1254 ISD::CondCode FPC, FOC; 1255 switch (FC->getPredicate()) { 1256 default: assert(0 && "Unknown fcmp predicate opcode!"); 1257 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break; 1258 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break; 1259 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break; 1260 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break; 1261 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break; 1262 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break; 1263 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break; 1264 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break; 1265 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break; 1266 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break; 1267 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break; 1268 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break; 1269 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break; 1270 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break; 1271 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break; 1272 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break; 1273 } 1274 if (FiniteOnlyFPMath()) 1275 Condition = FOC; 1276 else 1277 Condition = FPC; 1278 } else { 1279 Condition = ISD::SETEQ; // silence warning. 1280 assert(0 && "Unknown compare instruction"); 1281 } 1282 1283 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0), 1284 BOp->getOperand(1), NULL, TBB, FBB, CurBB); 1285 SwitchCases.push_back(CB); 1286 return; 1287 } 1288 1289 // Create a CaseBlock record representing this branch. 1290 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(), 1291 NULL, TBB, FBB, CurBB); 1292 SwitchCases.push_back(CB); 1293 return; 1294 } 1295 1296 1297 // Create TmpBB after CurBB. 1298 MachineFunction::iterator BBI = CurBB; 1299 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock()); 1300 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB); 1301 1302 if (Opc == Instruction::Or) { 1303 // Codegen X | Y as: 1304 // jmp_if_X TBB 1305 // jmp TmpBB 1306 // TmpBB: 1307 // jmp_if_Y TBB 1308 // jmp FBB 1309 // 1310 1311 // Emit the LHS condition. 1312 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc); 1313 1314 // Emit the RHS condition into TmpBB. 1315 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc); 1316 } else { 1317 assert(Opc == Instruction::And && "Unknown merge op!"); 1318 // Codegen X & Y as: 1319 // jmp_if_X TmpBB 1320 // jmp FBB 1321 // TmpBB: 1322 // jmp_if_Y TBB 1323 // jmp FBB 1324 // 1325 // This requires creation of TmpBB after CurBB. 1326 1327 // Emit the LHS condition. 1328 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc); 1329 1330 // Emit the RHS condition into TmpBB. 1331 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc); 1332 } 1333} 1334 1335/// If the set of cases should be emitted as a series of branches, return true. 1336/// If we should emit this as a bunch of and/or'd together conditions, return 1337/// false. 1338static bool 1339ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) { 1340 if (Cases.size() != 2) return true; 1341 1342 // If this is two comparisons of the same values or'd or and'd together, they 1343 // will get folded into a single comparison, so don't emit two blocks. 1344 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1345 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1346 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1347 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1348 return false; 1349 } 1350 1351 return true; 1352} 1353 1354void SelectionDAGLowering::visitBr(BranchInst &I) { 1355 // Update machine-CFG edges. 1356 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1357 1358 // Figure out which block is immediately after the current one. 1359 MachineBasicBlock *NextBlock = 0; 1360 MachineFunction::iterator BBI = CurMBB; 1361 if (++BBI != CurMBB->getParent()->end()) 1362 NextBlock = BBI; 1363 1364 if (I.isUnconditional()) { 1365 // If this is not a fall-through branch, emit the branch. 1366 if (Succ0MBB != NextBlock) 1367 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(), 1368 DAG.getBasicBlock(Succ0MBB))); 1369 1370 // Update machine-CFG edges. 1371 CurMBB->addSuccessor(Succ0MBB); 1372 return; 1373 } 1374 1375 // If this condition is one of the special cases we handle, do special stuff 1376 // now. 1377 Value *CondVal = I.getCondition(); 1378 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1379 1380 // If this is a series of conditions that are or'd or and'd together, emit 1381 // this as a sequence of branches instead of setcc's with and/or operations. 1382 // For example, instead of something like: 1383 // cmp A, B 1384 // C = seteq 1385 // cmp D, E 1386 // F = setle 1387 // or C, F 1388 // jnz foo 1389 // Emit: 1390 // cmp A, B 1391 // je foo 1392 // cmp D, E 1393 // jle foo 1394 // 1395 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1396 if (BOp->hasOneUse() && 1397 (BOp->getOpcode() == Instruction::And || 1398 BOp->getOpcode() == Instruction::Or)) { 1399 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode()); 1400 // If the compares in later blocks need to use values not currently 1401 // exported from this block, export them now. This block should always 1402 // be the first entry. 1403 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!"); 1404 1405 // Allow some cases to be rejected. 1406 if (ShouldEmitAsBranches(SwitchCases)) { 1407 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1408 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1409 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1410 } 1411 1412 // Emit the branch for this block. 1413 visitSwitchCase(SwitchCases[0]); 1414 SwitchCases.erase(SwitchCases.begin()); 1415 return; 1416 } 1417 1418 // Okay, we decided not to do this, remove any inserted MBB's and clear 1419 // SwitchCases. 1420 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1421 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB); 1422 1423 SwitchCases.clear(); 1424 } 1425 } 1426 1427 // Create a CaseBlock record representing this branch. 1428 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(), 1429 NULL, Succ0MBB, Succ1MBB, CurMBB); 1430 // Use visitSwitchCase to actually insert the fast branch sequence for this 1431 // cond branch. 1432 visitSwitchCase(CB); 1433} 1434 1435/// visitSwitchCase - Emits the necessary code to represent a single node in 1436/// the binary search tree resulting from lowering a switch instruction. 1437void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) { 1438 SDOperand Cond; 1439 SDOperand CondLHS = getValue(CB.CmpLHS); 1440 1441 // Build the setcc now. 1442 if (CB.CmpMHS == NULL) { 1443 // Fold "(X == true)" to X and "(X == false)" to !X to 1444 // handle common cases produced by branch lowering. 1445 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ) 1446 Cond = CondLHS; 1447 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) { 1448 SDOperand True = DAG.getConstant(1, CondLHS.getValueType()); 1449 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True); 1450 } else 1451 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1452 } else { 1453 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1454 1455 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue(); 1456 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue(); 1457 1458 SDOperand CmpOp = getValue(CB.CmpMHS); 1459 MVT::ValueType VT = CmpOp.getValueType(); 1460 1461 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1462 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE); 1463 } else { 1464 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT)); 1465 Cond = DAG.getSetCC(MVT::i1, SUB, 1466 DAG.getConstant(High-Low, VT), ISD::SETULE); 1467 } 1468 1469 } 1470 1471 // Set NextBlock to be the MBB immediately after the current one, if any. 1472 // This is used to avoid emitting unnecessary branches to the next block. 1473 MachineBasicBlock *NextBlock = 0; 1474 MachineFunction::iterator BBI = CurMBB; 1475 if (++BBI != CurMBB->getParent()->end()) 1476 NextBlock = BBI; 1477 1478 // If the lhs block is the next block, invert the condition so that we can 1479 // fall through to the lhs instead of the rhs block. 1480 if (CB.TrueBB == NextBlock) { 1481 std::swap(CB.TrueBB, CB.FalseBB); 1482 SDOperand True = DAG.getConstant(1, Cond.getValueType()); 1483 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True); 1484 } 1485 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond, 1486 DAG.getBasicBlock(CB.TrueBB)); 1487 if (CB.FalseBB == NextBlock) 1488 DAG.setRoot(BrCond); 1489 else 1490 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 1491 DAG.getBasicBlock(CB.FalseBB))); 1492 // Update successor info 1493 CurMBB->addSuccessor(CB.TrueBB); 1494 CurMBB->addSuccessor(CB.FalseBB); 1495} 1496 1497/// visitJumpTable - Emit JumpTable node in the current MBB 1498void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) { 1499 // Emit the code for the jump table 1500 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1501 MVT::ValueType PTy = TLI.getPointerTy(); 1502 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy); 1503 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy); 1504 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1), 1505 Table, Index)); 1506 return; 1507} 1508 1509/// visitJumpTableHeader - This function emits necessary code to produce index 1510/// in the JumpTable from switch case. 1511void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT, 1512 SelectionDAGISel::JumpTableHeader &JTH) { 1513 // Subtract the lowest switch case value from the value being switched on 1514 // and conditional branch to default mbb if the result is greater than the 1515 // difference between smallest and largest cases. 1516 SDOperand SwitchOp = getValue(JTH.SValue); 1517 MVT::ValueType VT = SwitchOp.getValueType(); 1518 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp, 1519 DAG.getConstant(JTH.First, VT)); 1520 1521 // The SDNode we just created, which holds the value being switched on 1522 // minus the the smallest case value, needs to be copied to a virtual 1523 // register so it can be used as an index into the jump table in a 1524 // subsequent basic block. This value may be smaller or larger than the 1525 // target's pointer type, and therefore require extension or truncating. 1526 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy())) 1527 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB); 1528 else 1529 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB); 1530 1531 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy()); 1532 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp); 1533 JT.Reg = JumpTableReg; 1534 1535 // Emit the range check for the jump table, and branch to the default 1536 // block for the switch statement if the value being switched on exceeds 1537 // the largest case in the switch. 1538 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB, 1539 DAG.getConstant(JTH.Last-JTH.First,VT), 1540 ISD::SETUGT); 1541 1542 // Set NextBlock to be the MBB immediately after the current one, if any. 1543 // This is used to avoid emitting unnecessary branches to the next block. 1544 MachineBasicBlock *NextBlock = 0; 1545 MachineFunction::iterator BBI = CurMBB; 1546 if (++BBI != CurMBB->getParent()->end()) 1547 NextBlock = BBI; 1548 1549 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP, 1550 DAG.getBasicBlock(JT.Default)); 1551 1552 if (JT.MBB == NextBlock) 1553 DAG.setRoot(BrCond); 1554 else 1555 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 1556 DAG.getBasicBlock(JT.MBB))); 1557 1558 return; 1559} 1560 1561/// visitBitTestHeader - This function emits necessary code to produce value 1562/// suitable for "bit tests" 1563void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) { 1564 // Subtract the minimum value 1565 SDOperand SwitchOp = getValue(B.SValue); 1566 MVT::ValueType VT = SwitchOp.getValueType(); 1567 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp, 1568 DAG.getConstant(B.First, VT)); 1569 1570 // Check range 1571 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB, 1572 DAG.getConstant(B.Range, VT), 1573 ISD::SETUGT); 1574 1575 SDOperand ShiftOp; 1576 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy())) 1577 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB); 1578 else 1579 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB); 1580 1581 // Make desired shift 1582 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(), 1583 DAG.getConstant(1, TLI.getPointerTy()), 1584 ShiftOp); 1585 1586 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy()); 1587 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal); 1588 B.Reg = SwitchReg; 1589 1590 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp, 1591 DAG.getBasicBlock(B.Default)); 1592 1593 // Set NextBlock to be the MBB immediately after the current one, if any. 1594 // This is used to avoid emitting unnecessary branches to the next block. 1595 MachineBasicBlock *NextBlock = 0; 1596 MachineFunction::iterator BBI = CurMBB; 1597 if (++BBI != CurMBB->getParent()->end()) 1598 NextBlock = BBI; 1599 1600 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1601 if (MBB == NextBlock) 1602 DAG.setRoot(BrRange); 1603 else 1604 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo, 1605 DAG.getBasicBlock(MBB))); 1606 1607 CurMBB->addSuccessor(B.Default); 1608 CurMBB->addSuccessor(MBB); 1609 1610 return; 1611} 1612 1613/// visitBitTestCase - this function produces one "bit test" 1614void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB, 1615 unsigned Reg, 1616 SelectionDAGISel::BitTestCase &B) { 1617 // Emit bit tests and jumps 1618 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy()); 1619 1620 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), 1621 SwitchVal, 1622 DAG.getConstant(B.Mask, 1623 TLI.getPointerTy())); 1624 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp, 1625 DAG.getConstant(0, TLI.getPointerTy()), 1626 ISD::SETNE); 1627 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), 1628 AndCmp, DAG.getBasicBlock(B.TargetBB)); 1629 1630 // Set NextBlock to be the MBB immediately after the current one, if any. 1631 // This is used to avoid emitting unnecessary branches to the next block. 1632 MachineBasicBlock *NextBlock = 0; 1633 MachineFunction::iterator BBI = CurMBB; 1634 if (++BBI != CurMBB->getParent()->end()) 1635 NextBlock = BBI; 1636 1637 if (NextMBB == NextBlock) 1638 DAG.setRoot(BrAnd); 1639 else 1640 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd, 1641 DAG.getBasicBlock(NextMBB))); 1642 1643 CurMBB->addSuccessor(B.TargetBB); 1644 CurMBB->addSuccessor(NextMBB); 1645 1646 return; 1647} 1648 1649void SelectionDAGLowering::visitInvoke(InvokeInst &I) { 1650 // Retrieve successors. 1651 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1652 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1653 1654 if (isa<InlineAsm>(I.getCalledValue())) 1655 visitInlineAsm(&I); 1656 else 1657 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad); 1658 1659 // If the value of the invoke is used outside of its defining block, make it 1660 // available as a virtual register. 1661 if (!I.use_empty()) { 1662 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I); 1663 if (VMI != FuncInfo.ValueMap.end()) 1664 CopyValueToVirtualRegister(&I, VMI->second); 1665 } 1666 1667 // Drop into normal successor. 1668 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(), 1669 DAG.getBasicBlock(Return))); 1670 1671 // Update successor info 1672 CurMBB->addSuccessor(Return); 1673 CurMBB->addSuccessor(LandingPad); 1674} 1675 1676void SelectionDAGLowering::visitUnwind(UnwindInst &I) { 1677} 1678 1679/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for 1680/// small case ranges). 1681bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR, 1682 CaseRecVector& WorkList, 1683 Value* SV, 1684 MachineBasicBlock* Default) { 1685 Case& BackCase = *(CR.Range.second-1); 1686 1687 // Size is the number of Cases represented by this range. 1688 unsigned Size = CR.Range.second - CR.Range.first; 1689 if (Size > 3) 1690 return false; 1691 1692 // Get the MachineFunction which holds the current MBB. This is used when 1693 // inserting any additional MBBs necessary to represent the switch. 1694 MachineFunction *CurMF = CurMBB->getParent(); 1695 1696 // Figure out which block is immediately after the current one. 1697 MachineBasicBlock *NextBlock = 0; 1698 MachineFunction::iterator BBI = CR.CaseBB; 1699 1700 if (++BBI != CurMBB->getParent()->end()) 1701 NextBlock = BBI; 1702 1703 // TODO: If any two of the cases has the same destination, and if one value 1704 // is the same as the other, but has one bit unset that the other has set, 1705 // use bit manipulation to do two compares at once. For example: 1706 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 1707 1708 // Rearrange the case blocks so that the last one falls through if possible. 1709 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { 1710 // The last case block won't fall through into 'NextBlock' if we emit the 1711 // branches in this order. See if rearranging a case value would help. 1712 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) { 1713 if (I->BB == NextBlock) { 1714 std::swap(*I, BackCase); 1715 break; 1716 } 1717 } 1718 } 1719 1720 // Create a CaseBlock record representing a conditional branch to 1721 // the Case's target mbb if the value being switched on SV is equal 1722 // to C. 1723 MachineBasicBlock *CurBlock = CR.CaseBB; 1724 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 1725 MachineBasicBlock *FallThrough; 1726 if (I != E-1) { 1727 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock()); 1728 CurMF->getBasicBlockList().insert(BBI, FallThrough); 1729 } else { 1730 // If the last case doesn't match, go to the default block. 1731 FallThrough = Default; 1732 } 1733 1734 Value *RHS, *LHS, *MHS; 1735 ISD::CondCode CC; 1736 if (I->High == I->Low) { 1737 // This is just small small case range :) containing exactly 1 case 1738 CC = ISD::SETEQ; 1739 LHS = SV; RHS = I->High; MHS = NULL; 1740 } else { 1741 CC = ISD::SETLE; 1742 LHS = I->Low; MHS = SV; RHS = I->High; 1743 } 1744 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS, 1745 I->BB, FallThrough, CurBlock); 1746 1747 // If emitting the first comparison, just call visitSwitchCase to emit the 1748 // code into the current block. Otherwise, push the CaseBlock onto the 1749 // vector to be later processed by SDISel, and insert the node's MBB 1750 // before the next MBB. 1751 if (CurBlock == CurMBB) 1752 visitSwitchCase(CB); 1753 else 1754 SwitchCases.push_back(CB); 1755 1756 CurBlock = FallThrough; 1757 } 1758 1759 return true; 1760} 1761 1762static inline bool areJTsAllowed(const TargetLowering &TLI) { 1763 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) || 1764 TLI.isOperationLegal(ISD::BRIND, MVT::Other)); 1765} 1766 1767/// handleJTSwitchCase - Emit jumptable for current switch case range 1768bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR, 1769 CaseRecVector& WorkList, 1770 Value* SV, 1771 MachineBasicBlock* Default) { 1772 Case& FrontCase = *CR.Range.first; 1773 Case& BackCase = *(CR.Range.second-1); 1774 1775 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue(); 1776 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue(); 1777 1778 uint64_t TSize = 0; 1779 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1780 I!=E; ++I) 1781 TSize += I->size(); 1782 1783 if (!areJTsAllowed(TLI) || TSize <= 3) 1784 return false; 1785 1786 double Density = (double)TSize / (double)((Last - First) + 1ULL); 1787 if (Density < 0.4) 1788 return false; 1789 1790 DOUT << "Lowering jump table\n" 1791 << "First entry: " << First << ". Last entry: " << Last << "\n" 1792 << "Size: " << TSize << ". Density: " << Density << "\n\n"; 1793 1794 // Get the MachineFunction which holds the current MBB. This is used when 1795 // inserting any additional MBBs necessary to represent the switch. 1796 MachineFunction *CurMF = CurMBB->getParent(); 1797 1798 // Figure out which block is immediately after the current one. 1799 MachineBasicBlock *NextBlock = 0; 1800 MachineFunction::iterator BBI = CR.CaseBB; 1801 1802 if (++BBI != CurMBB->getParent()->end()) 1803 NextBlock = BBI; 1804 1805 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1806 1807 // Create a new basic block to hold the code for loading the address 1808 // of the jump table, and jumping to it. Update successor information; 1809 // we will either branch to the default case for the switch, or the jump 1810 // table. 1811 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB); 1812 CurMF->getBasicBlockList().insert(BBI, JumpTableBB); 1813 CR.CaseBB->addSuccessor(Default); 1814 CR.CaseBB->addSuccessor(JumpTableBB); 1815 1816 // Build a vector of destination BBs, corresponding to each target 1817 // of the jump table. If the value of the jump table slot corresponds to 1818 // a case statement, push the case's BB onto the vector, otherwise, push 1819 // the default BB. 1820 std::vector<MachineBasicBlock*> DestBBs; 1821 int64_t TEI = First; 1822 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { 1823 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue(); 1824 int64_t High = cast<ConstantInt>(I->High)->getSExtValue(); 1825 1826 if ((Low <= TEI) && (TEI <= High)) { 1827 DestBBs.push_back(I->BB); 1828 if (TEI==High) 1829 ++I; 1830 } else { 1831 DestBBs.push_back(Default); 1832 } 1833 } 1834 1835 // Update successor info. Add one edge to each unique successor. 1836 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); 1837 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 1838 E = DestBBs.end(); I != E; ++I) { 1839 if (!SuccsHandled[(*I)->getNumber()]) { 1840 SuccsHandled[(*I)->getNumber()] = true; 1841 JumpTableBB->addSuccessor(*I); 1842 } 1843 } 1844 1845 // Create a jump table index for this jump table, or return an existing 1846 // one. 1847 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs); 1848 1849 // Set the jump table information so that we can codegen it as a second 1850 // MachineBasicBlock 1851 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default); 1852 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB, 1853 (CR.CaseBB == CurMBB)); 1854 if (CR.CaseBB == CurMBB) 1855 visitJumpTableHeader(JT, JTH); 1856 1857 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT)); 1858 1859 return true; 1860} 1861 1862/// handleBTSplitSwitchCase - emit comparison and split binary search tree into 1863/// 2 subtrees. 1864bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR, 1865 CaseRecVector& WorkList, 1866 Value* SV, 1867 MachineBasicBlock* Default) { 1868 // Get the MachineFunction which holds the current MBB. This is used when 1869 // inserting any additional MBBs necessary to represent the switch. 1870 MachineFunction *CurMF = CurMBB->getParent(); 1871 1872 // Figure out which block is immediately after the current one. 1873 MachineBasicBlock *NextBlock = 0; 1874 MachineFunction::iterator BBI = CR.CaseBB; 1875 1876 if (++BBI != CurMBB->getParent()->end()) 1877 NextBlock = BBI; 1878 1879 Case& FrontCase = *CR.Range.first; 1880 Case& BackCase = *(CR.Range.second-1); 1881 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1882 1883 // Size is the number of Cases represented by this range. 1884 unsigned Size = CR.Range.second - CR.Range.first; 1885 1886 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue(); 1887 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue(); 1888 double FMetric = 0; 1889 CaseItr Pivot = CR.Range.first + Size/2; 1890 1891 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 1892 // (heuristically) allow us to emit JumpTable's later. 1893 uint64_t TSize = 0; 1894 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1895 I!=E; ++I) 1896 TSize += I->size(); 1897 1898 uint64_t LSize = FrontCase.size(); 1899 uint64_t RSize = TSize-LSize; 1900 DOUT << "Selecting best pivot: \n" 1901 << "First: " << First << ", Last: " << Last <<"\n" 1902 << "LSize: " << LSize << ", RSize: " << RSize << "\n"; 1903 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 1904 J!=E; ++I, ++J) { 1905 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue(); 1906 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue(); 1907 assert((RBegin-LEnd>=1) && "Invalid case distance"); 1908 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL); 1909 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL); 1910 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity); 1911 // Should always split in some non-trivial place 1912 DOUT <<"=>Step\n" 1913 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n" 1914 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n" 1915 << "Metric: " << Metric << "\n"; 1916 if (FMetric < Metric) { 1917 Pivot = J; 1918 FMetric = Metric; 1919 DOUT << "Current metric set to: " << FMetric << "\n"; 1920 } 1921 1922 LSize += J->size(); 1923 RSize -= J->size(); 1924 } 1925 if (areJTsAllowed(TLI)) { 1926 // If our case is dense we *really* should handle it earlier! 1927 assert((FMetric > 0) && "Should handle dense range earlier!"); 1928 } else { 1929 Pivot = CR.Range.first + Size/2; 1930 } 1931 1932 CaseRange LHSR(CR.Range.first, Pivot); 1933 CaseRange RHSR(Pivot, CR.Range.second); 1934 Constant *C = Pivot->Low; 1935 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 1936 1937 // We know that we branch to the LHS if the Value being switched on is 1938 // less than the Pivot value, C. We use this to optimize our binary 1939 // tree a bit, by recognizing that if SV is greater than or equal to the 1940 // LHS's Case Value, and that Case Value is exactly one less than the 1941 // Pivot's Value, then we can branch directly to the LHS's Target, 1942 // rather than creating a leaf node for it. 1943 if ((LHSR.second - LHSR.first) == 1 && 1944 LHSR.first->High == CR.GE && 1945 cast<ConstantInt>(C)->getSExtValue() == 1946 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) { 1947 TrueBB = LHSR.first->BB; 1948 } else { 1949 TrueBB = new MachineBasicBlock(LLVMBB); 1950 CurMF->getBasicBlockList().insert(BBI, TrueBB); 1951 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 1952 } 1953 1954 // Similar to the optimization above, if the Value being switched on is 1955 // known to be less than the Constant CR.LT, and the current Case Value 1956 // is CR.LT - 1, then we can branch directly to the target block for 1957 // the current Case Value, rather than emitting a RHS leaf node for it. 1958 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 1959 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() == 1960 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) { 1961 FalseBB = RHSR.first->BB; 1962 } else { 1963 FalseBB = new MachineBasicBlock(LLVMBB); 1964 CurMF->getBasicBlockList().insert(BBI, FalseBB); 1965 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 1966 } 1967 1968 // Create a CaseBlock record representing a conditional branch to 1969 // the LHS node if the value being switched on SV is less than C. 1970 // Otherwise, branch to LHS. 1971 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL, 1972 TrueBB, FalseBB, CR.CaseBB); 1973 1974 if (CR.CaseBB == CurMBB) 1975 visitSwitchCase(CB); 1976 else 1977 SwitchCases.push_back(CB); 1978 1979 return true; 1980} 1981 1982/// handleBitTestsSwitchCase - if current case range has few destination and 1983/// range span less, than machine word bitwidth, encode case range into series 1984/// of masks and emit bit tests with these masks. 1985bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR, 1986 CaseRecVector& WorkList, 1987 Value* SV, 1988 MachineBasicBlock* Default){ 1989 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy()); 1990 1991 Case& FrontCase = *CR.Range.first; 1992 Case& BackCase = *(CR.Range.second-1); 1993 1994 // Get the MachineFunction which holds the current MBB. This is used when 1995 // inserting any additional MBBs necessary to represent the switch. 1996 MachineFunction *CurMF = CurMBB->getParent(); 1997 1998 unsigned numCmps = 0; 1999 for (CaseItr I = CR.Range.first, E = CR.Range.second; 2000 I!=E; ++I) { 2001 // Single case counts one, case range - two. 2002 if (I->Low == I->High) 2003 numCmps +=1; 2004 else 2005 numCmps +=2; 2006 } 2007 2008 // Count unique destinations 2009 SmallSet<MachineBasicBlock*, 4> Dests; 2010 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2011 Dests.insert(I->BB); 2012 if (Dests.size() > 3) 2013 // Don't bother the code below, if there are too much unique destinations 2014 return false; 2015 } 2016 DOUT << "Total number of unique destinations: " << Dests.size() << "\n" 2017 << "Total number of comparisons: " << numCmps << "\n"; 2018 2019 // Compute span of values. 2020 Constant* minValue = FrontCase.Low; 2021 Constant* maxValue = BackCase.High; 2022 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() - 2023 cast<ConstantInt>(minValue)->getSExtValue(); 2024 DOUT << "Compare range: " << range << "\n" 2025 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n" 2026 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n"; 2027 2028 if (range>=IntPtrBits || 2029 (!(Dests.size() == 1 && numCmps >= 3) && 2030 !(Dests.size() == 2 && numCmps >= 5) && 2031 !(Dests.size() >= 3 && numCmps >= 6))) 2032 return false; 2033 2034 DOUT << "Emitting bit tests\n"; 2035 int64_t lowBound = 0; 2036 2037 // Optimize the case where all the case values fit in a 2038 // word without having to subtract minValue. In this case, 2039 // we can optimize away the subtraction. 2040 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 && 2041 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) { 2042 range = cast<ConstantInt>(maxValue)->getSExtValue(); 2043 } else { 2044 lowBound = cast<ConstantInt>(minValue)->getSExtValue(); 2045 } 2046 2047 CaseBitsVector CasesBits; 2048 unsigned i, count = 0; 2049 2050 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2051 MachineBasicBlock* Dest = I->BB; 2052 for (i = 0; i < count; ++i) 2053 if (Dest == CasesBits[i].BB) 2054 break; 2055 2056 if (i == count) { 2057 assert((count < 3) && "Too much destinations to test!"); 2058 CasesBits.push_back(CaseBits(0, Dest, 0)); 2059 count++; 2060 } 2061 2062 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound; 2063 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound; 2064 2065 for (uint64_t j = lo; j <= hi; j++) { 2066 CasesBits[i].Mask |= 1ULL << j; 2067 CasesBits[i].Bits++; 2068 } 2069 2070 } 2071 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 2072 2073 SelectionDAGISel::BitTestInfo BTC; 2074 2075 // Figure out which block is immediately after the current one. 2076 MachineFunction::iterator BBI = CR.CaseBB; 2077 ++BBI; 2078 2079 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2080 2081 DOUT << "Cases:\n"; 2082 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 2083 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits 2084 << ", BB: " << CasesBits[i].BB << "\n"; 2085 2086 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB); 2087 CurMF->getBasicBlockList().insert(BBI, CaseBB); 2088 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask, 2089 CaseBB, 2090 CasesBits[i].BB)); 2091 } 2092 2093 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV, 2094 -1U, (CR.CaseBB == CurMBB), 2095 CR.CaseBB, Default, BTC); 2096 2097 if (CR.CaseBB == CurMBB) 2098 visitBitTestHeader(BTB); 2099 2100 BitTestCases.push_back(BTB); 2101 2102 return true; 2103} 2104 2105 2106/// Clusterify - Transform simple list of Cases into list of CaseRange's 2107unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases, 2108 const SwitchInst& SI) { 2109 unsigned numCmps = 0; 2110 2111 // Start with "simple" cases 2112 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) { 2113 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)]; 2114 Cases.push_back(Case(SI.getSuccessorValue(i), 2115 SI.getSuccessorValue(i), 2116 SMBB)); 2117 } 2118 std::sort(Cases.begin(), Cases.end(), CaseCmp()); 2119 2120 // Merge case into clusters 2121 if (Cases.size()>=2) 2122 // Must recompute end() each iteration because it may be 2123 // invalidated by erase if we hold on to it 2124 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) { 2125 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue(); 2126 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue(); 2127 MachineBasicBlock* nextBB = J->BB; 2128 MachineBasicBlock* currentBB = I->BB; 2129 2130 // If the two neighboring cases go to the same destination, merge them 2131 // into a single case. 2132 if ((nextValue-currentValue==1) && (currentBB == nextBB)) { 2133 I->High = J->High; 2134 J = Cases.erase(J); 2135 } else { 2136 I = J++; 2137 } 2138 } 2139 2140 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 2141 if (I->Low != I->High) 2142 // A range counts double, since it requires two compares. 2143 ++numCmps; 2144 } 2145 2146 return numCmps; 2147} 2148 2149void SelectionDAGLowering::visitSwitch(SwitchInst &SI) { 2150 // Figure out which block is immediately after the current one. 2151 MachineBasicBlock *NextBlock = 0; 2152 MachineFunction::iterator BBI = CurMBB; 2153 2154 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 2155 2156 // If there is only the default destination, branch to it if it is not the 2157 // next basic block. Otherwise, just fall through. 2158 if (SI.getNumOperands() == 2) { 2159 // Update machine-CFG edges. 2160 2161 // If this is not a fall-through branch, emit the branch. 2162 if (Default != NextBlock) 2163 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(), 2164 DAG.getBasicBlock(Default))); 2165 2166 CurMBB->addSuccessor(Default); 2167 return; 2168 } 2169 2170 // If there are any non-default case statements, create a vector of Cases 2171 // representing each one, and sort the vector so that we can efficiently 2172 // create a binary search tree from them. 2173 CaseVector Cases; 2174 unsigned numCmps = Clusterify(Cases, SI); 2175 DOUT << "Clusterify finished. Total clusters: " << Cases.size() 2176 << ". Total compares: " << numCmps << "\n"; 2177 2178 // Get the Value to be switched on and default basic blocks, which will be 2179 // inserted into CaseBlock records, representing basic blocks in the binary 2180 // search tree. 2181 Value *SV = SI.getOperand(0); 2182 2183 // Push the initial CaseRec onto the worklist 2184 CaseRecVector WorkList; 2185 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end()))); 2186 2187 while (!WorkList.empty()) { 2188 // Grab a record representing a case range to process off the worklist 2189 CaseRec CR = WorkList.back(); 2190 WorkList.pop_back(); 2191 2192 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default)) 2193 continue; 2194 2195 // If the range has few cases (two or less) emit a series of specific 2196 // tests. 2197 if (handleSmallSwitchRange(CR, WorkList, SV, Default)) 2198 continue; 2199 2200 // If the switch has more than 5 blocks, and at least 40% dense, and the 2201 // target supports indirect branches, then emit a jump table rather than 2202 // lowering the switch to a binary tree of conditional branches. 2203 if (handleJTSwitchCase(CR, WorkList, SV, Default)) 2204 continue; 2205 2206 // Emit binary tree. We need to pick a pivot, and push left and right ranges 2207 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 2208 handleBTSplitSwitchCase(CR, WorkList, SV, Default); 2209 } 2210} 2211 2212 2213void SelectionDAGLowering::visitSub(User &I) { 2214 // -0.0 - X --> fneg 2215 const Type *Ty = I.getType(); 2216 if (isa<VectorType>(Ty)) { 2217 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) { 2218 const VectorType *DestTy = cast<VectorType>(I.getType()); 2219 const Type *ElTy = DestTy->getElementType(); 2220 if (ElTy->isFloatingPoint()) { 2221 unsigned VL = DestTy->getNumElements(); 2222 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy)); 2223 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size()); 2224 if (CV == CNZ) { 2225 SDOperand Op2 = getValue(I.getOperand(1)); 2226 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2)); 2227 return; 2228 } 2229 } 2230 } 2231 } 2232 if (Ty->isFloatingPoint()) { 2233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 2234 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) { 2235 SDOperand Op2 = getValue(I.getOperand(1)); 2236 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2)); 2237 return; 2238 } 2239 } 2240 2241 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB); 2242} 2243 2244void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) { 2245 SDOperand Op1 = getValue(I.getOperand(0)); 2246 SDOperand Op2 = getValue(I.getOperand(1)); 2247 2248 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2)); 2249} 2250 2251void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) { 2252 SDOperand Op1 = getValue(I.getOperand(0)); 2253 SDOperand Op2 = getValue(I.getOperand(1)); 2254 2255 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) < 2256 MVT::getSizeInBits(Op2.getValueType())) 2257 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2); 2258 else if (TLI.getShiftAmountTy() > Op2.getValueType()) 2259 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2); 2260 2261 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2)); 2262} 2263 2264void SelectionDAGLowering::visitICmp(User &I) { 2265 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2266 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2267 predicate = IC->getPredicate(); 2268 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2269 predicate = ICmpInst::Predicate(IC->getPredicate()); 2270 SDOperand Op1 = getValue(I.getOperand(0)); 2271 SDOperand Op2 = getValue(I.getOperand(1)); 2272 ISD::CondCode Opcode; 2273 switch (predicate) { 2274 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break; 2275 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break; 2276 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break; 2277 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break; 2278 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break; 2279 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break; 2280 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break; 2281 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break; 2282 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break; 2283 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break; 2284 default: 2285 assert(!"Invalid ICmp predicate value"); 2286 Opcode = ISD::SETEQ; 2287 break; 2288 } 2289 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode)); 2290} 2291 2292void SelectionDAGLowering::visitFCmp(User &I) { 2293 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2294 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2295 predicate = FC->getPredicate(); 2296 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2297 predicate = FCmpInst::Predicate(FC->getPredicate()); 2298 SDOperand Op1 = getValue(I.getOperand(0)); 2299 SDOperand Op2 = getValue(I.getOperand(1)); 2300 ISD::CondCode Condition, FOC, FPC; 2301 switch (predicate) { 2302 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break; 2303 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break; 2304 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break; 2305 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break; 2306 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break; 2307 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break; 2308 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break; 2309 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break; 2310 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break; 2311 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break; 2312 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break; 2313 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break; 2314 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break; 2315 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break; 2316 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break; 2317 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break; 2318 default: 2319 assert(!"Invalid FCmp predicate value"); 2320 FOC = FPC = ISD::SETFALSE; 2321 break; 2322 } 2323 if (FiniteOnlyFPMath()) 2324 Condition = FOC; 2325 else 2326 Condition = FPC; 2327 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition)); 2328} 2329 2330void SelectionDAGLowering::visitSelect(User &I) { 2331 SDOperand Cond = getValue(I.getOperand(0)); 2332 SDOperand TrueVal = getValue(I.getOperand(1)); 2333 SDOperand FalseVal = getValue(I.getOperand(2)); 2334 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond, 2335 TrueVal, FalseVal)); 2336} 2337 2338 2339void SelectionDAGLowering::visitTrunc(User &I) { 2340 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2341 SDOperand N = getValue(I.getOperand(0)); 2342 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2343 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N)); 2344} 2345 2346void SelectionDAGLowering::visitZExt(User &I) { 2347 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2348 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2349 SDOperand N = getValue(I.getOperand(0)); 2350 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2351 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N)); 2352} 2353 2354void SelectionDAGLowering::visitSExt(User &I) { 2355 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2356 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2357 SDOperand N = getValue(I.getOperand(0)); 2358 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2359 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N)); 2360} 2361 2362void SelectionDAGLowering::visitFPTrunc(User &I) { 2363 // FPTrunc is never a no-op cast, no need to check 2364 SDOperand N = getValue(I.getOperand(0)); 2365 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2366 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0))); 2367} 2368 2369void SelectionDAGLowering::visitFPExt(User &I){ 2370 // FPTrunc is never a no-op cast, no need to check 2371 SDOperand N = getValue(I.getOperand(0)); 2372 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2373 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N)); 2374} 2375 2376void SelectionDAGLowering::visitFPToUI(User &I) { 2377 // FPToUI is never a no-op cast, no need to check 2378 SDOperand N = getValue(I.getOperand(0)); 2379 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2380 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N)); 2381} 2382 2383void SelectionDAGLowering::visitFPToSI(User &I) { 2384 // FPToSI is never a no-op cast, no need to check 2385 SDOperand N = getValue(I.getOperand(0)); 2386 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2387 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N)); 2388} 2389 2390void SelectionDAGLowering::visitUIToFP(User &I) { 2391 // UIToFP is never a no-op cast, no need to check 2392 SDOperand N = getValue(I.getOperand(0)); 2393 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2394 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N)); 2395} 2396 2397void SelectionDAGLowering::visitSIToFP(User &I){ 2398 // UIToFP is never a no-op cast, no need to check 2399 SDOperand N = getValue(I.getOperand(0)); 2400 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2401 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N)); 2402} 2403 2404void SelectionDAGLowering::visitPtrToInt(User &I) { 2405 // What to do depends on the size of the integer and the size of the pointer. 2406 // We can either truncate, zero extend, or no-op, accordingly. 2407 SDOperand N = getValue(I.getOperand(0)); 2408 MVT::ValueType SrcVT = N.getValueType(); 2409 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2410 SDOperand Result; 2411 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT)) 2412 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N); 2413 else 2414 // Note: ZERO_EXTEND can handle cases where the sizes are equal too 2415 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N); 2416 setValue(&I, Result); 2417} 2418 2419void SelectionDAGLowering::visitIntToPtr(User &I) { 2420 // What to do depends on the size of the integer and the size of the pointer. 2421 // We can either truncate, zero extend, or no-op, accordingly. 2422 SDOperand N = getValue(I.getOperand(0)); 2423 MVT::ValueType SrcVT = N.getValueType(); 2424 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2425 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT)) 2426 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N)); 2427 else 2428 // Note: ZERO_EXTEND can handle cases where the sizes are equal too 2429 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N)); 2430} 2431 2432void SelectionDAGLowering::visitBitCast(User &I) { 2433 SDOperand N = getValue(I.getOperand(0)); 2434 MVT::ValueType DestVT = TLI.getValueType(I.getType()); 2435 2436 // BitCast assures us that source and destination are the same size so this 2437 // is either a BIT_CONVERT or a no-op. 2438 if (DestVT != N.getValueType()) 2439 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types 2440 else 2441 setValue(&I, N); // noop cast. 2442} 2443 2444void SelectionDAGLowering::visitInsertElement(User &I) { 2445 SDOperand InVec = getValue(I.getOperand(0)); 2446 SDOperand InVal = getValue(I.getOperand(1)); 2447 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), 2448 getValue(I.getOperand(2))); 2449 2450 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, 2451 TLI.getValueType(I.getType()), 2452 InVec, InVal, InIdx)); 2453} 2454 2455void SelectionDAGLowering::visitExtractElement(User &I) { 2456 SDOperand InVec = getValue(I.getOperand(0)); 2457 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), 2458 getValue(I.getOperand(1))); 2459 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 2460 TLI.getValueType(I.getType()), InVec, InIdx)); 2461} 2462 2463void SelectionDAGLowering::visitShuffleVector(User &I) { 2464 SDOperand V1 = getValue(I.getOperand(0)); 2465 SDOperand V2 = getValue(I.getOperand(1)); 2466 SDOperand Mask = getValue(I.getOperand(2)); 2467 2468 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, 2469 TLI.getValueType(I.getType()), 2470 V1, V2, Mask)); 2471} 2472 2473 2474void SelectionDAGLowering::visitGetElementPtr(User &I) { 2475 SDOperand N = getValue(I.getOperand(0)); 2476 const Type *Ty = I.getOperand(0)->getType(); 2477 2478 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end(); 2479 OI != E; ++OI) { 2480 Value *Idx = *OI; 2481 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 2482 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2483 if (Field) { 2484 // N = N + Offset 2485 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 2486 N = DAG.getNode(ISD::ADD, N.getValueType(), N, 2487 DAG.getIntPtrConstant(Offset)); 2488 } 2489 Ty = StTy->getElementType(Field); 2490 } else { 2491 Ty = cast<SequentialType>(Ty)->getElementType(); 2492 2493 // If this is a constant subscript, handle it quickly. 2494 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 2495 if (CI->getZExtValue() == 0) continue; 2496 uint64_t Offs = 2497 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 2498 N = DAG.getNode(ISD::ADD, N.getValueType(), N, 2499 DAG.getIntPtrConstant(Offs)); 2500 continue; 2501 } 2502 2503 // N = N + Idx * ElementSize; 2504 uint64_t ElementSize = TD->getABITypeSize(Ty); 2505 SDOperand IdxN = getValue(Idx); 2506 2507 // If the index is smaller or larger than intptr_t, truncate or extend 2508 // it. 2509 if (IdxN.getValueType() < N.getValueType()) { 2510 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN); 2511 } else if (IdxN.getValueType() > N.getValueType()) 2512 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN); 2513 2514 // If this is a multiply by a power of two, turn it into a shl 2515 // immediately. This is a very common case. 2516 if (isPowerOf2_64(ElementSize)) { 2517 unsigned Amt = Log2_64(ElementSize); 2518 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN, 2519 DAG.getConstant(Amt, TLI.getShiftAmountTy())); 2520 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN); 2521 continue; 2522 } 2523 2524 SDOperand Scale = DAG.getIntPtrConstant(ElementSize); 2525 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale); 2526 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN); 2527 } 2528 } 2529 setValue(&I, N); 2530} 2531 2532void SelectionDAGLowering::visitAlloca(AllocaInst &I) { 2533 // If this is a fixed sized alloca in the entry block of the function, 2534 // allocate it statically on the stack. 2535 if (FuncInfo.StaticAllocaMap.count(&I)) 2536 return; // getValue will auto-populate this. 2537 2538 const Type *Ty = I.getAllocatedType(); 2539 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty); 2540 unsigned Align = 2541 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 2542 I.getAlignment()); 2543 2544 SDOperand AllocSize = getValue(I.getArraySize()); 2545 MVT::ValueType IntPtr = TLI.getPointerTy(); 2546 if (IntPtr < AllocSize.getValueType()) 2547 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize); 2548 else if (IntPtr > AllocSize.getValueType()) 2549 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize); 2550 2551 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize, 2552 DAG.getIntPtrConstant(TySize)); 2553 2554 // Handle alignment. If the requested alignment is less than or equal to 2555 // the stack alignment, ignore it. If the size is greater than or equal to 2556 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 2557 unsigned StackAlign = 2558 TLI.getTargetMachine().getFrameInfo()->getStackAlignment(); 2559 if (Align <= StackAlign) 2560 Align = 0; 2561 2562 // Round the size of the allocation up to the stack alignment size 2563 // by add SA-1 to the size. 2564 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize, 2565 DAG.getIntPtrConstant(StackAlign-1)); 2566 // Mask out the low bits for alignment purposes. 2567 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize, 2568 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1))); 2569 2570 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) }; 2571 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(), 2572 MVT::Other); 2573 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3); 2574 setValue(&I, DSA); 2575 DAG.setRoot(DSA.getValue(1)); 2576 2577 // Inform the Frame Information that we have just allocated a variable-sized 2578 // object. 2579 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject(); 2580} 2581 2582void SelectionDAGLowering::visitLoad(LoadInst &I) { 2583 SDOperand Ptr = getValue(I.getOperand(0)); 2584 2585 SDOperand Root; 2586 if (I.isVolatile()) 2587 Root = getRoot(); 2588 else { 2589 // Do not serialize non-volatile loads against each other. 2590 Root = DAG.getRoot(); 2591 } 2592 2593 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0), 2594 Root, I.isVolatile(), I.getAlignment())); 2595} 2596 2597SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr, 2598 const Value *SV, SDOperand Root, 2599 bool isVolatile, 2600 unsigned Alignment) { 2601 SDOperand L = 2602 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, 2603 isVolatile, Alignment); 2604 2605 if (isVolatile) 2606 DAG.setRoot(L.getValue(1)); 2607 else 2608 PendingLoads.push_back(L.getValue(1)); 2609 2610 return L; 2611} 2612 2613 2614void SelectionDAGLowering::visitStore(StoreInst &I) { 2615 Value *SrcV = I.getOperand(0); 2616 SDOperand Src = getValue(SrcV); 2617 SDOperand Ptr = getValue(I.getOperand(1)); 2618 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0, 2619 I.isVolatile(), I.getAlignment())); 2620} 2621 2622/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 2623/// node. 2624void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 2625 unsigned Intrinsic) { 2626 bool HasChain = !I.doesNotAccessMemory(); 2627 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 2628 2629 // Build the operand list. 2630 SmallVector<SDOperand, 8> Ops; 2631 if (HasChain) { // If this intrinsic has side-effects, chainify it. 2632 if (OnlyLoad) { 2633 // We don't need to serialize loads against other loads. 2634 Ops.push_back(DAG.getRoot()); 2635 } else { 2636 Ops.push_back(getRoot()); 2637 } 2638 } 2639 2640 // Add the intrinsic ID as an integer operand. 2641 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy())); 2642 2643 // Add all operands of the call to the operand list. 2644 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 2645 SDOperand Op = getValue(I.getOperand(i)); 2646 assert(TLI.isTypeLegal(Op.getValueType()) && 2647 "Intrinsic uses a non-legal type?"); 2648 Ops.push_back(Op); 2649 } 2650 2651 std::vector<MVT::ValueType> VTs; 2652 if (I.getType() != Type::VoidTy) { 2653 MVT::ValueType VT = TLI.getValueType(I.getType()); 2654 if (MVT::isVector(VT)) { 2655 const VectorType *DestTy = cast<VectorType>(I.getType()); 2656 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType()); 2657 2658 VT = MVT::getVectorType(EltVT, DestTy->getNumElements()); 2659 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?"); 2660 } 2661 2662 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?"); 2663 VTs.push_back(VT); 2664 } 2665 if (HasChain) 2666 VTs.push_back(MVT::Other); 2667 2668 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs); 2669 2670 // Create the node. 2671 SDOperand Result; 2672 if (!HasChain) 2673 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(), 2674 &Ops[0], Ops.size()); 2675 else if (I.getType() != Type::VoidTy) 2676 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(), 2677 &Ops[0], Ops.size()); 2678 else 2679 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(), 2680 &Ops[0], Ops.size()); 2681 2682 if (HasChain) { 2683 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1); 2684 if (OnlyLoad) 2685 PendingLoads.push_back(Chain); 2686 else 2687 DAG.setRoot(Chain); 2688 } 2689 if (I.getType() != Type::VoidTy) { 2690 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 2691 MVT::ValueType VT = TLI.getValueType(PTy); 2692 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result); 2693 } 2694 setValue(&I, Result); 2695 } 2696} 2697 2698/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V. 2699static GlobalVariable *ExtractTypeInfo (Value *V) { 2700 V = IntrinsicInst::StripPointerCasts(V); 2701 GlobalVariable *GV = dyn_cast<GlobalVariable>(V); 2702 assert ((GV || isa<ConstantPointerNull>(V)) && 2703 "TypeInfo must be a global variable or NULL"); 2704 return GV; 2705} 2706 2707/// addCatchInfo - Extract the personality and type infos from an eh.selector 2708/// call, and add them to the specified machine basic block. 2709static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI, 2710 MachineBasicBlock *MBB) { 2711 // Inform the MachineModuleInfo of the personality for this landing pad. 2712 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2)); 2713 assert(CE->getOpcode() == Instruction::BitCast && 2714 isa<Function>(CE->getOperand(0)) && 2715 "Personality should be a function"); 2716 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0))); 2717 2718 // Gather all the type infos for this landing pad and pass them along to 2719 // MachineModuleInfo. 2720 std::vector<GlobalVariable *> TyInfo; 2721 unsigned N = I.getNumOperands(); 2722 2723 for (unsigned i = N - 1; i > 2; --i) { 2724 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) { 2725 unsigned FilterLength = CI->getZExtValue(); 2726 unsigned FirstCatch = i + FilterLength + !FilterLength; 2727 assert (FirstCatch <= N && "Invalid filter length"); 2728 2729 if (FirstCatch < N) { 2730 TyInfo.reserve(N - FirstCatch); 2731 for (unsigned j = FirstCatch; j < N; ++j) 2732 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); 2733 MMI->addCatchTypeInfo(MBB, TyInfo); 2734 TyInfo.clear(); 2735 } 2736 2737 if (!FilterLength) { 2738 // Cleanup. 2739 MMI->addCleanup(MBB); 2740 } else { 2741 // Filter. 2742 TyInfo.reserve(FilterLength - 1); 2743 for (unsigned j = i + 1; j < FirstCatch; ++j) 2744 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); 2745 MMI->addFilterTypeInfo(MBB, TyInfo); 2746 TyInfo.clear(); 2747 } 2748 2749 N = i; 2750 } 2751 } 2752 2753 if (N > 3) { 2754 TyInfo.reserve(N - 3); 2755 for (unsigned j = 3; j < N; ++j) 2756 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j))); 2757 MMI->addCatchTypeInfo(MBB, TyInfo); 2758 } 2759} 2760 2761/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 2762/// we want to emit this as a call to a named external function, return the name 2763/// otherwise lower it and return null. 2764const char * 2765SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) { 2766 switch (Intrinsic) { 2767 default: 2768 // By default, turn this into a target intrinsic node. 2769 visitTargetIntrinsic(I, Intrinsic); 2770 return 0; 2771 case Intrinsic::vastart: visitVAStart(I); return 0; 2772 case Intrinsic::vaend: visitVAEnd(I); return 0; 2773 case Intrinsic::vacopy: visitVACopy(I); return 0; 2774 case Intrinsic::returnaddress: 2775 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(), 2776 getValue(I.getOperand(1)))); 2777 return 0; 2778 case Intrinsic::frameaddress: 2779 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(), 2780 getValue(I.getOperand(1)))); 2781 return 0; 2782 case Intrinsic::setjmp: 2783 return "_setjmp"+!TLI.usesUnderscoreSetJmp(); 2784 break; 2785 case Intrinsic::longjmp: 2786 return "_longjmp"+!TLI.usesUnderscoreLongJmp(); 2787 break; 2788 case Intrinsic::memcpy_i32: 2789 case Intrinsic::memcpy_i64: { 2790 SDOperand Op1 = getValue(I.getOperand(1)); 2791 SDOperand Op2 = getValue(I.getOperand(2)); 2792 SDOperand Op3 = getValue(I.getOperand(3)); 2793 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 2794 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false, 2795 I.getOperand(1), 0, I.getOperand(2), 0)); 2796 return 0; 2797 } 2798 case Intrinsic::memset_i32: 2799 case Intrinsic::memset_i64: { 2800 SDOperand Op1 = getValue(I.getOperand(1)); 2801 SDOperand Op2 = getValue(I.getOperand(2)); 2802 SDOperand Op3 = getValue(I.getOperand(3)); 2803 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 2804 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align, 2805 I.getOperand(1), 0)); 2806 return 0; 2807 } 2808 case Intrinsic::memmove_i32: 2809 case Intrinsic::memmove_i64: { 2810 SDOperand Op1 = getValue(I.getOperand(1)); 2811 SDOperand Op2 = getValue(I.getOperand(2)); 2812 SDOperand Op3 = getValue(I.getOperand(3)); 2813 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 2814 2815 // If the source and destination are known to not be aliases, we can 2816 // lower memmove as memcpy. 2817 uint64_t Size = -1ULL; 2818 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3)) 2819 Size = C->getValue(); 2820 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) == 2821 AliasAnalysis::NoAlias) { 2822 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false, 2823 I.getOperand(1), 0, I.getOperand(2), 0)); 2824 return 0; 2825 } 2826 2827 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align, 2828 I.getOperand(1), 0, I.getOperand(2), 0)); 2829 return 0; 2830 } 2831 case Intrinsic::dbg_stoppoint: { 2832 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2833 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I); 2834 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) { 2835 SDOperand Ops[5]; 2836 2837 Ops[0] = getRoot(); 2838 Ops[1] = getValue(SPI.getLineValue()); 2839 Ops[2] = getValue(SPI.getColumnValue()); 2840 2841 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext()); 2842 assert(DD && "Not a debug information descriptor"); 2843 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD); 2844 2845 Ops[3] = DAG.getString(CompileUnit->getFileName()); 2846 Ops[4] = DAG.getString(CompileUnit->getDirectory()); 2847 2848 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5)); 2849 } 2850 2851 return 0; 2852 } 2853 case Intrinsic::dbg_region_start: { 2854 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2855 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I); 2856 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) { 2857 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext()); 2858 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(), 2859 DAG.getConstant(LabelID, MVT::i32), 2860 DAG.getConstant(0, MVT::i32))); 2861 } 2862 2863 return 0; 2864 } 2865 case Intrinsic::dbg_region_end: { 2866 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2867 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I); 2868 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) { 2869 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext()); 2870 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(), 2871 DAG.getConstant(LabelID, MVT::i32), 2872 DAG.getConstant(0, MVT::i32))); 2873 } 2874 2875 return 0; 2876 } 2877 case Intrinsic::dbg_func_start: { 2878 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2879 if (!MMI) return 0; 2880 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I); 2881 Value *SP = FSI.getSubprogram(); 2882 if (SP && MMI->Verify(SP)) { 2883 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is 2884 // what (most?) gdb expects. 2885 DebugInfoDesc *DD = MMI->getDescFor(SP); 2886 assert(DD && "Not a debug information descriptor"); 2887 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD); 2888 const CompileUnitDesc *CompileUnit = Subprogram->getFile(); 2889 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(), 2890 CompileUnit->getFileName()); 2891 // Record the source line but does create a label. It will be emitted 2892 // at asm emission time. 2893 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile); 2894 } 2895 2896 return 0; 2897 } 2898 case Intrinsic::dbg_declare: { 2899 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2900 DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 2901 Value *Variable = DI.getVariable(); 2902 if (MMI && Variable && MMI->Verify(Variable)) 2903 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(), 2904 getValue(DI.getAddress()), getValue(Variable))); 2905 return 0; 2906 } 2907 2908 case Intrinsic::eh_exception: { 2909 if (!CurMBB->isLandingPad()) { 2910 // FIXME: Mark exception register as live in. Hack for PR1508. 2911 unsigned Reg = TLI.getExceptionAddressRegister(); 2912 if (Reg) CurMBB->addLiveIn(Reg); 2913 } 2914 // Insert the EXCEPTIONADDR instruction. 2915 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 2916 SDOperand Ops[1]; 2917 Ops[0] = DAG.getRoot(); 2918 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1); 2919 setValue(&I, Op); 2920 DAG.setRoot(Op.getValue(1)); 2921 return 0; 2922 } 2923 2924 case Intrinsic::eh_selector_i32: 2925 case Intrinsic::eh_selector_i64: { 2926 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2927 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ? 2928 MVT::i32 : MVT::i64); 2929 2930 if (MMI) { 2931 if (CurMBB->isLandingPad()) 2932 addCatchInfo(I, MMI, CurMBB); 2933 else { 2934#ifndef NDEBUG 2935 FuncInfo.CatchInfoLost.insert(&I); 2936#endif 2937 // FIXME: Mark exception selector register as live in. Hack for PR1508. 2938 unsigned Reg = TLI.getExceptionSelectorRegister(); 2939 if (Reg) CurMBB->addLiveIn(Reg); 2940 } 2941 2942 // Insert the EHSELECTION instruction. 2943 SDVTList VTs = DAG.getVTList(VT, MVT::Other); 2944 SDOperand Ops[2]; 2945 Ops[0] = getValue(I.getOperand(1)); 2946 Ops[1] = getRoot(); 2947 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2); 2948 setValue(&I, Op); 2949 DAG.setRoot(Op.getValue(1)); 2950 } else { 2951 setValue(&I, DAG.getConstant(0, VT)); 2952 } 2953 2954 return 0; 2955 } 2956 2957 case Intrinsic::eh_typeid_for_i32: 2958 case Intrinsic::eh_typeid_for_i64: { 2959 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2960 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ? 2961 MVT::i32 : MVT::i64); 2962 2963 if (MMI) { 2964 // Find the type id for the given typeinfo. 2965 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1)); 2966 2967 unsigned TypeID = MMI->getTypeIDFor(GV); 2968 setValue(&I, DAG.getConstant(TypeID, VT)); 2969 } else { 2970 // Return something different to eh_selector. 2971 setValue(&I, DAG.getConstant(1, VT)); 2972 } 2973 2974 return 0; 2975 } 2976 2977 case Intrinsic::eh_return: { 2978 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 2979 2980 if (MMI) { 2981 MMI->setCallsEHReturn(true); 2982 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, 2983 MVT::Other, 2984 getControlRoot(), 2985 getValue(I.getOperand(1)), 2986 getValue(I.getOperand(2)))); 2987 } else { 2988 setValue(&I, DAG.getConstant(0, TLI.getPointerTy())); 2989 } 2990 2991 return 0; 2992 } 2993 2994 case Intrinsic::eh_unwind_init: { 2995 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) { 2996 MMI->setCallsUnwindInit(true); 2997 } 2998 2999 return 0; 3000 } 3001 3002 case Intrinsic::eh_dwarf_cfa: { 3003 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType(); 3004 SDOperand CfaArg; 3005 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy())) 3006 CfaArg = DAG.getNode(ISD::TRUNCATE, 3007 TLI.getPointerTy(), getValue(I.getOperand(1))); 3008 else 3009 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, 3010 TLI.getPointerTy(), getValue(I.getOperand(1))); 3011 3012 SDOperand Offset = DAG.getNode(ISD::ADD, 3013 TLI.getPointerTy(), 3014 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, 3015 TLI.getPointerTy()), 3016 CfaArg); 3017 setValue(&I, DAG.getNode(ISD::ADD, 3018 TLI.getPointerTy(), 3019 DAG.getNode(ISD::FRAMEADDR, 3020 TLI.getPointerTy(), 3021 DAG.getConstant(0, 3022 TLI.getPointerTy())), 3023 Offset)); 3024 return 0; 3025 } 3026 3027 case Intrinsic::sqrt: 3028 setValue(&I, DAG.getNode(ISD::FSQRT, 3029 getValue(I.getOperand(1)).getValueType(), 3030 getValue(I.getOperand(1)))); 3031 return 0; 3032 case Intrinsic::powi: 3033 setValue(&I, DAG.getNode(ISD::FPOWI, 3034 getValue(I.getOperand(1)).getValueType(), 3035 getValue(I.getOperand(1)), 3036 getValue(I.getOperand(2)))); 3037 return 0; 3038 case Intrinsic::sin: 3039 setValue(&I, DAG.getNode(ISD::FSIN, 3040 getValue(I.getOperand(1)).getValueType(), 3041 getValue(I.getOperand(1)))); 3042 return 0; 3043 case Intrinsic::cos: 3044 setValue(&I, DAG.getNode(ISD::FCOS, 3045 getValue(I.getOperand(1)).getValueType(), 3046 getValue(I.getOperand(1)))); 3047 return 0; 3048 case Intrinsic::pow: 3049 setValue(&I, DAG.getNode(ISD::FPOW, 3050 getValue(I.getOperand(1)).getValueType(), 3051 getValue(I.getOperand(1)), 3052 getValue(I.getOperand(2)))); 3053 return 0; 3054 case Intrinsic::pcmarker: { 3055 SDOperand Tmp = getValue(I.getOperand(1)); 3056 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp)); 3057 return 0; 3058 } 3059 case Intrinsic::readcyclecounter: { 3060 SDOperand Op = getRoot(); 3061 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, 3062 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2, 3063 &Op, 1); 3064 setValue(&I, Tmp); 3065 DAG.setRoot(Tmp.getValue(1)); 3066 return 0; 3067 } 3068 case Intrinsic::part_select: { 3069 // Currently not implemented: just abort 3070 assert(0 && "part_select intrinsic not implemented"); 3071 abort(); 3072 } 3073 case Intrinsic::part_set: { 3074 // Currently not implemented: just abort 3075 assert(0 && "part_set intrinsic not implemented"); 3076 abort(); 3077 } 3078 case Intrinsic::bswap: 3079 setValue(&I, DAG.getNode(ISD::BSWAP, 3080 getValue(I.getOperand(1)).getValueType(), 3081 getValue(I.getOperand(1)))); 3082 return 0; 3083 case Intrinsic::cttz: { 3084 SDOperand Arg = getValue(I.getOperand(1)); 3085 MVT::ValueType Ty = Arg.getValueType(); 3086 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg); 3087 setValue(&I, result); 3088 return 0; 3089 } 3090 case Intrinsic::ctlz: { 3091 SDOperand Arg = getValue(I.getOperand(1)); 3092 MVT::ValueType Ty = Arg.getValueType(); 3093 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg); 3094 setValue(&I, result); 3095 return 0; 3096 } 3097 case Intrinsic::ctpop: { 3098 SDOperand Arg = getValue(I.getOperand(1)); 3099 MVT::ValueType Ty = Arg.getValueType(); 3100 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg); 3101 setValue(&I, result); 3102 return 0; 3103 } 3104 case Intrinsic::stacksave: { 3105 SDOperand Op = getRoot(); 3106 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, 3107 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1); 3108 setValue(&I, Tmp); 3109 DAG.setRoot(Tmp.getValue(1)); 3110 return 0; 3111 } 3112 case Intrinsic::stackrestore: { 3113 SDOperand Tmp = getValue(I.getOperand(1)); 3114 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp)); 3115 return 0; 3116 } 3117 case Intrinsic::var_annotation: 3118 // Discard annotate attributes 3119 return 0; 3120 3121 case Intrinsic::init_trampoline: { 3122 const Function *F = 3123 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2))); 3124 3125 SDOperand Ops[6]; 3126 Ops[0] = getRoot(); 3127 Ops[1] = getValue(I.getOperand(1)); 3128 Ops[2] = getValue(I.getOperand(2)); 3129 Ops[3] = getValue(I.getOperand(3)); 3130 Ops[4] = DAG.getSrcValue(I.getOperand(1)); 3131 Ops[5] = DAG.getSrcValue(F); 3132 3133 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE, 3134 DAG.getNodeValueTypes(TLI.getPointerTy(), 3135 MVT::Other), 2, 3136 Ops, 6); 3137 3138 setValue(&I, Tmp); 3139 DAG.setRoot(Tmp.getValue(1)); 3140 return 0; 3141 } 3142 3143 case Intrinsic::gcroot: 3144 if (GCI) { 3145 Value *Alloca = I.getOperand(1); 3146 Constant *TypeMap = cast<Constant>(I.getOperand(2)); 3147 3148 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val); 3149 GCI->addStackRoot(FI->getIndex(), TypeMap); 3150 } 3151 return 0; 3152 3153 case Intrinsic::gcread: 3154 case Intrinsic::gcwrite: 3155 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!"); 3156 return 0; 3157 3158 case Intrinsic::flt_rounds: { 3159 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32)); 3160 return 0; 3161 } 3162 3163 case Intrinsic::trap: { 3164 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot())); 3165 return 0; 3166 } 3167 case Intrinsic::prefetch: { 3168 SDOperand Ops[4]; 3169 Ops[0] = getRoot(); 3170 Ops[1] = getValue(I.getOperand(1)); 3171 Ops[2] = getValue(I.getOperand(2)); 3172 Ops[3] = getValue(I.getOperand(3)); 3173 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4)); 3174 return 0; 3175 } 3176 3177 case Intrinsic::memory_barrier: { 3178 SDOperand Ops[6]; 3179 Ops[0] = getRoot(); 3180 for (int x = 1; x < 6; ++x) 3181 Ops[x] = getValue(I.getOperand(x)); 3182 3183 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6)); 3184 return 0; 3185 } 3186 case Intrinsic::atomic_lcs: { 3187 SDOperand Root = getRoot(); 3188 SDOperand O3 = getValue(I.getOperand(3)); 3189 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root, 3190 getValue(I.getOperand(1)), 3191 getValue(I.getOperand(2)), 3192 O3, O3.getValueType()); 3193 setValue(&I, L); 3194 DAG.setRoot(L.getValue(1)); 3195 return 0; 3196 } 3197 case Intrinsic::atomic_las: { 3198 SDOperand Root = getRoot(); 3199 SDOperand O2 = getValue(I.getOperand(2)); 3200 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root, 3201 getValue(I.getOperand(1)), 3202 O2, O2.getValueType()); 3203 setValue(&I, L); 3204 DAG.setRoot(L.getValue(1)); 3205 return 0; 3206 } 3207 case Intrinsic::atomic_swap: { 3208 SDOperand Root = getRoot(); 3209 SDOperand O2 = getValue(I.getOperand(2)); 3210 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root, 3211 getValue(I.getOperand(1)), 3212 O2, O2.getValueType()); 3213 setValue(&I, L); 3214 DAG.setRoot(L.getValue(1)); 3215 return 0; 3216 } 3217 3218 } 3219} 3220 3221 3222void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee, 3223 bool IsTailCall, 3224 MachineBasicBlock *LandingPad) { 3225 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 3226 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 3227 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 3228 unsigned BeginLabel = 0, EndLabel = 0; 3229 3230 TargetLowering::ArgListTy Args; 3231 TargetLowering::ArgListEntry Entry; 3232 Args.reserve(CS.arg_size()); 3233 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 3234 i != e; ++i) { 3235 SDOperand ArgNode = getValue(*i); 3236 Entry.Node = ArgNode; Entry.Ty = (*i)->getType(); 3237 3238 unsigned attrInd = i - CS.arg_begin() + 1; 3239 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt); 3240 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt); 3241 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg); 3242 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet); 3243 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest); 3244 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal); 3245 Entry.Alignment = CS.getParamAlignment(attrInd); 3246 Args.push_back(Entry); 3247 } 3248 3249 if (LandingPad && MMI) { 3250 // Insert a label before the invoke call to mark the try range. This can be 3251 // used to detect deletion of the invoke via the MachineModuleInfo. 3252 BeginLabel = MMI->NextLabelID(); 3253 // Both PendingLoads and PendingExports must be flushed here; 3254 // this call might not return. 3255 (void)getRoot(); 3256 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(), 3257 DAG.getConstant(BeginLabel, MVT::i32), 3258 DAG.getConstant(1, MVT::i32))); 3259 } 3260 3261 std::pair<SDOperand,SDOperand> Result = 3262 TLI.LowerCallTo(getRoot(), CS.getType(), 3263 CS.paramHasAttr(0, ParamAttr::SExt), 3264 CS.paramHasAttr(0, ParamAttr::ZExt), 3265 FTy->isVarArg(), CS.getCallingConv(), IsTailCall, 3266 Callee, Args, DAG); 3267 if (CS.getType() != Type::VoidTy) 3268 setValue(CS.getInstruction(), Result.first); 3269 DAG.setRoot(Result.second); 3270 3271 if (LandingPad && MMI) { 3272 // Insert a label at the end of the invoke call to mark the try range. This 3273 // can be used to detect deletion of the invoke via the MachineModuleInfo. 3274 EndLabel = MMI->NextLabelID(); 3275 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(), 3276 DAG.getConstant(EndLabel, MVT::i32), 3277 DAG.getConstant(1, MVT::i32))); 3278 3279 // Inform MachineModuleInfo of range. 3280 MMI->addInvoke(LandingPad, BeginLabel, EndLabel); 3281 } 3282} 3283 3284 3285void SelectionDAGLowering::visitCall(CallInst &I) { 3286 const char *RenameFn = 0; 3287 if (Function *F = I.getCalledFunction()) { 3288 if (F->isDeclaration()) { 3289 if (unsigned IID = F->getIntrinsicID()) { 3290 RenameFn = visitIntrinsicCall(I, IID); 3291 if (!RenameFn) 3292 return; 3293 } 3294 } 3295 3296 // Check for well-known libc/libm calls. If the function is internal, it 3297 // can't be a library call. 3298 unsigned NameLen = F->getNameLen(); 3299 if (!F->hasInternalLinkage() && NameLen) { 3300 const char *NameStr = F->getNameStart(); 3301 if (NameStr[0] == 'c' && 3302 ((NameLen == 8 && !strcmp(NameStr, "copysign")) || 3303 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) { 3304 if (I.getNumOperands() == 3 && // Basic sanity checks. 3305 I.getOperand(1)->getType()->isFloatingPoint() && 3306 I.getType() == I.getOperand(1)->getType() && 3307 I.getType() == I.getOperand(2)->getType()) { 3308 SDOperand LHS = getValue(I.getOperand(1)); 3309 SDOperand RHS = getValue(I.getOperand(2)); 3310 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(), 3311 LHS, RHS)); 3312 return; 3313 } 3314 } else if (NameStr[0] == 'f' && 3315 ((NameLen == 4 && !strcmp(NameStr, "fabs")) || 3316 (NameLen == 5 && !strcmp(NameStr, "fabsf")) || 3317 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) { 3318 if (I.getNumOperands() == 2 && // Basic sanity checks. 3319 I.getOperand(1)->getType()->isFloatingPoint() && 3320 I.getType() == I.getOperand(1)->getType()) { 3321 SDOperand Tmp = getValue(I.getOperand(1)); 3322 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp)); 3323 return; 3324 } 3325 } else if (NameStr[0] == 's' && 3326 ((NameLen == 3 && !strcmp(NameStr, "sin")) || 3327 (NameLen == 4 && !strcmp(NameStr, "sinf")) || 3328 (NameLen == 4 && !strcmp(NameStr, "sinl")))) { 3329 if (I.getNumOperands() == 2 && // Basic sanity checks. 3330 I.getOperand(1)->getType()->isFloatingPoint() && 3331 I.getType() == I.getOperand(1)->getType()) { 3332 SDOperand Tmp = getValue(I.getOperand(1)); 3333 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp)); 3334 return; 3335 } 3336 } else if (NameStr[0] == 'c' && 3337 ((NameLen == 3 && !strcmp(NameStr, "cos")) || 3338 (NameLen == 4 && !strcmp(NameStr, "cosf")) || 3339 (NameLen == 4 && !strcmp(NameStr, "cosl")))) { 3340 if (I.getNumOperands() == 2 && // Basic sanity checks. 3341 I.getOperand(1)->getType()->isFloatingPoint() && 3342 I.getType() == I.getOperand(1)->getType()) { 3343 SDOperand Tmp = getValue(I.getOperand(1)); 3344 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp)); 3345 return; 3346 } 3347 } 3348 } 3349 } else if (isa<InlineAsm>(I.getOperand(0))) { 3350 visitInlineAsm(&I); 3351 return; 3352 } 3353 3354 SDOperand Callee; 3355 if (!RenameFn) 3356 Callee = getValue(I.getOperand(0)); 3357 else 3358 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 3359 3360 LowerCallTo(&I, Callee, I.isTailCall()); 3361} 3362 3363 3364void SelectionDAGLowering::visitGetResult(GetResultInst &I) { 3365 if (isa<UndefValue>(I.getOperand(0))) { 3366 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())); 3367 setValue(&I, Undef); 3368 } else { 3369 SDOperand Call = getValue(I.getOperand(0)); 3370 3371 // To add support for individual return values with aggregate types, 3372 // we'd need a way to take a getresult index and determine which 3373 // values of the Call SDNode are associated with it. 3374 assert(TLI.getValueType(I.getType(), true) != MVT::Other && 3375 "Individual return values must not be aggregates!"); 3376 3377 setValue(&I, SDOperand(Call.Val, I.getIndex())); 3378 } 3379} 3380 3381 3382/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 3383/// this value and returns the result as a ValueVT value. This uses 3384/// Chain/Flag as the input and updates them for the output Chain/Flag. 3385/// If the Flag pointer is NULL, no flag is used. 3386SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 3387 SDOperand &Chain, SDOperand *Flag)const{ 3388 // Assemble the legal parts into the final values. 3389 SmallVector<SDOperand, 4> Values(ValueVTs.size()); 3390 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) { 3391 // Copy the legal parts from the registers. 3392 MVT::ValueType ValueVT = ValueVTs[Value]; 3393 unsigned NumRegs = TLI->getNumRegisters(ValueVT); 3394 MVT::ValueType RegisterVT = RegVTs[Value]; 3395 3396 SmallVector<SDOperand, 8> Parts(NumRegs); 3397 for (unsigned i = 0; i != NumRegs; ++i) { 3398 SDOperand P = Flag ? 3399 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag) : 3400 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT); 3401 Chain = P.getValue(1); 3402 if (Flag) 3403 *Flag = P.getValue(2); 3404 Parts[Part+i] = P; 3405 } 3406 3407 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT, 3408 ValueVT); 3409 Part += NumRegs; 3410 } 3411 return DAG.getNode(ISD::MERGE_VALUES, 3412 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 3413 &Values[0], ValueVTs.size()); 3414} 3415 3416/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 3417/// specified value into the registers specified by this object. This uses 3418/// Chain/Flag as the input and updates them for the output Chain/Flag. 3419/// If the Flag pointer is NULL, no flag is used. 3420void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG, 3421 SDOperand &Chain, SDOperand *Flag) const { 3422 // Get the list of the values's legal parts. 3423 unsigned NumRegs = Regs.size(); 3424 SmallVector<SDOperand, 8> Parts(NumRegs); 3425 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) { 3426 MVT::ValueType ValueVT = ValueVTs[Value]; 3427 unsigned NumParts = TLI->getNumRegisters(ValueVT); 3428 MVT::ValueType RegisterVT = RegVTs[Value]; 3429 3430 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value), 3431 &Parts[Part], NumParts, RegisterVT); 3432 Part += NumParts; 3433 } 3434 3435 // Copy the parts into the registers. 3436 SmallVector<SDOperand, 8> Chains(NumRegs); 3437 for (unsigned i = 0; i != NumRegs; ++i) { 3438 SDOperand Part = Flag ? 3439 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) : 3440 DAG.getCopyToReg(Chain, Regs[i], Parts[i]); 3441 Chains[i] = Part.getValue(0); 3442 if (Flag) 3443 *Flag = Part.getValue(1); 3444 } 3445 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs); 3446} 3447 3448/// AddInlineAsmOperands - Add this value to the specified inlineasm node 3449/// operand list. This adds the code marker and includes the number of 3450/// values added into it. 3451void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG, 3452 std::vector<SDOperand> &Ops) const { 3453 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy(); 3454 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy)); 3455 for (unsigned Value = 0, Reg = 0; Value != ValueVTs.size(); ++Value) { 3456 MVT::ValueType ValueVT = ValueVTs[Value]; 3457 unsigned NumRegs = TLI->getNumRegisters(ValueVT); 3458 MVT::ValueType RegisterVT = RegVTs[Value]; 3459 for (unsigned i = 0; i != NumRegs; ++i) { 3460 SDOperand RegOp = DAG.getRegister(Regs[Reg+i], RegisterVT); 3461 Ops.push_back(RegOp); 3462 } 3463 Reg += NumRegs; 3464 } 3465} 3466 3467/// isAllocatableRegister - If the specified register is safe to allocate, 3468/// i.e. it isn't a stack pointer or some other special register, return the 3469/// register class for the register. Otherwise, return null. 3470static const TargetRegisterClass * 3471isAllocatableRegister(unsigned Reg, MachineFunction &MF, 3472 const TargetLowering &TLI, 3473 const TargetRegisterInfo *TRI) { 3474 MVT::ValueType FoundVT = MVT::Other; 3475 const TargetRegisterClass *FoundRC = 0; 3476 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(), 3477 E = TRI->regclass_end(); RCI != E; ++RCI) { 3478 MVT::ValueType ThisVT = MVT::Other; 3479 3480 const TargetRegisterClass *RC = *RCI; 3481 // If none of the the value types for this register class are valid, we 3482 // can't use it. For example, 64-bit reg classes on 32-bit targets. 3483 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 3484 I != E; ++I) { 3485 if (TLI.isTypeLegal(*I)) { 3486 // If we have already found this register in a different register class, 3487 // choose the one with the largest VT specified. For example, on 3488 // PowerPC, we favor f64 register classes over f32. 3489 if (FoundVT == MVT::Other || 3490 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) { 3491 ThisVT = *I; 3492 break; 3493 } 3494 } 3495 } 3496 3497 if (ThisVT == MVT::Other) continue; 3498 3499 // NOTE: This isn't ideal. In particular, this might allocate the 3500 // frame pointer in functions that need it (due to them not being taken 3501 // out of allocation, because a variable sized allocation hasn't been seen 3502 // yet). This is a slight code pessimization, but should still work. 3503 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF), 3504 E = RC->allocation_order_end(MF); I != E; ++I) 3505 if (*I == Reg) { 3506 // We found a matching register class. Keep looking at others in case 3507 // we find one with larger registers that this physreg is also in. 3508 FoundRC = RC; 3509 FoundVT = ThisVT; 3510 break; 3511 } 3512 } 3513 return FoundRC; 3514} 3515 3516 3517namespace { 3518/// AsmOperandInfo - This contains information for each constraint that we are 3519/// lowering. 3520struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 3521 /// CallOperand - If this is the result output operand or a clobber 3522 /// this is null, otherwise it is the incoming operand to the CallInst. 3523 /// This gets modified as the asm is processed. 3524 SDOperand CallOperand; 3525 3526 /// AssignedRegs - If this is a register or register class operand, this 3527 /// contains the set of register corresponding to the operand. 3528 RegsForValue AssignedRegs; 3529 3530 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info) 3531 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) { 3532 } 3533 3534 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers 3535 /// busy in OutputRegs/InputRegs. 3536 void MarkAllocatedRegs(bool isOutReg, bool isInReg, 3537 std::set<unsigned> &OutputRegs, 3538 std::set<unsigned> &InputRegs, 3539 const TargetRegisterInfo &TRI) const { 3540 if (isOutReg) { 3541 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 3542 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI); 3543 } 3544 if (isInReg) { 3545 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 3546 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI); 3547 } 3548 } 3549 3550private: 3551 /// MarkRegAndAliases - Mark the specified register and all aliases in the 3552 /// specified set. 3553 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 3554 const TargetRegisterInfo &TRI) { 3555 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg"); 3556 Regs.insert(Reg); 3557 if (const unsigned *Aliases = TRI.getAliasSet(Reg)) 3558 for (; *Aliases; ++Aliases) 3559 Regs.insert(*Aliases); 3560 } 3561}; 3562} // end anon namespace. 3563 3564 3565/// GetRegistersForValue - Assign registers (virtual or physical) for the 3566/// specified operand. We prefer to assign virtual registers, to allow the 3567/// register allocator handle the assignment process. However, if the asm uses 3568/// features that we can't model on machineinstrs, we have SDISel do the 3569/// allocation. This produces generally horrible, but correct, code. 3570/// 3571/// OpInfo describes the operand. 3572/// HasEarlyClobber is true if there are any early clobber constraints (=&r) 3573/// or any explicitly clobbered registers. 3574/// Input and OutputRegs are the set of already allocated physical registers. 3575/// 3576void SelectionDAGLowering:: 3577GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber, 3578 std::set<unsigned> &OutputRegs, 3579 std::set<unsigned> &InputRegs) { 3580 // Compute whether this value requires an input register, an output register, 3581 // or both. 3582 bool isOutReg = false; 3583 bool isInReg = false; 3584 switch (OpInfo.Type) { 3585 case InlineAsm::isOutput: 3586 isOutReg = true; 3587 3588 // If this is an early-clobber output, or if there is an input 3589 // constraint that matches this, we need to reserve the input register 3590 // so no other inputs allocate to it. 3591 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput; 3592 break; 3593 case InlineAsm::isInput: 3594 isInReg = true; 3595 isOutReg = false; 3596 break; 3597 case InlineAsm::isClobber: 3598 isOutReg = true; 3599 isInReg = true; 3600 break; 3601 } 3602 3603 3604 MachineFunction &MF = DAG.getMachineFunction(); 3605 std::vector<unsigned> Regs; 3606 3607 // If this is a constraint for a single physreg, or a constraint for a 3608 // register class, find it. 3609 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 3610 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 3611 OpInfo.ConstraintVT); 3612 3613 unsigned NumRegs = 1; 3614 if (OpInfo.ConstraintVT != MVT::Other) 3615 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT); 3616 MVT::ValueType RegVT; 3617 MVT::ValueType ValueVT = OpInfo.ConstraintVT; 3618 3619 3620 // If this is a constraint for a specific physical register, like {r17}, 3621 // assign it now. 3622 if (PhysReg.first) { 3623 if (OpInfo.ConstraintVT == MVT::Other) 3624 ValueVT = *PhysReg.second->vt_begin(); 3625 3626 // Get the actual register value type. This is important, because the user 3627 // may have asked for (e.g.) the AX register in i32 type. We need to 3628 // remember that AX is actually i16 to get the right extension. 3629 RegVT = *PhysReg.second->vt_begin(); 3630 3631 // This is a explicit reference to a physical register. 3632 Regs.push_back(PhysReg.first); 3633 3634 // If this is an expanded reference, add the rest of the regs to Regs. 3635 if (NumRegs != 1) { 3636 TargetRegisterClass::iterator I = PhysReg.second->begin(); 3637 TargetRegisterClass::iterator E = PhysReg.second->end(); 3638 for (; *I != PhysReg.first; ++I) 3639 assert(I != E && "Didn't find reg!"); 3640 3641 // Already added the first reg. 3642 --NumRegs; ++I; 3643 for (; NumRegs; --NumRegs, ++I) { 3644 assert(I != E && "Ran out of registers to allocate!"); 3645 Regs.push_back(*I); 3646 } 3647 } 3648 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT); 3649 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 3650 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 3651 return; 3652 } 3653 3654 // Otherwise, if this was a reference to an LLVM register class, create vregs 3655 // for this reference. 3656 std::vector<unsigned> RegClassRegs; 3657 const TargetRegisterClass *RC = PhysReg.second; 3658 if (RC) { 3659 // If this is an early clobber or tied register, our regalloc doesn't know 3660 // how to maintain the constraint. If it isn't, go ahead and create vreg 3661 // and let the regalloc do the right thing. 3662 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber && 3663 // If there is some other early clobber and this is an input register, 3664 // then we are forced to pre-allocate the input reg so it doesn't 3665 // conflict with the earlyclobber. 3666 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) { 3667 RegVT = *PhysReg.second->vt_begin(); 3668 3669 if (OpInfo.ConstraintVT == MVT::Other) 3670 ValueVT = RegVT; 3671 3672 // Create the appropriate number of virtual registers. 3673 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 3674 for (; NumRegs; --NumRegs) 3675 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second)); 3676 3677 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT); 3678 return; 3679 } 3680 3681 // Otherwise, we can't allocate it. Let the code below figure out how to 3682 // maintain these constraints. 3683 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end()); 3684 3685 } else { 3686 // This is a reference to a register class that doesn't directly correspond 3687 // to an LLVM register class. Allocate NumRegs consecutive, available, 3688 // registers from the class. 3689 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode, 3690 OpInfo.ConstraintVT); 3691 } 3692 3693 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 3694 unsigned NumAllocated = 0; 3695 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) { 3696 unsigned Reg = RegClassRegs[i]; 3697 // See if this register is available. 3698 if ((isOutReg && OutputRegs.count(Reg)) || // Already used. 3699 (isInReg && InputRegs.count(Reg))) { // Already used. 3700 // Make sure we find consecutive registers. 3701 NumAllocated = 0; 3702 continue; 3703 } 3704 3705 // Check to see if this register is allocatable (i.e. don't give out the 3706 // stack pointer). 3707 if (RC == 0) { 3708 RC = isAllocatableRegister(Reg, MF, TLI, TRI); 3709 if (!RC) { // Couldn't allocate this register. 3710 // Reset NumAllocated to make sure we return consecutive registers. 3711 NumAllocated = 0; 3712 continue; 3713 } 3714 } 3715 3716 // Okay, this register is good, we can use it. 3717 ++NumAllocated; 3718 3719 // If we allocated enough consecutive registers, succeed. 3720 if (NumAllocated == NumRegs) { 3721 unsigned RegStart = (i-NumAllocated)+1; 3722 unsigned RegEnd = i+1; 3723 // Mark all of the allocated registers used. 3724 for (unsigned i = RegStart; i != RegEnd; ++i) 3725 Regs.push_back(RegClassRegs[i]); 3726 3727 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(), 3728 OpInfo.ConstraintVT); 3729 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 3730 return; 3731 } 3732 } 3733 3734 // Otherwise, we couldn't allocate enough registers for this. 3735 return; 3736} 3737 3738 3739/// visitInlineAsm - Handle a call to an InlineAsm object. 3740/// 3741void SelectionDAGLowering::visitInlineAsm(CallSite CS) { 3742 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 3743 3744 /// ConstraintOperands - Information about all of the constraints. 3745 std::vector<SDISelAsmOperandInfo> ConstraintOperands; 3746 3747 SDOperand Chain = getRoot(); 3748 SDOperand Flag; 3749 3750 std::set<unsigned> OutputRegs, InputRegs; 3751 3752 // Do a prepass over the constraints, canonicalizing them, and building up the 3753 // ConstraintOperands list. 3754 std::vector<InlineAsm::ConstraintInfo> 3755 ConstraintInfos = IA->ParseConstraints(); 3756 3757 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output 3758 // constraint. If so, we can't let the register allocator allocate any input 3759 // registers, because it will not know to avoid the earlyclobbered output reg. 3760 bool SawEarlyClobber = false; 3761 3762 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 3763 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 3764 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i])); 3765 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 3766 3767 MVT::ValueType OpVT = MVT::Other; 3768 3769 // Compute the value type for each operand. 3770 switch (OpInfo.Type) { 3771 case InlineAsm::isOutput: 3772 if (!OpInfo.isIndirect) { 3773 // The return value of the call is this value. As such, there is no 3774 // corresponding argument. 3775 assert(CS.getType() != Type::VoidTy && "Bad inline asm!"); 3776 OpVT = TLI.getValueType(CS.getType()); 3777 } else { 3778 OpInfo.CallOperandVal = CS.getArgument(ArgNo++); 3779 } 3780 break; 3781 case InlineAsm::isInput: 3782 OpInfo.CallOperandVal = CS.getArgument(ArgNo++); 3783 break; 3784 case InlineAsm::isClobber: 3785 // Nothing to do. 3786 break; 3787 } 3788 3789 // If this is an input or an indirect output, process the call argument. 3790 // BasicBlocks are labels, currently appearing only in asm's. 3791 if (OpInfo.CallOperandVal) { 3792 if (isa<BasicBlock>(OpInfo.CallOperandVal)) 3793 OpInfo.CallOperand = 3794 DAG.getBasicBlock(FuncInfo.MBBMap[cast<BasicBlock>( 3795 OpInfo.CallOperandVal)]); 3796 else { 3797 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 3798 const Type *OpTy = OpInfo.CallOperandVal->getType(); 3799 // If this is an indirect operand, the operand is a pointer to the 3800 // accessed type. 3801 if (OpInfo.isIndirect) 3802 OpTy = cast<PointerType>(OpTy)->getElementType(); 3803 3804 // If OpTy is not a first-class value, it may be a struct/union that we 3805 // can tile with integers. 3806 if (!OpTy->isFirstClassType() && OpTy->isSized()) { 3807 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 3808 switch (BitSize) { 3809 default: break; 3810 case 1: 3811 case 8: 3812 case 16: 3813 case 32: 3814 case 64: 3815 OpTy = IntegerType::get(BitSize); 3816 break; 3817 } 3818 } 3819 3820 OpVT = TLI.getValueType(OpTy, true); 3821 } 3822 } 3823 3824 OpInfo.ConstraintVT = OpVT; 3825 3826 // Compute the constraint code and ConstraintType to use. 3827 OpInfo.ComputeConstraintToUse(TLI); 3828 3829 // Keep track of whether we see an earlyclobber. 3830 SawEarlyClobber |= OpInfo.isEarlyClobber; 3831 3832 // If we see a clobber of a register, it is an early clobber. 3833 if (!SawEarlyClobber && 3834 OpInfo.Type == InlineAsm::isClobber && 3835 OpInfo.ConstraintType == TargetLowering::C_Register) { 3836 // Note that we want to ignore things that we don't trick here, like 3837 // dirflag, fpsr, flags, etc. 3838 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 3839 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 3840 OpInfo.ConstraintVT); 3841 if (PhysReg.first || PhysReg.second) { 3842 // This is a register we know of. 3843 SawEarlyClobber = true; 3844 } 3845 } 3846 3847 // If this is a memory input, and if the operand is not indirect, do what we 3848 // need to to provide an address for the memory input. 3849 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 3850 !OpInfo.isIndirect) { 3851 assert(OpInfo.Type == InlineAsm::isInput && 3852 "Can only indirectify direct input operands!"); 3853 3854 // Memory operands really want the address of the value. If we don't have 3855 // an indirect input, put it in the constpool if we can, otherwise spill 3856 // it to a stack slot. 3857 3858 // If the operand is a float, integer, or vector constant, spill to a 3859 // constant pool entry to get its address. 3860 Value *OpVal = OpInfo.CallOperandVal; 3861 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 3862 isa<ConstantVector>(OpVal)) { 3863 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 3864 TLI.getPointerTy()); 3865 } else { 3866 // Otherwise, create a stack slot and emit a store to it before the 3867 // asm. 3868 const Type *Ty = OpVal->getType(); 3869 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty); 3870 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty); 3871 MachineFunction &MF = DAG.getMachineFunction(); 3872 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align); 3873 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 3874 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0); 3875 OpInfo.CallOperand = StackSlot; 3876 } 3877 3878 // There is no longer a Value* corresponding to this operand. 3879 OpInfo.CallOperandVal = 0; 3880 // It is now an indirect operand. 3881 OpInfo.isIndirect = true; 3882 } 3883 3884 // If this constraint is for a specific register, allocate it before 3885 // anything else. 3886 if (OpInfo.ConstraintType == TargetLowering::C_Register) 3887 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs); 3888 } 3889 ConstraintInfos.clear(); 3890 3891 3892 // Second pass - Loop over all of the operands, assigning virtual or physregs 3893 // to registerclass operands. 3894 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 3895 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 3896 3897 // C_Register operands have already been allocated, Other/Memory don't need 3898 // to be. 3899 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 3900 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs); 3901 } 3902 3903 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 3904 std::vector<SDOperand> AsmNodeOperands; 3905 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain 3906 AsmNodeOperands.push_back( 3907 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other)); 3908 3909 3910 // Loop over all of the inputs, copying the operand values into the 3911 // appropriate registers and processing the output regs. 3912 RegsForValue RetValRegs; 3913 3914 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 3915 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 3916 3917 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 3918 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 3919 3920 switch (OpInfo.Type) { 3921 case InlineAsm::isOutput: { 3922 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 3923 OpInfo.ConstraintType != TargetLowering::C_Register) { 3924 // Memory output, or 'other' output (e.g. 'X' constraint). 3925 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 3926 3927 // Add information to the INLINEASM node to know about this output. 3928 unsigned ResOpType = 4/*MEM*/ | (1 << 3); 3929 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 3930 TLI.getPointerTy())); 3931 AsmNodeOperands.push_back(OpInfo.CallOperand); 3932 break; 3933 } 3934 3935 // Otherwise, this is a register or register class output. 3936 3937 // Copy the output from the appropriate register. Find a register that 3938 // we can use. 3939 if (OpInfo.AssignedRegs.Regs.empty()) { 3940 cerr << "Couldn't allocate output reg for contraint '" 3941 << OpInfo.ConstraintCode << "'!\n"; 3942 exit(1); 3943 } 3944 3945 if (!OpInfo.isIndirect) { 3946 // This is the result value of the call. 3947 assert(RetValRegs.Regs.empty() && 3948 "Cannot have multiple output constraints yet!"); 3949 assert(CS.getType() != Type::VoidTy && "Bad inline asm!"); 3950 RetValRegs = OpInfo.AssignedRegs; 3951 } else { 3952 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 3953 OpInfo.CallOperandVal)); 3954 } 3955 3956 // Add information to the INLINEASM node to know that this register is 3957 // set. 3958 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, 3959 AsmNodeOperands); 3960 break; 3961 } 3962 case InlineAsm::isInput: { 3963 SDOperand InOperandVal = OpInfo.CallOperand; 3964 3965 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint? 3966 // If this is required to match an output register we have already set, 3967 // just use its register. 3968 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str()); 3969 3970 // Scan until we find the definition we already emitted of this operand. 3971 // When we find it, create a RegsForValue operand. 3972 unsigned CurOp = 2; // The first operand. 3973 for (; OperandNo; --OperandNo) { 3974 // Advance to the next operand. 3975 unsigned NumOps = 3976 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue(); 3977 assert(((NumOps & 7) == 2 /*REGDEF*/ || 3978 (NumOps & 7) == 4 /*MEM*/) && 3979 "Skipped past definitions?"); 3980 CurOp += (NumOps>>3)+1; 3981 } 3982 3983 unsigned NumOps = 3984 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue(); 3985 if ((NumOps & 7) == 2 /*REGDEF*/) { 3986 // Add NumOps>>3 registers to MatchedRegs. 3987 RegsForValue MatchedRegs; 3988 MatchedRegs.TLI = &TLI; 3989 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType()); 3990 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType()); 3991 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) { 3992 unsigned Reg = 3993 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg(); 3994 MatchedRegs.Regs.push_back(Reg); 3995 } 3996 3997 // Use the produced MatchedRegs object to 3998 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag); 3999 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands); 4000 break; 4001 } else { 4002 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!"); 4003 assert((NumOps >> 3) == 1 && "Unexpected number of operands"); 4004 // Add information to the INLINEASM node to know about this input. 4005 unsigned ResOpType = 4/*MEM*/ | (1 << 3); 4006 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 4007 TLI.getPointerTy())); 4008 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 4009 break; 4010 } 4011 } 4012 4013 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 4014 assert(!OpInfo.isIndirect && 4015 "Don't know how to handle indirect other inputs yet!"); 4016 4017 std::vector<SDOperand> Ops; 4018 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0], 4019 Ops, DAG); 4020 if (Ops.empty()) { 4021 cerr << "Invalid operand for inline asm constraint '" 4022 << OpInfo.ConstraintCode << "'!\n"; 4023 exit(1); 4024 } 4025 4026 // Add information to the INLINEASM node to know about this input. 4027 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3); 4028 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 4029 TLI.getPointerTy())); 4030 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 4031 break; 4032 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 4033 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 4034 assert(InOperandVal.getValueType() == TLI.getPointerTy() && 4035 "Memory operands expect pointer values"); 4036 4037 // Add information to the INLINEASM node to know about this input. 4038 unsigned ResOpType = 4/*MEM*/ | (1 << 3); 4039 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 4040 TLI.getPointerTy())); 4041 AsmNodeOperands.push_back(InOperandVal); 4042 break; 4043 } 4044 4045 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 4046 OpInfo.ConstraintType == TargetLowering::C_Register) && 4047 "Unknown constraint type!"); 4048 assert(!OpInfo.isIndirect && 4049 "Don't know how to handle indirect register inputs yet!"); 4050 4051 // Copy the input into the appropriate registers. 4052 assert(!OpInfo.AssignedRegs.Regs.empty() && 4053 "Couldn't allocate input reg!"); 4054 4055 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag); 4056 4057 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, 4058 AsmNodeOperands); 4059 break; 4060 } 4061 case InlineAsm::isClobber: { 4062 // Add the clobbered value to the operand list, so that the register 4063 // allocator is aware that the physreg got clobbered. 4064 if (!OpInfo.AssignedRegs.Regs.empty()) 4065 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, 4066 AsmNodeOperands); 4067 break; 4068 } 4069 } 4070 } 4071 4072 // Finish up input operands. 4073 AsmNodeOperands[0] = Chain; 4074 if (Flag.Val) AsmNodeOperands.push_back(Flag); 4075 4076 Chain = DAG.getNode(ISD::INLINEASM, 4077 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2, 4078 &AsmNodeOperands[0], AsmNodeOperands.size()); 4079 Flag = Chain.getValue(1); 4080 4081 // If this asm returns a register value, copy the result from that register 4082 // and set it as the value of the call. 4083 if (!RetValRegs.Regs.empty()) { 4084 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag); 4085 4086 // If the result of the inline asm is a vector, it may have the wrong 4087 // width/num elts. Make sure to convert it to the right type with 4088 // bit_convert. 4089 if (MVT::isVector(Val.getValueType())) { 4090 const VectorType *VTy = cast<VectorType>(CS.getType()); 4091 MVT::ValueType DesiredVT = TLI.getValueType(VTy); 4092 4093 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val); 4094 } 4095 4096 setValue(CS.getInstruction(), Val); 4097 } 4098 4099 std::vector<std::pair<SDOperand, Value*> > StoresToEmit; 4100 4101 // Process indirect outputs, first output all of the flagged copies out of 4102 // physregs. 4103 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 4104 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 4105 Value *Ptr = IndirectStoresToEmit[i].second; 4106 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag); 4107 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 4108 } 4109 4110 // Emit the non-flagged stores from the physregs. 4111 SmallVector<SDOperand, 8> OutChains; 4112 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) 4113 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first, 4114 getValue(StoresToEmit[i].second), 4115 StoresToEmit[i].second, 0)); 4116 if (!OutChains.empty()) 4117 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, 4118 &OutChains[0], OutChains.size()); 4119 DAG.setRoot(Chain); 4120} 4121 4122 4123void SelectionDAGLowering::visitMalloc(MallocInst &I) { 4124 SDOperand Src = getValue(I.getOperand(0)); 4125 4126 MVT::ValueType IntPtr = TLI.getPointerTy(); 4127 4128 if (IntPtr < Src.getValueType()) 4129 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src); 4130 else if (IntPtr > Src.getValueType()) 4131 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src); 4132 4133 // Scale the source by the type size. 4134 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType()); 4135 Src = DAG.getNode(ISD::MUL, Src.getValueType(), 4136 Src, DAG.getIntPtrConstant(ElementSize)); 4137 4138 TargetLowering::ArgListTy Args; 4139 TargetLowering::ArgListEntry Entry; 4140 Entry.Node = Src; 4141 Entry.Ty = TLI.getTargetData()->getIntPtrType(); 4142 Args.push_back(Entry); 4143 4144 std::pair<SDOperand,SDOperand> Result = 4145 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C, 4146 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG); 4147 setValue(&I, Result.first); // Pointers always fit in registers 4148 DAG.setRoot(Result.second); 4149} 4150 4151void SelectionDAGLowering::visitFree(FreeInst &I) { 4152 TargetLowering::ArgListTy Args; 4153 TargetLowering::ArgListEntry Entry; 4154 Entry.Node = getValue(I.getOperand(0)); 4155 Entry.Ty = TLI.getTargetData()->getIntPtrType(); 4156 Args.push_back(Entry); 4157 MVT::ValueType IntPtr = TLI.getPointerTy(); 4158 std::pair<SDOperand,SDOperand> Result = 4159 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, 4160 CallingConv::C, true, 4161 DAG.getExternalSymbol("free", IntPtr), Args, DAG); 4162 DAG.setRoot(Result.second); 4163} 4164 4165// EmitInstrWithCustomInserter - This method should be implemented by targets 4166// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These 4167// instructions are special in various ways, which require special support to 4168// insert. The specified MachineInstr is created but not inserted into any 4169// basic blocks, and the scheduler passes ownership of it to this method. 4170MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 4171 MachineBasicBlock *MBB) { 4172 cerr << "If a target marks an instruction with " 4173 << "'usesCustomDAGSchedInserter', it must implement " 4174 << "TargetLowering::EmitInstrWithCustomInserter!\n"; 4175 abort(); 4176 return 0; 4177} 4178 4179void SelectionDAGLowering::visitVAStart(CallInst &I) { 4180 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 4181 getValue(I.getOperand(1)), 4182 DAG.getSrcValue(I.getOperand(1)))); 4183} 4184 4185void SelectionDAGLowering::visitVAArg(VAArgInst &I) { 4186 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(), 4187 getValue(I.getOperand(0)), 4188 DAG.getSrcValue(I.getOperand(0))); 4189 setValue(&I, V); 4190 DAG.setRoot(V.getValue(1)); 4191} 4192 4193void SelectionDAGLowering::visitVAEnd(CallInst &I) { 4194 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(), 4195 getValue(I.getOperand(1)), 4196 DAG.getSrcValue(I.getOperand(1)))); 4197} 4198 4199void SelectionDAGLowering::visitVACopy(CallInst &I) { 4200 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 4201 getValue(I.getOperand(1)), 4202 getValue(I.getOperand(2)), 4203 DAG.getSrcValue(I.getOperand(1)), 4204 DAG.getSrcValue(I.getOperand(2)))); 4205} 4206 4207/// TargetLowering::LowerArguments - This is the default LowerArguments 4208/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all 4209/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 4210/// integrated into SDISel. 4211std::vector<SDOperand> 4212TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) { 4213 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node. 4214 std::vector<SDOperand> Ops; 4215 Ops.push_back(DAG.getRoot()); 4216 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy())); 4217 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy())); 4218 4219 // Add one result value for each formal argument. 4220 std::vector<MVT::ValueType> RetVals; 4221 unsigned j = 1; 4222 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); 4223 I != E; ++I, ++j) { 4224 MVT::ValueType VT = getValueType(I->getType()); 4225 ISD::ArgFlagsTy Flags; 4226 unsigned OriginalAlignment = 4227 getTargetData()->getABITypeAlignment(I->getType()); 4228 4229 if (F.paramHasAttr(j, ParamAttr::ZExt)) 4230 Flags.setZExt(); 4231 if (F.paramHasAttr(j, ParamAttr::SExt)) 4232 Flags.setSExt(); 4233 if (F.paramHasAttr(j, ParamAttr::InReg)) 4234 Flags.setInReg(); 4235 if (F.paramHasAttr(j, ParamAttr::StructRet)) 4236 Flags.setSRet(); 4237 if (F.paramHasAttr(j, ParamAttr::ByVal)) { 4238 Flags.setByVal(); 4239 const PointerType *Ty = cast<PointerType>(I->getType()); 4240 const Type *ElementTy = Ty->getElementType(); 4241 unsigned FrameAlign = getByValTypeAlignment(ElementTy); 4242 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy); 4243 // For ByVal, alignment should be passed from FE. BE will guess if 4244 // this info is not there but there are cases it cannot get right. 4245 if (F.getParamAlignment(j)) 4246 FrameAlign = F.getParamAlignment(j); 4247 Flags.setByValAlign(FrameAlign); 4248 Flags.setByValSize(FrameSize); 4249 } 4250 if (F.paramHasAttr(j, ParamAttr::Nest)) 4251 Flags.setNest(); 4252 Flags.setOrigAlign(OriginalAlignment); 4253 4254 MVT::ValueType RegisterVT = getRegisterType(VT); 4255 unsigned NumRegs = getNumRegisters(VT); 4256 for (unsigned i = 0; i != NumRegs; ++i) { 4257 RetVals.push_back(RegisterVT); 4258 ISD::ArgFlagsTy MyFlags = Flags; 4259 if (NumRegs > 1 && i == 0) 4260 MyFlags.setSplit(); 4261 // if it isn't first piece, alignment must be 1 4262 else if (i > 0) 4263 MyFlags.setOrigAlign(1); 4264 Ops.push_back(DAG.getArgFlags(MyFlags)); 4265 } 4266 } 4267 4268 RetVals.push_back(MVT::Other); 4269 4270 // Create the node. 4271 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, 4272 DAG.getVTList(&RetVals[0], RetVals.size()), 4273 &Ops[0], Ops.size()).Val; 4274 4275 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but 4276 // allows exposing the loads that may be part of the argument access to the 4277 // first DAGCombiner pass. 4278 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG); 4279 4280 // The number of results should match up, except that the lowered one may have 4281 // an extra flag result. 4282 assert((Result->getNumValues() == TmpRes.Val->getNumValues() || 4283 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() && 4284 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag)) 4285 && "Lowering produced unexpected number of results!"); 4286 Result = TmpRes.Val; 4287 4288 unsigned NumArgRegs = Result->getNumValues() - 1; 4289 DAG.setRoot(SDOperand(Result, NumArgRegs)); 4290 4291 // Set up the return result vector. 4292 Ops.clear(); 4293 unsigned i = 0; 4294 unsigned Idx = 1; 4295 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 4296 ++I, ++Idx) { 4297 MVT::ValueType VT = getValueType(I->getType()); 4298 MVT::ValueType PartVT = getRegisterType(VT); 4299 4300 unsigned NumParts = getNumRegisters(VT); 4301 SmallVector<SDOperand, 4> Parts(NumParts); 4302 for (unsigned j = 0; j != NumParts; ++j) 4303 Parts[j] = SDOperand(Result, i++); 4304 4305 ISD::NodeType AssertOp = ISD::DELETED_NODE; 4306 if (F.paramHasAttr(Idx, ParamAttr::SExt)) 4307 AssertOp = ISD::AssertSext; 4308 else if (F.paramHasAttr(Idx, ParamAttr::ZExt)) 4309 AssertOp = ISD::AssertZext; 4310 4311 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT, 4312 AssertOp)); 4313 } 4314 assert(i == NumArgRegs && "Argument register count mismatch!"); 4315 return Ops; 4316} 4317 4318 4319/// TargetLowering::LowerCallTo - This is the default LowerCallTo 4320/// implementation, which just inserts an ISD::CALL node, which is later custom 4321/// lowered by the target to something concrete. FIXME: When all targets are 4322/// migrated to using ISD::CALL, this hook should be integrated into SDISel. 4323std::pair<SDOperand, SDOperand> 4324TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, 4325 bool RetSExt, bool RetZExt, bool isVarArg, 4326 unsigned CallingConv, bool isTailCall, 4327 SDOperand Callee, 4328 ArgListTy &Args, SelectionDAG &DAG) { 4329 SmallVector<SDOperand, 32> Ops; 4330 Ops.push_back(Chain); // Op#0 - Chain 4331 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC 4332 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg 4333 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail 4334 Ops.push_back(Callee); 4335 4336 // Handle all of the outgoing arguments. 4337 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 4338 MVT::ValueType VT = getValueType(Args[i].Ty); 4339 SDOperand Op = Args[i].Node; 4340 ISD::ArgFlagsTy Flags; 4341 unsigned OriginalAlignment = 4342 getTargetData()->getABITypeAlignment(Args[i].Ty); 4343 4344 if (Args[i].isZExt) 4345 Flags.setZExt(); 4346 if (Args[i].isSExt) 4347 Flags.setSExt(); 4348 if (Args[i].isInReg) 4349 Flags.setInReg(); 4350 if (Args[i].isSRet) 4351 Flags.setSRet(); 4352 if (Args[i].isByVal) { 4353 Flags.setByVal(); 4354 const PointerType *Ty = cast<PointerType>(Args[i].Ty); 4355 const Type *ElementTy = Ty->getElementType(); 4356 unsigned FrameAlign = getByValTypeAlignment(ElementTy); 4357 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy); 4358 // For ByVal, alignment should come from FE. BE will guess if this 4359 // info is not there but there are cases it cannot get right. 4360 if (Args[i].Alignment) 4361 FrameAlign = Args[i].Alignment; 4362 Flags.setByValAlign(FrameAlign); 4363 Flags.setByValSize(FrameSize); 4364 } 4365 if (Args[i].isNest) 4366 Flags.setNest(); 4367 Flags.setOrigAlign(OriginalAlignment); 4368 4369 MVT::ValueType PartVT = getRegisterType(VT); 4370 unsigned NumParts = getNumRegisters(VT); 4371 SmallVector<SDOperand, 4> Parts(NumParts); 4372 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 4373 4374 if (Args[i].isSExt) 4375 ExtendKind = ISD::SIGN_EXTEND; 4376 else if (Args[i].isZExt) 4377 ExtendKind = ISD::ZERO_EXTEND; 4378 4379 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind); 4380 4381 for (unsigned i = 0; i != NumParts; ++i) { 4382 // if it isn't first piece, alignment must be 1 4383 ISD::ArgFlagsTy MyFlags = Flags; 4384 if (NumParts > 1 && i == 0) 4385 MyFlags.setSplit(); 4386 else if (i != 0) 4387 MyFlags.setOrigAlign(1); 4388 4389 Ops.push_back(Parts[i]); 4390 Ops.push_back(DAG.getArgFlags(MyFlags)); 4391 } 4392 } 4393 4394 // Figure out the result value types. We start by making a list of 4395 // the potentially illegal return value types. 4396 SmallVector<MVT::ValueType, 4> LoweredRetTys; 4397 SmallVector<MVT::ValueType, 4> RetTys; 4398 ComputeValueVTs(*this, RetTy, RetTys); 4399 4400 // Then we translate that to a list of legal types. 4401 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 4402 MVT::ValueType VT = RetTys[I]; 4403 MVT::ValueType RegisterVT = getRegisterType(VT); 4404 unsigned NumRegs = getNumRegisters(VT); 4405 for (unsigned i = 0; i != NumRegs; ++i) 4406 LoweredRetTys.push_back(RegisterVT); 4407 } 4408 4409 LoweredRetTys.push_back(MVT::Other); // Always has a chain. 4410 4411 // Create the CALL node. 4412 SDOperand Res = DAG.getNode(ISD::CALL, 4413 DAG.getVTList(&LoweredRetTys[0], 4414 LoweredRetTys.size()), 4415 &Ops[0], Ops.size()); 4416 Chain = Res.getValue(LoweredRetTys.size() - 1); 4417 4418 // Gather up the call result into a single value. 4419 if (RetTy != Type::VoidTy) { 4420 ISD::NodeType AssertOp = ISD::DELETED_NODE; 4421 4422 if (RetSExt) 4423 AssertOp = ISD::AssertSext; 4424 else if (RetZExt) 4425 AssertOp = ISD::AssertZext; 4426 4427 SmallVector<SDOperand, 4> ReturnValues; 4428 unsigned RegNo = 0; 4429 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 4430 MVT::ValueType VT = RetTys[I]; 4431 MVT::ValueType RegisterVT = getRegisterType(VT); 4432 unsigned NumRegs = getNumRegisters(VT); 4433 unsigned RegNoEnd = NumRegs + RegNo; 4434 SmallVector<SDOperand, 4> Results; 4435 for (; RegNo != RegNoEnd; ++RegNo) 4436 Results.push_back(Res.getValue(RegNo)); 4437 SDOperand ReturnValue = 4438 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT, 4439 AssertOp); 4440 ReturnValues.push_back(ReturnValue); 4441 } 4442 Res = ReturnValues.size() == 1 ? ReturnValues.front() : 4443 DAG.getNode(ISD::MERGE_VALUES, 4444 DAG.getVTList(&RetTys[0], RetTys.size()), 4445 &ReturnValues[0], ReturnValues.size()); 4446 } 4447 4448 return std::make_pair(Res, Chain); 4449} 4450 4451SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) { 4452 assert(0 && "LowerOperation not implemented for this target!"); 4453 abort(); 4454 return SDOperand(); 4455} 4456 4457SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op, 4458 SelectionDAG &DAG) { 4459 assert(0 && "CustomPromoteOperation not implemented for this target!"); 4460 abort(); 4461 return SDOperand(); 4462} 4463 4464//===----------------------------------------------------------------------===// 4465// SelectionDAGISel code 4466//===----------------------------------------------------------------------===// 4467 4468unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) { 4469 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT)); 4470} 4471 4472void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { 4473 AU.addRequired<AliasAnalysis>(); 4474 AU.addRequired<CollectorModuleMetadata>(); 4475 AU.setPreservesAll(); 4476} 4477 4478 4479 4480bool SelectionDAGISel::runOnFunction(Function &Fn) { 4481 // Get alias analysis for load/store combining. 4482 AA = &getAnalysis<AliasAnalysis>(); 4483 4484 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine()); 4485 if (MF.getFunction()->hasCollector()) 4486 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction()); 4487 else 4488 GCI = 0; 4489 RegInfo = &MF.getRegInfo(); 4490 DOUT << "\n\n\n=== " << Fn.getName() << "\n"; 4491 4492 FunctionLoweringInfo FuncInfo(TLI, Fn, MF); 4493 4494 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 4495 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator())) 4496 // Mark landing pad. 4497 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad(); 4498 4499 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 4500 SelectBasicBlock(I, MF, FuncInfo); 4501 4502 // Add function live-ins to entry block live-in set. 4503 BasicBlock *EntryBB = &Fn.getEntryBlock(); 4504 BB = FuncInfo.MBBMap[EntryBB]; 4505 if (!RegInfo->livein_empty()) 4506 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(), 4507 E = RegInfo->livein_end(); I != E; ++I) 4508 BB->addLiveIn(I->first); 4509 4510#ifndef NDEBUG 4511 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() && 4512 "Not all catch info was assigned to a landing pad!"); 4513#endif 4514 4515 return true; 4516} 4517 4518void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, 4519 unsigned Reg) { 4520 SDOperand Op = getValue(V); 4521 assert((Op.getOpcode() != ISD::CopyFromReg || 4522 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 4523 "Copy from a reg to the same reg!"); 4524 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 4525 4526 RegsForValue RFV(TLI, Reg, V->getType()); 4527 SDOperand Chain = DAG.getEntryNode(); 4528 RFV.getCopyToRegs(Op, DAG, Chain, 0); 4529 PendingExports.push_back(Chain); 4530} 4531 4532void SelectionDAGISel:: 4533LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) { 4534 // If this is the entry block, emit arguments. 4535 Function &F = *LLVMBB->getParent(); 4536 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo; 4537 SDOperand OldRoot = SDL.DAG.getRoot(); 4538 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG); 4539 4540 unsigned a = 0; 4541 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 4542 AI != E; ++AI, ++a) 4543 if (!AI->use_empty()) { 4544 SDL.setValue(AI, Args[a]); 4545 4546 // If this argument is live outside of the entry block, insert a copy from 4547 // whereever we got it to the vreg that other BB's will reference it as. 4548 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI); 4549 if (VMI != FuncInfo.ValueMap.end()) { 4550 SDL.CopyValueToVirtualRegister(AI, VMI->second); 4551 } 4552 } 4553 4554 // Finally, if the target has anything special to do, allow it to do so. 4555 // FIXME: this should insert code into the DAG! 4556 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction()); 4557} 4558 4559static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB, 4560 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) { 4561 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I) 4562 if (isSelector(I)) { 4563 // Apply the catch info to DestBB. 4564 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]); 4565#ifndef NDEBUG 4566 if (!FLI.MBBMap[SrcBB]->isLandingPad()) 4567 FLI.CatchInfoFound.insert(I); 4568#endif 4569 } 4570} 4571 4572/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the 4573/// DAG and fixes their tailcall attribute operand. 4574static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG, 4575 TargetLowering& TLI) { 4576 SDNode * Ret = NULL; 4577 SDOperand Terminator = DAG.getRoot(); 4578 4579 // Find RET node. 4580 if (Terminator.getOpcode() == ISD::RET) { 4581 Ret = Terminator.Val; 4582 } 4583 4584 // Fix tail call attribute of CALL nodes. 4585 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(), 4586 BI = prior(DAG.allnodes_end()); BI != BE; --BI) { 4587 if (BI->getOpcode() == ISD::CALL) { 4588 SDOperand OpRet(Ret, 0); 4589 SDOperand OpCall(static_cast<SDNode*>(BI), 0); 4590 bool isMarkedTailCall = 4591 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0; 4592 // If CALL node has tail call attribute set to true and the call is not 4593 // eligible (no RET or the target rejects) the attribute is fixed to 4594 // false. The TargetLowering::IsEligibleForTailCallOptimization function 4595 // must correctly identify tail call optimizable calls. 4596 if (isMarkedTailCall && 4597 (Ret==NULL || 4598 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) { 4599 SmallVector<SDOperand, 32> Ops; 4600 unsigned idx=0; 4601 for(SDNode::op_iterator I =OpCall.Val->op_begin(), 4602 E=OpCall.Val->op_end(); I!=E; I++, idx++) { 4603 if (idx!=3) 4604 Ops.push_back(*I); 4605 else 4606 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy())); 4607 } 4608 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size()); 4609 } 4610 } 4611 } 4612} 4613 4614void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB, 4615 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate, 4616 FunctionLoweringInfo &FuncInfo) { 4617 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI); 4618 4619 // Lower any arguments needed in this block if this is the entry block. 4620 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock()) 4621 LowerArguments(LLVMBB, SDL); 4622 4623 BB = FuncInfo.MBBMap[LLVMBB]; 4624 SDL.setCurrentBasicBlock(BB); 4625 4626 MachineModuleInfo *MMI = DAG.getMachineModuleInfo(); 4627 4628 if (MMI && BB->isLandingPad()) { 4629 // Add a label to mark the beginning of the landing pad. Deletion of the 4630 // landing pad can thus be detected via the MachineModuleInfo. 4631 unsigned LabelID = MMI->addLandingPad(BB); 4632 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(), 4633 DAG.getConstant(LabelID, MVT::i32), 4634 DAG.getConstant(1, MVT::i32))); 4635 4636 // Mark exception register as live in. 4637 unsigned Reg = TLI.getExceptionAddressRegister(); 4638 if (Reg) BB->addLiveIn(Reg); 4639 4640 // Mark exception selector register as live in. 4641 Reg = TLI.getExceptionSelectorRegister(); 4642 if (Reg) BB->addLiveIn(Reg); 4643 4644 // FIXME: Hack around an exception handling flaw (PR1508): the personality 4645 // function and list of typeids logically belong to the invoke (or, if you 4646 // like, the basic block containing the invoke), and need to be associated 4647 // with it in the dwarf exception handling tables. Currently however the 4648 // information is provided by an intrinsic (eh.selector) that can be moved 4649 // to unexpected places by the optimizers: if the unwind edge is critical, 4650 // then breaking it can result in the intrinsics being in the successor of 4651 // the landing pad, not the landing pad itself. This results in exceptions 4652 // not being caught because no typeids are associated with the invoke. 4653 // This may not be the only way things can go wrong, but it is the only way 4654 // we try to work around for the moment. 4655 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator()); 4656 4657 if (Br && Br->isUnconditional()) { // Critical edge? 4658 BasicBlock::iterator I, E; 4659 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I) 4660 if (isSelector(I)) 4661 break; 4662 4663 if (I == E) 4664 // No catch info found - try to extract some from the successor. 4665 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo); 4666 } 4667 } 4668 4669 // Lower all of the non-terminator instructions. 4670 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end(); 4671 I != E; ++I) 4672 SDL.visit(*I); 4673 4674 // Ensure that all instructions which are used outside of their defining 4675 // blocks are available as virtual registers. Invoke is handled elsewhere. 4676 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I) 4677 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) { 4678 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I); 4679 if (VMI != FuncInfo.ValueMap.end()) 4680 SDL.CopyValueToVirtualRegister(I, VMI->second); 4681 } 4682 4683 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 4684 // ensure constants are generated when needed. Remember the virtual registers 4685 // that need to be added to the Machine PHI nodes as input. We cannot just 4686 // directly add them, because expansion might result in multiple MBB's for one 4687 // BB. As such, the start of the BB might correspond to a different MBB than 4688 // the end. 4689 // 4690 TerminatorInst *TI = LLVMBB->getTerminator(); 4691 4692 // Emit constants only once even if used by multiple PHI nodes. 4693 std::map<Constant*, unsigned> ConstantsOut; 4694 4695 // Vector bool would be better, but vector<bool> is really slow. 4696 std::vector<unsigned char> SuccsHandled; 4697 if (TI->getNumSuccessors()) 4698 SuccsHandled.resize(BB->getParent()->getNumBlockIDs()); 4699 4700 // Check successor nodes' PHI nodes that expect a constant to be available 4701 // from this block. 4702 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 4703 BasicBlock *SuccBB = TI->getSuccessor(succ); 4704 if (!isa<PHINode>(SuccBB->begin())) continue; 4705 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 4706 4707 // If this terminator has multiple identical successors (common for 4708 // switches), only handle each succ once. 4709 unsigned SuccMBBNo = SuccMBB->getNumber(); 4710 if (SuccsHandled[SuccMBBNo]) continue; 4711 SuccsHandled[SuccMBBNo] = true; 4712 4713 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 4714 PHINode *PN; 4715 4716 // At this point we know that there is a 1-1 correspondence between LLVM PHI 4717 // nodes and Machine PHI nodes, but the incoming operands have not been 4718 // emitted yet. 4719 for (BasicBlock::iterator I = SuccBB->begin(); 4720 (PN = dyn_cast<PHINode>(I)); ++I) { 4721 // Ignore dead phi's. 4722 if (PN->use_empty()) continue; 4723 4724 unsigned Reg; 4725 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 4726 4727 if (Constant *C = dyn_cast<Constant>(PHIOp)) { 4728 unsigned &RegOut = ConstantsOut[C]; 4729 if (RegOut == 0) { 4730 RegOut = FuncInfo.CreateRegForValue(C); 4731 SDL.CopyValueToVirtualRegister(C, RegOut); 4732 } 4733 Reg = RegOut; 4734 } else { 4735 Reg = FuncInfo.ValueMap[PHIOp]; 4736 if (Reg == 0) { 4737 assert(isa<AllocaInst>(PHIOp) && 4738 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 4739 "Didn't codegen value into a register!??"); 4740 Reg = FuncInfo.CreateRegForValue(PHIOp); 4741 SDL.CopyValueToVirtualRegister(PHIOp, Reg); 4742 } 4743 } 4744 4745 // Remember that this register needs to added to the machine PHI node as 4746 // the input for this MBB. 4747 MVT::ValueType VT = TLI.getValueType(PN->getType()); 4748 unsigned NumRegisters = TLI.getNumRegisters(VT); 4749 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 4750 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 4751 } 4752 } 4753 ConstantsOut.clear(); 4754 4755 // Lower the terminator after the copies are emitted. 4756 SDL.visit(*LLVMBB->getTerminator()); 4757 4758 // Copy over any CaseBlock records that may now exist due to SwitchInst 4759 // lowering, as well as any jump table information. 4760 SwitchCases.clear(); 4761 SwitchCases = SDL.SwitchCases; 4762 JTCases.clear(); 4763 JTCases = SDL.JTCases; 4764 BitTestCases.clear(); 4765 BitTestCases = SDL.BitTestCases; 4766 4767 // Make sure the root of the DAG is up-to-date. 4768 DAG.setRoot(SDL.getControlRoot()); 4769 4770 // Check whether calls in this block are real tail calls. Fix up CALL nodes 4771 // with correct tailcall attribute so that the target can rely on the tailcall 4772 // attribute indicating whether the call is really eligible for tail call 4773 // optimization. 4774 CheckDAGForTailCallsAndFixThem(DAG, TLI); 4775} 4776 4777void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) { 4778 DOUT << "Lowered selection DAG:\n"; 4779 DEBUG(DAG.dump()); 4780 4781 // Run the DAG combiner in pre-legalize mode. 4782 DAG.Combine(false, *AA); 4783 4784 DOUT << "Optimized lowered selection DAG:\n"; 4785 DEBUG(DAG.dump()); 4786 4787 // Second step, hack on the DAG until it only uses operations and types that 4788 // the target supports. 4789#if 0 // Enable this some day. 4790 DAG.LegalizeTypes(); 4791 // Someday even later, enable a dag combine pass here. 4792#endif 4793 DAG.Legalize(); 4794 4795 DOUT << "Legalized selection DAG:\n"; 4796 DEBUG(DAG.dump()); 4797 4798 // Run the DAG combiner in post-legalize mode. 4799 DAG.Combine(true, *AA); 4800 4801 DOUT << "Optimized legalized selection DAG:\n"; 4802 DEBUG(DAG.dump()); 4803 4804 if (ViewISelDAGs) DAG.viewGraph(); 4805 4806 // Third, instruction select all of the operations to machine code, adding the 4807 // code to the MachineBasicBlock. 4808 InstructionSelectBasicBlock(DAG); 4809 4810 DOUT << "Selected machine code:\n"; 4811 DEBUG(BB->dump()); 4812} 4813 4814void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF, 4815 FunctionLoweringInfo &FuncInfo) { 4816 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate; 4817 { 4818 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4819 CurDAG = &DAG; 4820 4821 // First step, lower LLVM code to some DAG. This DAG may use operations and 4822 // types that are not supported by the target. 4823 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo); 4824 4825 // Second step, emit the lowered DAG as machine code. 4826 CodeGenAndEmitDAG(DAG); 4827 } 4828 4829 DOUT << "Total amount of phi nodes to update: " 4830 << PHINodesToUpdate.size() << "\n"; 4831 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) 4832 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first 4833 << ", " << PHINodesToUpdate[i].second << ")\n";); 4834 4835 // Next, now that we know what the last MBB the LLVM BB expanded is, update 4836 // PHI nodes in successors. 4837 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) { 4838 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) { 4839 MachineInstr *PHI = PHINodesToUpdate[i].first; 4840 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4841 "This is not a machine PHI node that we are updating!"); 4842 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second, 4843 false)); 4844 PHI->addOperand(MachineOperand::CreateMBB(BB)); 4845 } 4846 return; 4847 } 4848 4849 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) { 4850 // Lower header first, if it wasn't already lowered 4851 if (!BitTestCases[i].Emitted) { 4852 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4853 CurDAG = &HSDAG; 4854 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI); 4855 // Set the current basic block to the mbb we wish to insert the code into 4856 BB = BitTestCases[i].Parent; 4857 HSDL.setCurrentBasicBlock(BB); 4858 // Emit the code 4859 HSDL.visitBitTestHeader(BitTestCases[i]); 4860 HSDAG.setRoot(HSDL.getRoot()); 4861 CodeGenAndEmitDAG(HSDAG); 4862 } 4863 4864 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) { 4865 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4866 CurDAG = &BSDAG; 4867 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI); 4868 // Set the current basic block to the mbb we wish to insert the code into 4869 BB = BitTestCases[i].Cases[j].ThisBB; 4870 BSDL.setCurrentBasicBlock(BB); 4871 // Emit the code 4872 if (j+1 != ej) 4873 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB, 4874 BitTestCases[i].Reg, 4875 BitTestCases[i].Cases[j]); 4876 else 4877 BSDL.visitBitTestCase(BitTestCases[i].Default, 4878 BitTestCases[i].Reg, 4879 BitTestCases[i].Cases[j]); 4880 4881 4882 BSDAG.setRoot(BSDL.getRoot()); 4883 CodeGenAndEmitDAG(BSDAG); 4884 } 4885 4886 // Update PHI Nodes 4887 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) { 4888 MachineInstr *PHI = PHINodesToUpdate[pi].first; 4889 MachineBasicBlock *PHIBB = PHI->getParent(); 4890 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4891 "This is not a machine PHI node that we are updating!"); 4892 // This is "default" BB. We have two jumps to it. From "header" BB and 4893 // from last "case" BB. 4894 if (PHIBB == BitTestCases[i].Default) { 4895 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second, 4896 false)); 4897 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent)); 4898 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second, 4899 false)); 4900 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases. 4901 back().ThisBB)); 4902 } 4903 // One of "cases" BB. 4904 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) { 4905 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB; 4906 if (cBB->succ_end() != 4907 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) { 4908 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second, 4909 false)); 4910 PHI->addOperand(MachineOperand::CreateMBB(cBB)); 4911 } 4912 } 4913 } 4914 } 4915 4916 // If the JumpTable record is filled in, then we need to emit a jump table. 4917 // Updating the PHI nodes is tricky in this case, since we need to determine 4918 // whether the PHI is a successor of the range check MBB or the jump table MBB 4919 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) { 4920 // Lower header first, if it wasn't already lowered 4921 if (!JTCases[i].first.Emitted) { 4922 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4923 CurDAG = &HSDAG; 4924 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI); 4925 // Set the current basic block to the mbb we wish to insert the code into 4926 BB = JTCases[i].first.HeaderBB; 4927 HSDL.setCurrentBasicBlock(BB); 4928 // Emit the code 4929 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first); 4930 HSDAG.setRoot(HSDL.getRoot()); 4931 CodeGenAndEmitDAG(HSDAG); 4932 } 4933 4934 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4935 CurDAG = &JSDAG; 4936 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI); 4937 // Set the current basic block to the mbb we wish to insert the code into 4938 BB = JTCases[i].second.MBB; 4939 JSDL.setCurrentBasicBlock(BB); 4940 // Emit the code 4941 JSDL.visitJumpTable(JTCases[i].second); 4942 JSDAG.setRoot(JSDL.getRoot()); 4943 CodeGenAndEmitDAG(JSDAG); 4944 4945 // Update PHI Nodes 4946 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) { 4947 MachineInstr *PHI = PHINodesToUpdate[pi].first; 4948 MachineBasicBlock *PHIBB = PHI->getParent(); 4949 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4950 "This is not a machine PHI node that we are updating!"); 4951 // "default" BB. We can go there only from header BB. 4952 if (PHIBB == JTCases[i].second.Default) { 4953 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second, 4954 false)); 4955 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB)); 4956 } 4957 // JT BB. Just iterate over successors here 4958 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) { 4959 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second, 4960 false)); 4961 PHI->addOperand(MachineOperand::CreateMBB(BB)); 4962 } 4963 } 4964 } 4965 4966 // If the switch block involved a branch to one of the actual successors, we 4967 // need to update PHI nodes in that block. 4968 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) { 4969 MachineInstr *PHI = PHINodesToUpdate[i].first; 4970 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 4971 "This is not a machine PHI node that we are updating!"); 4972 if (BB->isSuccessor(PHI->getParent())) { 4973 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second, 4974 false)); 4975 PHI->addOperand(MachineOperand::CreateMBB(BB)); 4976 } 4977 } 4978 4979 // If we generated any switch lowering information, build and codegen any 4980 // additional DAGs necessary. 4981 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) { 4982 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>()); 4983 CurDAG = &SDAG; 4984 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI); 4985 4986 // Set the current basic block to the mbb we wish to insert the code into 4987 BB = SwitchCases[i].ThisBB; 4988 SDL.setCurrentBasicBlock(BB); 4989 4990 // Emit the code 4991 SDL.visitSwitchCase(SwitchCases[i]); 4992 SDAG.setRoot(SDL.getRoot()); 4993 CodeGenAndEmitDAG(SDAG); 4994 4995 // Handle any PHI nodes in successors of this chunk, as if we were coming 4996 // from the original BB before switch expansion. Note that PHI nodes can 4997 // occur multiple times in PHINodesToUpdate. We have to be very careful to 4998 // handle them the right number of times. 4999 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS. 5000 for (MachineBasicBlock::iterator Phi = BB->begin(); 5001 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){ 5002 // This value for this PHI node is recorded in PHINodesToUpdate, get it. 5003 for (unsigned pn = 0; ; ++pn) { 5004 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!"); 5005 if (PHINodesToUpdate[pn].first == Phi) { 5006 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn]. 5007 second, false)); 5008 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB)); 5009 break; 5010 } 5011 } 5012 } 5013 5014 // Don't process RHS if same block as LHS. 5015 if (BB == SwitchCases[i].FalseBB) 5016 SwitchCases[i].FalseBB = 0; 5017 5018 // If we haven't handled the RHS, do so now. Otherwise, we're done. 5019 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB; 5020 SwitchCases[i].FalseBB = 0; 5021 } 5022 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0); 5023 } 5024} 5025 5026 5027//===----------------------------------------------------------------------===// 5028/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each 5029/// target node in the graph. 5030void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) { 5031 if (ViewSchedDAGs) DAG.viewGraph(); 5032 5033 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault(); 5034 5035 if (!Ctor) { 5036 Ctor = ISHeuristic; 5037 RegisterScheduler::setDefault(Ctor); 5038 } 5039 5040 ScheduleDAG *SL = Ctor(this, &DAG, BB); 5041 BB = SL->Run(); 5042 5043 if (ViewSUnitDAGs) SL->viewGraph(); 5044 5045 delete SL; 5046} 5047 5048 5049HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() { 5050 return new HazardRecognizer(); 5051} 5052 5053//===----------------------------------------------------------------------===// 5054// Helper functions used by the generated instruction selector. 5055//===----------------------------------------------------------------------===// 5056// Calls to these methods are generated by tblgen. 5057 5058/// CheckAndMask - The isel is trying to match something like (and X, 255). If 5059/// the dag combiner simplified the 255, we still want to match. RHS is the 5060/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 5061/// specified in the .td file (e.g. 255). 5062bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS, 5063 int64_t DesiredMaskS) const { 5064 const APInt &ActualMask = RHS->getAPIntValue(); 5065 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 5066 5067 // If the actual mask exactly matches, success! 5068 if (ActualMask == DesiredMask) 5069 return true; 5070 5071 // If the actual AND mask is allowing unallowed bits, this doesn't match. 5072 if (ActualMask.intersects(~DesiredMask)) 5073 return false; 5074 5075 // Otherwise, the DAG Combiner may have proven that the value coming in is 5076 // either already zero or is not demanded. Check for known zero input bits. 5077 APInt NeededMask = DesiredMask & ~ActualMask; 5078 if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) 5079 return true; 5080 5081 // TODO: check to see if missing bits are just not demanded. 5082 5083 // Otherwise, this pattern doesn't match. 5084 return false; 5085} 5086 5087/// CheckOrMask - The isel is trying to match something like (or X, 255). If 5088/// the dag combiner simplified the 255, we still want to match. RHS is the 5089/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 5090/// specified in the .td file (e.g. 255). 5091bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS, 5092 int64_t DesiredMaskS) const { 5093 const APInt &ActualMask = RHS->getAPIntValue(); 5094 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 5095 5096 // If the actual mask exactly matches, success! 5097 if (ActualMask == DesiredMask) 5098 return true; 5099 5100 // If the actual AND mask is allowing unallowed bits, this doesn't match. 5101 if (ActualMask.intersects(~DesiredMask)) 5102 return false; 5103 5104 // Otherwise, the DAG Combiner may have proven that the value coming in is 5105 // either already zero or is not demanded. Check for known zero input bits. 5106 APInt NeededMask = DesiredMask & ~ActualMask; 5107 5108 APInt KnownZero, KnownOne; 5109 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne); 5110 5111 // If all the missing bits in the or are already known to be set, match! 5112 if ((NeededMask & KnownOne) == NeededMask) 5113 return true; 5114 5115 // TODO: check to see if missing bits are just not demanded. 5116 5117 // Otherwise, this pattern doesn't match. 5118 return false; 5119} 5120 5121 5122/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 5123/// by tblgen. Others should not call it. 5124void SelectionDAGISel:: 5125SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) { 5126 std::vector<SDOperand> InOps; 5127 std::swap(InOps, Ops); 5128 5129 Ops.push_back(InOps[0]); // input chain. 5130 Ops.push_back(InOps[1]); // input asm string. 5131 5132 unsigned i = 2, e = InOps.size(); 5133 if (InOps[e-1].getValueType() == MVT::Flag) 5134 --e; // Don't process a flag operand if it is here. 5135 5136 while (i != e) { 5137 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue(); 5138 if ((Flags & 7) != 4 /*MEM*/) { 5139 // Just skip over this operand, copying the operands verbatim. 5140 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1); 5141 i += (Flags >> 3) + 1; 5142 } else { 5143 assert((Flags >> 3) == 1 && "Memory operand with multiple values?"); 5144 // Otherwise, this is a memory operand. Ask the target to select it. 5145 std::vector<SDOperand> SelOps; 5146 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) { 5147 cerr << "Could not match memory address. Inline asm failure!\n"; 5148 exit(1); 5149 } 5150 5151 // Add this to the output node. 5152 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy(); 5153 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3), 5154 IntPtrTy)); 5155 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 5156 i += 2; 5157 } 5158 } 5159 5160 // Add the flag input back if present. 5161 if (e != InOps.size()) 5162 Ops.push_back(InOps.back()); 5163} 5164 5165char SelectionDAGISel::ID = 0; 5166