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