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