SelectionDAGISel.cpp revision 20a4921791eafc0cce00fb01dcacfcfc15a0d0fc
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/CodeGen/SelectionDAGISel.h" 16#include "llvm/CodeGen/ScheduleDAG.h" 17#include "llvm/CallingConv.h" 18#include "llvm/Constants.h" 19#include "llvm/DerivedTypes.h" 20#include "llvm/Function.h" 21#include "llvm/GlobalVariable.h" 22#include "llvm/InlineAsm.h" 23#include "llvm/Instructions.h" 24#include "llvm/Intrinsics.h" 25#include "llvm/CodeGen/IntrinsicLowering.h" 26#include "llvm/CodeGen/MachineDebugInfo.h" 27#include "llvm/CodeGen/MachineFunction.h" 28#include "llvm/CodeGen/MachineFrameInfo.h" 29#include "llvm/CodeGen/MachineInstrBuilder.h" 30#include "llvm/CodeGen/SelectionDAG.h" 31#include "llvm/CodeGen/SSARegMap.h" 32#include "llvm/Target/MRegisterInfo.h" 33#include "llvm/Target/TargetData.h" 34#include "llvm/Target/TargetFrameInfo.h" 35#include "llvm/Target/TargetInstrInfo.h" 36#include "llvm/Target/TargetLowering.h" 37#include "llvm/Target/TargetMachine.h" 38#include "llvm/Transforms/Utils/BasicBlockUtils.h" 39#include "llvm/Support/CommandLine.h" 40#include "llvm/Support/MathExtras.h" 41#include "llvm/Support/Debug.h" 42#include <map> 43#include <set> 44#include <iostream> 45#include <algorithm> 46using namespace llvm; 47 48#ifndef NDEBUG 49static cl::opt<bool> 50ViewISelDAGs("view-isel-dags", cl::Hidden, 51 cl::desc("Pop up a window to show isel dags as they are selected")); 52static cl::opt<bool> 53ViewSchedDAGs("view-sched-dags", cl::Hidden, 54 cl::desc("Pop up a window to show sched dags as they are processed")); 55#else 56static const bool ViewISelDAGs = 0; 57static const bool ViewSchedDAGs = 0; 58#endif 59 60// Scheduling heuristics 61enum SchedHeuristics { 62 defaultScheduling, // Let the target specify its preference. 63 noScheduling, // No scheduling, emit breadth first sequence. 64 simpleScheduling, // Two pass, min. critical path, max. utilization. 65 simpleNoItinScheduling, // Same as above exact using generic latency. 66 listSchedulingBURR, // Bottom up reg reduction list scheduling. 67 listSchedulingTD // Top-down list scheduler. 68}; 69 70namespace { 71 cl::opt<SchedHeuristics> 72 ISHeuristic( 73 "sched", 74 cl::desc("Choose scheduling style"), 75 cl::init(defaultScheduling), 76 cl::values( 77 clEnumValN(defaultScheduling, "default", 78 "Target preferred scheduling style"), 79 clEnumValN(noScheduling, "none", 80 "No scheduling: breadth first sequencing"), 81 clEnumValN(simpleScheduling, "simple", 82 "Simple two pass scheduling: minimize critical path " 83 "and maximize processor utilization"), 84 clEnumValN(simpleNoItinScheduling, "simple-noitin", 85 "Simple two pass scheduling: Same as simple " 86 "except using generic latency"), 87 clEnumValN(listSchedulingBURR, "list-burr", 88 "Bottom up register reduction list scheduling"), 89 clEnumValN(listSchedulingTD, "list-td", 90 "Top-down list scheduler"), 91 clEnumValEnd)); 92} // namespace 93 94namespace { 95 /// RegsForValue - This struct represents the physical registers that a 96 /// particular value is assigned and the type information about the value. 97 /// This is needed because values can be promoted into larger registers and 98 /// expanded into multiple smaller registers than the value. 99 struct RegsForValue { 100 /// Regs - This list hold the register (for legal and promoted values) 101 /// or register set (for expanded values) that the value should be assigned 102 /// to. 103 std::vector<unsigned> Regs; 104 105 /// RegVT - The value type of each register. 106 /// 107 MVT::ValueType RegVT; 108 109 /// ValueVT - The value type of the LLVM value, which may be promoted from 110 /// RegVT or made from merging the two expanded parts. 111 MVT::ValueType ValueVT; 112 113 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {} 114 115 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt) 116 : RegVT(regvt), ValueVT(valuevt) { 117 Regs.push_back(Reg); 118 } 119 RegsForValue(const std::vector<unsigned> ®s, 120 MVT::ValueType regvt, MVT::ValueType valuevt) 121 : Regs(regs), RegVT(regvt), ValueVT(valuevt) { 122 } 123 124 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 125 /// this value and returns the result as a ValueVT value. This uses 126 /// Chain/Flag as the input and updates them for the output Chain/Flag. 127 SDOperand getCopyFromRegs(SelectionDAG &DAG, 128 SDOperand &Chain, SDOperand &Flag) const; 129 130 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 131 /// specified value into the registers specified by this object. This uses 132 /// Chain/Flag as the input and updates them for the output Chain/Flag. 133 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG, 134 SDOperand &Chain, SDOperand &Flag) const; 135 136 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 137 /// operand list. This adds the code marker and includes the number of 138 /// values added into it. 139 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG, 140 std::vector<SDOperand> &Ops) const; 141 }; 142} 143 144namespace llvm { 145 //===--------------------------------------------------------------------===// 146 /// FunctionLoweringInfo - This contains information that is global to a 147 /// function that is used when lowering a region of the function. 148 class FunctionLoweringInfo { 149 public: 150 TargetLowering &TLI; 151 Function &Fn; 152 MachineFunction &MF; 153 SSARegMap *RegMap; 154 155 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF); 156 157 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry. 158 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap; 159 160 /// ValueMap - Since we emit code for the function a basic block at a time, 161 /// we must remember which virtual registers hold the values for 162 /// cross-basic-block values. 163 std::map<const Value*, unsigned> ValueMap; 164 165 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in 166 /// the entry block. This allows the allocas to be efficiently referenced 167 /// anywhere in the function. 168 std::map<const AllocaInst*, int> StaticAllocaMap; 169 170 unsigned MakeReg(MVT::ValueType VT) { 171 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT)); 172 } 173 174 unsigned CreateRegForValue(const Value *V) { 175 MVT::ValueType VT = TLI.getValueType(V->getType()); 176 // The common case is that we will only create one register for this 177 // value. If we have that case, create and return the virtual register. 178 unsigned NV = TLI.getNumElements(VT); 179 if (NV == 1) { 180 // If we are promoting this value, pick the next largest supported type. 181 return MakeReg(TLI.getTypeToTransformTo(VT)); 182 } 183 184 // If this value is represented with multiple target registers, make sure 185 // to create enough consecutive registers of the right (smaller) type. 186 unsigned NT = VT-1; // Find the type to use. 187 while (TLI.getNumElements((MVT::ValueType)NT) != 1) 188 --NT; 189 190 unsigned R = MakeReg((MVT::ValueType)NT); 191 for (unsigned i = 1; i != NV; ++i) 192 MakeReg((MVT::ValueType)NT); 193 return R; 194 } 195 196 unsigned InitializeRegForValue(const Value *V) { 197 unsigned &R = ValueMap[V]; 198 assert(R == 0 && "Already initialized this value register!"); 199 return R = CreateRegForValue(V); 200 } 201 }; 202} 203 204/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by 205/// PHI nodes or outside of the basic block that defines it. 206static bool isUsedOutsideOfDefiningBlock(Instruction *I) { 207 if (isa<PHINode>(I)) return true; 208 BasicBlock *BB = I->getParent(); 209 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI) 210 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI)) 211 return true; 212 return false; 213} 214 215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the 216/// entry block, return true. 217static bool isOnlyUsedInEntryBlock(Argument *A) { 218 BasicBlock *Entry = A->getParent()->begin(); 219 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI) 220 if (cast<Instruction>(*UI)->getParent() != Entry) 221 return false; // Use not in entry block. 222 return true; 223} 224 225FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli, 226 Function &fn, MachineFunction &mf) 227 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) { 228 229 // Create a vreg for each argument register that is not dead and is used 230 // outside of the entry block for the function. 231 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end(); 232 AI != E; ++AI) 233 if (!isOnlyUsedInEntryBlock(AI)) 234 InitializeRegForValue(AI); 235 236 // Initialize the mapping of values to registers. This is only set up for 237 // instruction values that are used outside of the block that defines 238 // them. 239 Function::iterator BB = Fn.begin(), EB = Fn.end(); 240 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 241 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 242 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) { 243 const Type *Ty = AI->getAllocatedType(); 244 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty); 245 unsigned Align = 246 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty), 247 AI->getAlignment()); 248 249 // If the alignment of the value is smaller than the size of the value, 250 // and if the size of the value is particularly small (<= 8 bytes), 251 // round up to the size of the value for potentially better performance. 252 // 253 // FIXME: This could be made better with a preferred alignment hook in 254 // TargetData. It serves primarily to 8-byte align doubles for X86. 255 if (Align < TySize && TySize <= 8) Align = TySize; 256 TySize *= CUI->getValue(); // Get total allocated size. 257 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects. 258 StaticAllocaMap[AI] = 259 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align); 260 } 261 262 for (; BB != EB; ++BB) 263 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 264 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I)) 265 if (!isa<AllocaInst>(I) || 266 !StaticAllocaMap.count(cast<AllocaInst>(I))) 267 InitializeRegForValue(I); 268 269 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This 270 // also creates the initial PHI MachineInstrs, though none of the input 271 // operands are populated. 272 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) { 273 MachineBasicBlock *MBB = new MachineBasicBlock(BB); 274 MBBMap[BB] = MBB; 275 MF.getBasicBlockList().push_back(MBB); 276 277 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as 278 // appropriate. 279 PHINode *PN; 280 for (BasicBlock::iterator I = BB->begin(); 281 (PN = dyn_cast<PHINode>(I)); ++I) 282 if (!PN->use_empty()) { 283 unsigned NumElements = 284 TLI.getNumElements(TLI.getValueType(PN->getType())); 285 unsigned PHIReg = ValueMap[PN]; 286 assert(PHIReg &&"PHI node does not have an assigned virtual register!"); 287 for (unsigned i = 0; i != NumElements; ++i) 288 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i); 289 } 290 } 291} 292 293 294 295//===----------------------------------------------------------------------===// 296/// SelectionDAGLowering - This is the common target-independent lowering 297/// implementation that is parameterized by a TargetLowering object. 298/// Also, targets can overload any lowering method. 299/// 300namespace llvm { 301class SelectionDAGLowering { 302 MachineBasicBlock *CurMBB; 303 304 std::map<const Value*, SDOperand> NodeMap; 305 306 /// PendingLoads - Loads are not emitted to the program immediately. We bunch 307 /// them up and then emit token factor nodes when possible. This allows us to 308 /// get simple disambiguation between loads without worrying about alias 309 /// analysis. 310 std::vector<SDOperand> PendingLoads; 311 312public: 313 // TLI - This is information that describes the available target features we 314 // need for lowering. This indicates when operations are unavailable, 315 // implemented with a libcall, etc. 316 TargetLowering &TLI; 317 SelectionDAG &DAG; 318 const TargetData &TD; 319 320 /// FuncInfo - Information about the function as a whole. 321 /// 322 FunctionLoweringInfo &FuncInfo; 323 324 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli, 325 FunctionLoweringInfo &funcinfo) 326 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), 327 FuncInfo(funcinfo) { 328 } 329 330 /// getRoot - Return the current virtual root of the Selection DAG. 331 /// 332 SDOperand getRoot() { 333 if (PendingLoads.empty()) 334 return DAG.getRoot(); 335 336 if (PendingLoads.size() == 1) { 337 SDOperand Root = PendingLoads[0]; 338 DAG.setRoot(Root); 339 PendingLoads.clear(); 340 return Root; 341 } 342 343 // Otherwise, we have to make a token factor node. 344 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads); 345 PendingLoads.clear(); 346 DAG.setRoot(Root); 347 return Root; 348 } 349 350 void visit(Instruction &I) { visit(I.getOpcode(), I); } 351 352 void visit(unsigned Opcode, User &I) { 353 switch (Opcode) { 354 default: assert(0 && "Unknown instruction type encountered!"); 355 abort(); 356 // Build the switch statement using the Instruction.def file. 357#define HANDLE_INST(NUM, OPCODE, CLASS) \ 358 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I); 359#include "llvm/Instruction.def" 360 } 361 } 362 363 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; } 364 365 366 SDOperand getIntPtrConstant(uint64_t Val) { 367 return DAG.getConstant(Val, TLI.getPointerTy()); 368 } 369 370 SDOperand getValue(const Value *V) { 371 SDOperand &N = NodeMap[V]; 372 if (N.Val) return N; 373 374 const Type *VTy = V->getType(); 375 MVT::ValueType VT = TLI.getValueType(VTy); 376 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) 377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 378 visit(CE->getOpcode(), *CE); 379 assert(N.Val && "visit didn't populate the ValueMap!"); 380 return N; 381 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) { 382 return N = DAG.getGlobalAddress(GV, VT); 383 } else if (isa<ConstantPointerNull>(C)) { 384 return N = DAG.getConstant(0, TLI.getPointerTy()); 385 } else if (isa<UndefValue>(C)) { 386 return N = DAG.getNode(ISD::UNDEF, VT); 387 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 388 return N = DAG.getConstantFP(CFP->getValue(), VT); 389 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) { 390 unsigned NumElements = PTy->getNumElements(); 391 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 392 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements); 393 394 // Now that we know the number and type of the elements, push a 395 // Constant or ConstantFP node onto the ops list for each element of 396 // the packed constant. 397 std::vector<SDOperand> Ops; 398 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) { 399 if (MVT::isFloatingPoint(PVT)) { 400 for (unsigned i = 0; i != NumElements; ++i) { 401 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i)); 402 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT)); 403 } 404 } else { 405 for (unsigned i = 0; i != NumElements; ++i) { 406 const ConstantIntegral *El = 407 cast<ConstantIntegral>(CP->getOperand(i)); 408 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT)); 409 } 410 } 411 } else { 412 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!"); 413 SDOperand Op; 414 if (MVT::isFloatingPoint(PVT)) 415 Op = DAG.getConstantFP(0, PVT); 416 else 417 Op = DAG.getConstant(0, PVT); 418 Ops.assign(NumElements, Op); 419 } 420 421 // Handle the case where we have a 1-element vector, in which 422 // case we want to immediately turn it into a scalar constant. 423 if (Ops.size() == 1) { 424 return N = Ops[0]; 425 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) { 426 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops); 427 } else { 428 // If the packed type isn't legal, then create a ConstantVec node with 429 // generic Vector type instead. 430 SDOperand Num = DAG.getConstant(NumElements, MVT::i32); 431 SDOperand Typ = DAG.getValueType(PVT); 432 Ops.insert(Ops.begin(), Typ); 433 Ops.insert(Ops.begin(), Num); 434 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops); 435 } 436 } else { 437 // Canonicalize all constant ints to be unsigned. 438 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT); 439 } 440 441 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 442 std::map<const AllocaInst*, int>::iterator SI = 443 FuncInfo.StaticAllocaMap.find(AI); 444 if (SI != FuncInfo.StaticAllocaMap.end()) 445 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 446 } 447 448 std::map<const Value*, unsigned>::const_iterator VMI = 449 FuncInfo.ValueMap.find(V); 450 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!"); 451 452 unsigned InReg = VMI->second; 453 454 // If this type is not legal, make it so now. 455 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT); 456 457 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT); 458 if (DestVT < VT) { 459 // Source must be expanded. This input value is actually coming from the 460 // register pair VMI->second and VMI->second+1. 461 N = DAG.getNode(ISD::BUILD_PAIR, VT, N, 462 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT)); 463 } else { 464 if (DestVT > VT) { // Promotion case 465 if (MVT::isFloatingPoint(VT)) 466 N = DAG.getNode(ISD::FP_ROUND, VT, N); 467 else 468 N = DAG.getNode(ISD::TRUNCATE, VT, N); 469 } 470 } 471 472 return N; 473 } 474 475 const SDOperand &setValue(const Value *V, SDOperand NewN) { 476 SDOperand &N = NodeMap[V]; 477 assert(N.Val == 0 && "Already set a value for this node!"); 478 return N = NewN; 479 } 480 481 RegsForValue GetRegistersForValue(const std::string &ConstrCode, 482 MVT::ValueType VT, 483 bool OutReg, bool InReg, 484 std::set<unsigned> &OutputRegs, 485 std::set<unsigned> &InputRegs); 486 487 // Terminator instructions. 488 void visitRet(ReturnInst &I); 489 void visitBr(BranchInst &I); 490 void visitUnreachable(UnreachableInst &I) { /* noop */ } 491 492 // These all get lowered before this pass. 493 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); } 494 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); } 495 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); } 496 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); } 497 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); } 498 499 // 500 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp); 501 void visitShift(User &I, unsigned Opcode); 502 void visitAdd(User &I) { 503 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD); 504 } 505 void visitSub(User &I); 506 void visitMul(User &I) { 507 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL); 508 } 509 void visitDiv(User &I) { 510 const Type *Ty = I.getType(); 511 visitBinary(I, 512 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 513 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV); 514 } 515 void visitRem(User &I) { 516 const Type *Ty = I.getType(); 517 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0); 518 } 519 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); } 520 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); } 521 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); } 522 void visitShl(User &I) { visitShift(I, ISD::SHL); } 523 void visitShr(User &I) { 524 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA); 525 } 526 527 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc); 528 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); } 529 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); } 530 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); } 531 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); } 532 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); } 533 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); } 534 535 void visitGetElementPtr(User &I); 536 void visitCast(User &I); 537 void visitSelect(User &I); 538 // 539 540 void visitMalloc(MallocInst &I); 541 void visitFree(FreeInst &I); 542 void visitAlloca(AllocaInst &I); 543 void visitLoad(LoadInst &I); 544 void visitStore(StoreInst &I); 545 void visitPHI(PHINode &I) { } // PHI nodes are handled specially. 546 void visitCall(CallInst &I); 547 void visitInlineAsm(CallInst &I); 548 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic); 549 550 void visitVAStart(CallInst &I); 551 void visitVAArg(VAArgInst &I); 552 void visitVAEnd(CallInst &I); 553 void visitVACopy(CallInst &I); 554 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress); 555 556 void visitMemIntrinsic(CallInst &I, unsigned Op); 557 558 void visitUserOp1(Instruction &I) { 559 assert(0 && "UserOp1 should not exist at instruction selection time!"); 560 abort(); 561 } 562 void visitUserOp2(Instruction &I) { 563 assert(0 && "UserOp2 should not exist at instruction selection time!"); 564 abort(); 565 } 566}; 567} // end namespace llvm 568 569void SelectionDAGLowering::visitRet(ReturnInst &I) { 570 if (I.getNumOperands() == 0) { 571 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot())); 572 return; 573 } 574 std::vector<SDOperand> NewValues; 575 NewValues.push_back(getRoot()); 576 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) { 577 SDOperand RetOp = getValue(I.getOperand(i)); 578 579 // If this is an integer return value, we need to promote it ourselves to 580 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather 581 // than sign/zero. 582 if (MVT::isInteger(RetOp.getValueType()) && 583 RetOp.getValueType() < MVT::i64) { 584 MVT::ValueType TmpVT; 585 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote) 586 TmpVT = TLI.getTypeToTransformTo(MVT::i32); 587 else 588 TmpVT = MVT::i32; 589 590 if (I.getOperand(i)->getType()->isSigned()) 591 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp); 592 else 593 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp); 594 } 595 NewValues.push_back(RetOp); 596 } 597 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues)); 598} 599 600void SelectionDAGLowering::visitBr(BranchInst &I) { 601 // Update machine-CFG edges. 602 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 603 604 // Figure out which block is immediately after the current one. 605 MachineBasicBlock *NextBlock = 0; 606 MachineFunction::iterator BBI = CurMBB; 607 if (++BBI != CurMBB->getParent()->end()) 608 NextBlock = BBI; 609 610 if (I.isUnconditional()) { 611 // If this is not a fall-through branch, emit the branch. 612 if (Succ0MBB != NextBlock) 613 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(), 614 DAG.getBasicBlock(Succ0MBB))); 615 } else { 616 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 617 618 SDOperand Cond = getValue(I.getCondition()); 619 if (Succ1MBB == NextBlock) { 620 // If the condition is false, fall through. This means we should branch 621 // if the condition is true to Succ #0. 622 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), 623 Cond, DAG.getBasicBlock(Succ0MBB))); 624 } else if (Succ0MBB == NextBlock) { 625 // If the condition is true, fall through. This means we should branch if 626 // the condition is false to Succ #1. Invert the condition first. 627 SDOperand True = DAG.getConstant(1, Cond.getValueType()); 628 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True); 629 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), 630 Cond, DAG.getBasicBlock(Succ1MBB))); 631 } else { 632 std::vector<SDOperand> Ops; 633 Ops.push_back(getRoot()); 634 // If the false case is the current basic block, then this is a self 635 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it 636 // adds an extra instruction in the loop. Instead, invert the 637 // condition and emit "Loop: ... br!cond Loop; br Out. 638 if (CurMBB == Succ1MBB) { 639 std::swap(Succ0MBB, Succ1MBB); 640 SDOperand True = DAG.getConstant(1, Cond.getValueType()); 641 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True); 642 } 643 Ops.push_back(Cond); 644 Ops.push_back(DAG.getBasicBlock(Succ0MBB)); 645 Ops.push_back(DAG.getBasicBlock(Succ1MBB)); 646 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops)); 647 } 648 } 649} 650 651void SelectionDAGLowering::visitSub(User &I) { 652 // -0.0 - X --> fneg 653 if (I.getType()->isFloatingPoint()) { 654 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 655 if (CFP->isExactlyValue(-0.0)) { 656 SDOperand Op2 = getValue(I.getOperand(1)); 657 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2)); 658 return; 659 } 660 } 661 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB); 662} 663 664void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp, 665 unsigned VecOp) { 666 const Type *Ty = I.getType(); 667 SDOperand Op1 = getValue(I.getOperand(0)); 668 SDOperand Op2 = getValue(I.getOperand(1)); 669 670 if (Ty->isIntegral()) { 671 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2)); 672 } else if (Ty->isFloatingPoint()) { 673 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2)); 674 } else { 675 const PackedType *PTy = cast<PackedType>(Ty); 676 unsigned NumElements = PTy->getNumElements(); 677 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 678 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements); 679 680 // Immediately scalarize packed types containing only one element, so that 681 // the Legalize pass does not have to deal with them. Similarly, if the 682 // abstract vector is going to turn into one that the target natively 683 // supports, generate that type now so that Legalize doesn't have to deal 684 // with that either. These steps ensure that Legalize only has to handle 685 // vector types in its Expand case. 686 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp; 687 if (NumElements == 1) { 688 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2)); 689 } else if (TVT != MVT::Other && 690 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) { 691 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2)); 692 } else { 693 SDOperand Num = DAG.getConstant(NumElements, MVT::i32); 694 SDOperand Typ = DAG.getValueType(PVT); 695 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2)); 696 } 697 } 698} 699 700void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) { 701 SDOperand Op1 = getValue(I.getOperand(0)); 702 SDOperand Op2 = getValue(I.getOperand(1)); 703 704 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2); 705 706 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2)); 707} 708 709void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode, 710 ISD::CondCode UnsignedOpcode) { 711 SDOperand Op1 = getValue(I.getOperand(0)); 712 SDOperand Op2 = getValue(I.getOperand(1)); 713 ISD::CondCode Opcode = SignedOpcode; 714 if (I.getOperand(0)->getType()->isUnsigned()) 715 Opcode = UnsignedOpcode; 716 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode)); 717} 718 719void SelectionDAGLowering::visitSelect(User &I) { 720 SDOperand Cond = getValue(I.getOperand(0)); 721 SDOperand TrueVal = getValue(I.getOperand(1)); 722 SDOperand FalseVal = getValue(I.getOperand(2)); 723 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond, 724 TrueVal, FalseVal)); 725} 726 727void SelectionDAGLowering::visitCast(User &I) { 728 SDOperand N = getValue(I.getOperand(0)); 729 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType()); 730 MVT::ValueType DestTy = TLI.getValueType(I.getType()); 731 732 if (N.getValueType() == DestTy) { 733 setValue(&I, N); // noop cast. 734 } else if (DestTy == MVT::i1) { 735 // Cast to bool is a comparison against zero, not truncation to zero. 736 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) : 737 DAG.getConstantFP(0.0, N.getValueType()); 738 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE)); 739 } else if (isInteger(SrcTy)) { 740 if (isInteger(DestTy)) { // Int -> Int cast 741 if (DestTy < SrcTy) // Truncating cast? 742 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N)); 743 else if (I.getOperand(0)->getType()->isSigned()) 744 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N)); 745 else 746 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N)); 747 } else { // Int -> FP cast 748 if (I.getOperand(0)->getType()->isSigned()) 749 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N)); 750 else 751 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N)); 752 } 753 } else { 754 assert(isFloatingPoint(SrcTy) && "Unknown value type!"); 755 if (isFloatingPoint(DestTy)) { // FP -> FP cast 756 if (DestTy < SrcTy) // Rounding cast? 757 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N)); 758 else 759 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N)); 760 } else { // FP -> Int cast. 761 if (I.getType()->isSigned()) 762 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N)); 763 else 764 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N)); 765 } 766 } 767} 768 769void SelectionDAGLowering::visitGetElementPtr(User &I) { 770 SDOperand N = getValue(I.getOperand(0)); 771 const Type *Ty = I.getOperand(0)->getType(); 772 const Type *UIntPtrTy = TD.getIntPtrType(); 773 774 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end(); 775 OI != E; ++OI) { 776 Value *Idx = *OI; 777 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 778 unsigned Field = cast<ConstantUInt>(Idx)->getValue(); 779 if (Field) { 780 // N = N + Offset 781 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field]; 782 N = DAG.getNode(ISD::ADD, N.getValueType(), N, 783 getIntPtrConstant(Offset)); 784 } 785 Ty = StTy->getElementType(Field); 786 } else { 787 Ty = cast<SequentialType>(Ty)->getElementType(); 788 789 // If this is a constant subscript, handle it quickly. 790 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 791 if (CI->getRawValue() == 0) continue; 792 793 uint64_t Offs; 794 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI)) 795 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue(); 796 else 797 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue(); 798 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs)); 799 continue; 800 } 801 802 // N = N + Idx * ElementSize; 803 uint64_t ElementSize = TD.getTypeSize(Ty); 804 SDOperand IdxN = getValue(Idx); 805 806 // If the index is smaller or larger than intptr_t, truncate or extend 807 // it. 808 if (IdxN.getValueType() < N.getValueType()) { 809 if (Idx->getType()->isSigned()) 810 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN); 811 else 812 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN); 813 } else if (IdxN.getValueType() > N.getValueType()) 814 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN); 815 816 // If this is a multiply by a power of two, turn it into a shl 817 // immediately. This is a very common case. 818 if (isPowerOf2_64(ElementSize)) { 819 unsigned Amt = Log2_64(ElementSize); 820 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN, 821 DAG.getConstant(Amt, TLI.getShiftAmountTy())); 822 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN); 823 continue; 824 } 825 826 SDOperand Scale = getIntPtrConstant(ElementSize); 827 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale); 828 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN); 829 } 830 } 831 setValue(&I, N); 832} 833 834void SelectionDAGLowering::visitAlloca(AllocaInst &I) { 835 // If this is a fixed sized alloca in the entry block of the function, 836 // allocate it statically on the stack. 837 if (FuncInfo.StaticAllocaMap.count(&I)) 838 return; // getValue will auto-populate this. 839 840 const Type *Ty = I.getAllocatedType(); 841 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty); 842 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty), 843 I.getAlignment()); 844 845 SDOperand AllocSize = getValue(I.getArraySize()); 846 MVT::ValueType IntPtr = TLI.getPointerTy(); 847 if (IntPtr < AllocSize.getValueType()) 848 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize); 849 else if (IntPtr > AllocSize.getValueType()) 850 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize); 851 852 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize, 853 getIntPtrConstant(TySize)); 854 855 // Handle alignment. If the requested alignment is less than or equal to the 856 // stack alignment, ignore it and round the size of the allocation up to the 857 // stack alignment size. If the size is greater than the stack alignment, we 858 // note this in the DYNAMIC_STACKALLOC node. 859 unsigned StackAlign = 860 TLI.getTargetMachine().getFrameInfo()->getStackAlignment(); 861 if (Align <= StackAlign) { 862 Align = 0; 863 // Add SA-1 to the size. 864 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize, 865 getIntPtrConstant(StackAlign-1)); 866 // Mask out the low bits for alignment purposes. 867 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize, 868 getIntPtrConstant(~(uint64_t)(StackAlign-1))); 869 } 870 871 std::vector<MVT::ValueType> VTs; 872 VTs.push_back(AllocSize.getValueType()); 873 VTs.push_back(MVT::Other); 874 std::vector<SDOperand> Ops; 875 Ops.push_back(getRoot()); 876 Ops.push_back(AllocSize); 877 Ops.push_back(getIntPtrConstant(Align)); 878 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops); 879 DAG.setRoot(setValue(&I, DSA).getValue(1)); 880 881 // Inform the Frame Information that we have just allocated a variable-sized 882 // object. 883 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject(); 884} 885 886void SelectionDAGLowering::visitLoad(LoadInst &I) { 887 SDOperand Ptr = getValue(I.getOperand(0)); 888 889 SDOperand Root; 890 if (I.isVolatile()) 891 Root = getRoot(); 892 else { 893 // Do not serialize non-volatile loads against each other. 894 Root = DAG.getRoot(); 895 } 896 897 const Type *Ty = I.getType(); 898 SDOperand L; 899 900 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) { 901 unsigned NumElements = PTy->getNumElements(); 902 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType()); 903 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements); 904 905 // Immediately scalarize packed types containing only one element, so that 906 // the Legalize pass does not have to deal with them. 907 if (NumElements == 1) { 908 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0))); 909 } else if (TVT != MVT::Other && 910 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(ISD::LOAD, TVT)) { 911 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0))); 912 } else { 913 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr, 914 DAG.getSrcValue(I.getOperand(0))); 915 } 916 } else { 917 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, 918 DAG.getSrcValue(I.getOperand(0))); 919 } 920 setValue(&I, L); 921 922 if (I.isVolatile()) 923 DAG.setRoot(L.getValue(1)); 924 else 925 PendingLoads.push_back(L.getValue(1)); 926} 927 928 929void SelectionDAGLowering::visitStore(StoreInst &I) { 930 Value *SrcV = I.getOperand(0); 931 SDOperand Src = getValue(SrcV); 932 SDOperand Ptr = getValue(I.getOperand(1)); 933 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr, 934 DAG.getSrcValue(I.getOperand(1)))); 935} 936 937/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 938/// we want to emit this as a call to a named external function, return the name 939/// otherwise lower it and return null. 940const char * 941SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) { 942 switch (Intrinsic) { 943 case Intrinsic::vastart: visitVAStart(I); return 0; 944 case Intrinsic::vaend: visitVAEnd(I); return 0; 945 case Intrinsic::vacopy: visitVACopy(I); return 0; 946 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0; 947 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0; 948 case Intrinsic::setjmp: 949 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp(); 950 break; 951 case Intrinsic::longjmp: 952 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp(); 953 break; 954 case Intrinsic::memcpy_i32: 955 case Intrinsic::memcpy_i64: 956 visitMemIntrinsic(I, ISD::MEMCPY); 957 return 0; 958 case Intrinsic::memset_i32: 959 case Intrinsic::memset_i64: 960 visitMemIntrinsic(I, ISD::MEMSET); 961 return 0; 962 case Intrinsic::memmove_i32: 963 case Intrinsic::memmove_i64: 964 visitMemIntrinsic(I, ISD::MEMMOVE); 965 return 0; 966 967 case Intrinsic::dbg_stoppoint: { 968 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions()) 969 return "llvm_debugger_stop"; 970 971 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo(); 972 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) { 973 std::vector<SDOperand> Ops; 974 975 // Input Chain 976 Ops.push_back(getRoot()); 977 978 // line number 979 Ops.push_back(getValue(I.getOperand(2))); 980 981 // column 982 Ops.push_back(getValue(I.getOperand(3))); 983 984 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4)); 985 assert(DD && "Not a debug information descriptor"); 986 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD); 987 assert(CompileUnit && "Not a compile unit"); 988 Ops.push_back(DAG.getString(CompileUnit->getFileName())); 989 Ops.push_back(DAG.getString(CompileUnit->getDirectory())); 990 991 if (Ops.size() == 5) // Found filename/workingdir. 992 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops)); 993 } 994 995 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()))); 996 return 0; 997 } 998 case Intrinsic::dbg_region_start: 999 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions()) 1000 return "llvm_dbg_region_start"; 1001 if (I.getType() != Type::VoidTy) 1002 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()))); 1003 return 0; 1004 case Intrinsic::dbg_region_end: 1005 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions()) 1006 return "llvm_dbg_region_end"; 1007 if (I.getType() != Type::VoidTy) 1008 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()))); 1009 return 0; 1010 case Intrinsic::dbg_func_start: 1011 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions()) 1012 return "llvm_dbg_subprogram"; 1013 if (I.getType() != Type::VoidTy) 1014 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()))); 1015 return 0; 1016 1017 case Intrinsic::isunordered_f32: 1018 case Intrinsic::isunordered_f64: 1019 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)), 1020 getValue(I.getOperand(2)), ISD::SETUO)); 1021 return 0; 1022 1023 case Intrinsic::sqrt_f32: 1024 case Intrinsic::sqrt_f64: 1025 setValue(&I, DAG.getNode(ISD::FSQRT, 1026 getValue(I.getOperand(1)).getValueType(), 1027 getValue(I.getOperand(1)))); 1028 return 0; 1029 case Intrinsic::pcmarker: { 1030 SDOperand Tmp = getValue(I.getOperand(1)); 1031 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp)); 1032 return 0; 1033 } 1034 case Intrinsic::readcyclecounter: { 1035 std::vector<MVT::ValueType> VTs; 1036 VTs.push_back(MVT::i64); 1037 VTs.push_back(MVT::Other); 1038 std::vector<SDOperand> Ops; 1039 Ops.push_back(getRoot()); 1040 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops); 1041 setValue(&I, Tmp); 1042 DAG.setRoot(Tmp.getValue(1)); 1043 return 0; 1044 } 1045 case Intrinsic::bswap_i16: 1046 case Intrinsic::bswap_i32: 1047 case Intrinsic::bswap_i64: 1048 setValue(&I, DAG.getNode(ISD::BSWAP, 1049 getValue(I.getOperand(1)).getValueType(), 1050 getValue(I.getOperand(1)))); 1051 return 0; 1052 case Intrinsic::cttz_i8: 1053 case Intrinsic::cttz_i16: 1054 case Intrinsic::cttz_i32: 1055 case Intrinsic::cttz_i64: 1056 setValue(&I, DAG.getNode(ISD::CTTZ, 1057 getValue(I.getOperand(1)).getValueType(), 1058 getValue(I.getOperand(1)))); 1059 return 0; 1060 case Intrinsic::ctlz_i8: 1061 case Intrinsic::ctlz_i16: 1062 case Intrinsic::ctlz_i32: 1063 case Intrinsic::ctlz_i64: 1064 setValue(&I, DAG.getNode(ISD::CTLZ, 1065 getValue(I.getOperand(1)).getValueType(), 1066 getValue(I.getOperand(1)))); 1067 return 0; 1068 case Intrinsic::ctpop_i8: 1069 case Intrinsic::ctpop_i16: 1070 case Intrinsic::ctpop_i32: 1071 case Intrinsic::ctpop_i64: 1072 setValue(&I, DAG.getNode(ISD::CTPOP, 1073 getValue(I.getOperand(1)).getValueType(), 1074 getValue(I.getOperand(1)))); 1075 return 0; 1076 case Intrinsic::stacksave: { 1077 std::vector<MVT::ValueType> VTs; 1078 VTs.push_back(TLI.getPointerTy()); 1079 VTs.push_back(MVT::Other); 1080 std::vector<SDOperand> Ops; 1081 Ops.push_back(getRoot()); 1082 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops); 1083 setValue(&I, Tmp); 1084 DAG.setRoot(Tmp.getValue(1)); 1085 return 0; 1086 } 1087 case Intrinsic::stackrestore: { 1088 SDOperand Tmp = getValue(I.getOperand(1)); 1089 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp)); 1090 return 0; 1091 } 1092 case Intrinsic::prefetch: 1093 // FIXME: Currently discarding prefetches. 1094 return 0; 1095 default: 1096 std::cerr << I; 1097 assert(0 && "This intrinsic is not implemented yet!"); 1098 return 0; 1099 } 1100} 1101 1102 1103void SelectionDAGLowering::visitCall(CallInst &I) { 1104 const char *RenameFn = 0; 1105 if (Function *F = I.getCalledFunction()) { 1106 if (F->isExternal()) 1107 if (unsigned IID = F->getIntrinsicID()) { 1108 RenameFn = visitIntrinsicCall(I, IID); 1109 if (!RenameFn) 1110 return; 1111 } else { // Not an LLVM intrinsic. 1112 const std::string &Name = F->getName(); 1113 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) { 1114 if (I.getNumOperands() == 3 && // Basic sanity checks. 1115 I.getOperand(1)->getType()->isFloatingPoint() && 1116 I.getType() == I.getOperand(1)->getType() && 1117 I.getType() == I.getOperand(2)->getType()) { 1118 SDOperand LHS = getValue(I.getOperand(1)); 1119 SDOperand RHS = getValue(I.getOperand(2)); 1120 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(), 1121 LHS, RHS)); 1122 return; 1123 } 1124 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) { 1125 if (I.getNumOperands() == 2 && // Basic sanity checks. 1126 I.getOperand(1)->getType()->isFloatingPoint() && 1127 I.getType() == I.getOperand(1)->getType()) { 1128 SDOperand Tmp = getValue(I.getOperand(1)); 1129 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp)); 1130 return; 1131 } 1132 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) { 1133 if (I.getNumOperands() == 2 && // Basic sanity checks. 1134 I.getOperand(1)->getType()->isFloatingPoint() && 1135 I.getType() == I.getOperand(1)->getType()) { 1136 SDOperand Tmp = getValue(I.getOperand(1)); 1137 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp)); 1138 return; 1139 } 1140 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) { 1141 if (I.getNumOperands() == 2 && // Basic sanity checks. 1142 I.getOperand(1)->getType()->isFloatingPoint() && 1143 I.getType() == I.getOperand(1)->getType()) { 1144 SDOperand Tmp = getValue(I.getOperand(1)); 1145 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp)); 1146 return; 1147 } 1148 } 1149 } 1150 } else if (isa<InlineAsm>(I.getOperand(0))) { 1151 visitInlineAsm(I); 1152 return; 1153 } 1154 1155 SDOperand Callee; 1156 if (!RenameFn) 1157 Callee = getValue(I.getOperand(0)); 1158 else 1159 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 1160 std::vector<std::pair<SDOperand, const Type*> > Args; 1161 Args.reserve(I.getNumOperands()); 1162 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 1163 Value *Arg = I.getOperand(i); 1164 SDOperand ArgNode = getValue(Arg); 1165 Args.push_back(std::make_pair(ArgNode, Arg->getType())); 1166 } 1167 1168 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType()); 1169 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 1170 1171 std::pair<SDOperand,SDOperand> Result = 1172 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(), 1173 I.isTailCall(), Callee, Args, DAG); 1174 if (I.getType() != Type::VoidTy) 1175 setValue(&I, Result.first); 1176 DAG.setRoot(Result.second); 1177} 1178 1179SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 1180 SDOperand &Chain, SDOperand &Flag)const{ 1181 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag); 1182 Chain = Val.getValue(1); 1183 Flag = Val.getValue(2); 1184 1185 // If the result was expanded, copy from the top part. 1186 if (Regs.size() > 1) { 1187 assert(Regs.size() == 2 && 1188 "Cannot expand to more than 2 elts yet!"); 1189 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag); 1190 Chain = Val.getValue(1); 1191 Flag = Val.getValue(2); 1192 if (DAG.getTargetLoweringInfo().isLittleEndian()) 1193 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi); 1194 else 1195 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val); 1196 } 1197 1198 // Otherwise, if the return value was promoted, truncate it to the 1199 // appropriate type. 1200 if (RegVT == ValueVT) 1201 return Val; 1202 1203 if (MVT::isInteger(RegVT)) 1204 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val); 1205 else 1206 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val); 1207} 1208 1209/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 1210/// specified value into the registers specified by this object. This uses 1211/// Chain/Flag as the input and updates them for the output Chain/Flag. 1212void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG, 1213 SDOperand &Chain, SDOperand &Flag) const { 1214 if (Regs.size() == 1) { 1215 // If there is a single register and the types differ, this must be 1216 // a promotion. 1217 if (RegVT != ValueVT) { 1218 if (MVT::isInteger(RegVT)) 1219 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val); 1220 else 1221 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val); 1222 } 1223 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag); 1224 Flag = Chain.getValue(1); 1225 } else { 1226 std::vector<unsigned> R(Regs); 1227 if (!DAG.getTargetLoweringInfo().isLittleEndian()) 1228 std::reverse(R.begin(), R.end()); 1229 1230 for (unsigned i = 0, e = R.size(); i != e; ++i) { 1231 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val, 1232 DAG.getConstant(i, MVT::i32)); 1233 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag); 1234 Flag = Chain.getValue(1); 1235 } 1236 } 1237} 1238 1239/// AddInlineAsmOperands - Add this value to the specified inlineasm node 1240/// operand list. This adds the code marker and includes the number of 1241/// values added into it. 1242void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG, 1243 std::vector<SDOperand> &Ops) const { 1244 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32)); 1245 for (unsigned i = 0, e = Regs.size(); i != e; ++i) 1246 Ops.push_back(DAG.getRegister(Regs[i], RegVT)); 1247} 1248 1249/// isAllocatableRegister - If the specified register is safe to allocate, 1250/// i.e. it isn't a stack pointer or some other special register, return the 1251/// register class for the register. Otherwise, return null. 1252static const TargetRegisterClass * 1253isAllocatableRegister(unsigned Reg, MachineFunction &MF, 1254 const TargetLowering &TLI, const MRegisterInfo *MRI) { 1255 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(), 1256 E = MRI->regclass_end(); RCI != E; ++RCI) { 1257 const TargetRegisterClass *RC = *RCI; 1258 // If none of the the value types for this register class are valid, we 1259 // can't use it. For example, 64-bit reg classes on 32-bit targets. 1260 bool isLegal = false; 1261 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 1262 I != E; ++I) { 1263 if (TLI.isTypeLegal(*I)) { 1264 isLegal = true; 1265 break; 1266 } 1267 } 1268 1269 if (!isLegal) continue; 1270 1271 // NOTE: This isn't ideal. In particular, this might allocate the 1272 // frame pointer in functions that need it (due to them not being taken 1273 // out of allocation, because a variable sized allocation hasn't been seen 1274 // yet). This is a slight code pessimization, but should still work. 1275 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF), 1276 E = RC->allocation_order_end(MF); I != E; ++I) 1277 if (*I == Reg) 1278 return RC; 1279 } 1280 return 0; 1281} 1282 1283RegsForValue SelectionDAGLowering:: 1284GetRegistersForValue(const std::string &ConstrCode, 1285 MVT::ValueType VT, bool isOutReg, bool isInReg, 1286 std::set<unsigned> &OutputRegs, 1287 std::set<unsigned> &InputRegs) { 1288 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 1289 TLI.getRegForInlineAsmConstraint(ConstrCode, VT); 1290 std::vector<unsigned> Regs; 1291 1292 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1; 1293 MVT::ValueType RegVT; 1294 MVT::ValueType ValueVT = VT; 1295 1296 if (PhysReg.first) { 1297 if (VT == MVT::Other) 1298 ValueVT = *PhysReg.second->vt_begin(); 1299 RegVT = VT; 1300 1301 // This is a explicit reference to a physical register. 1302 Regs.push_back(PhysReg.first); 1303 1304 // If this is an expanded reference, add the rest of the regs to Regs. 1305 if (NumRegs != 1) { 1306 RegVT = *PhysReg.second->vt_begin(); 1307 TargetRegisterClass::iterator I = PhysReg.second->begin(); 1308 TargetRegisterClass::iterator E = PhysReg.second->end(); 1309 for (; *I != PhysReg.first; ++I) 1310 assert(I != E && "Didn't find reg!"); 1311 1312 // Already added the first reg. 1313 --NumRegs; ++I; 1314 for (; NumRegs; --NumRegs, ++I) { 1315 assert(I != E && "Ran out of registers to allocate!"); 1316 Regs.push_back(*I); 1317 } 1318 } 1319 return RegsForValue(Regs, RegVT, ValueVT); 1320 } 1321 1322 // This is a reference to a register class. Allocate NumRegs consecutive, 1323 // available, registers from the class. 1324 std::vector<unsigned> RegClassRegs = 1325 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT); 1326 1327 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo(); 1328 MachineFunction &MF = *CurMBB->getParent(); 1329 unsigned NumAllocated = 0; 1330 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) { 1331 unsigned Reg = RegClassRegs[i]; 1332 // See if this register is available. 1333 if ((isOutReg && OutputRegs.count(Reg)) || // Already used. 1334 (isInReg && InputRegs.count(Reg))) { // Already used. 1335 // Make sure we find consecutive registers. 1336 NumAllocated = 0; 1337 continue; 1338 } 1339 1340 // Check to see if this register is allocatable (i.e. don't give out the 1341 // stack pointer). 1342 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI); 1343 if (!RC) { 1344 // Make sure we find consecutive registers. 1345 NumAllocated = 0; 1346 continue; 1347 } 1348 1349 // Okay, this register is good, we can use it. 1350 ++NumAllocated; 1351 1352 // If we allocated enough consecutive 1353 if (NumAllocated == NumRegs) { 1354 unsigned RegStart = (i-NumAllocated)+1; 1355 unsigned RegEnd = i+1; 1356 // Mark all of the allocated registers used. 1357 for (unsigned i = RegStart; i != RegEnd; ++i) { 1358 unsigned Reg = RegClassRegs[i]; 1359 Regs.push_back(Reg); 1360 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used. 1361 if (isInReg) InputRegs.insert(Reg); // Mark reg used. 1362 } 1363 1364 return RegsForValue(Regs, *RC->vt_begin(), VT); 1365 } 1366 } 1367 1368 // Otherwise, we couldn't allocate enough registers for this. 1369 return RegsForValue(); 1370} 1371 1372 1373/// visitInlineAsm - Handle a call to an InlineAsm object. 1374/// 1375void SelectionDAGLowering::visitInlineAsm(CallInst &I) { 1376 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0)); 1377 1378 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), 1379 MVT::Other); 1380 1381 // Note, we treat inline asms both with and without side-effects as the same. 1382 // If an inline asm doesn't have side effects and doesn't access memory, we 1383 // could not choose to not chain it. 1384 bool hasSideEffects = IA->hasSideEffects(); 1385 1386 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints(); 1387 std::vector<MVT::ValueType> ConstraintVTs; 1388 1389 /// AsmNodeOperands - A list of pairs. The first element is a register, the 1390 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set 1391 /// if it is a def of that register. 1392 std::vector<SDOperand> AsmNodeOperands; 1393 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain 1394 AsmNodeOperands.push_back(AsmStr); 1395 1396 SDOperand Chain = getRoot(); 1397 SDOperand Flag; 1398 1399 // We fully assign registers here at isel time. This is not optimal, but 1400 // should work. For register classes that correspond to LLVM classes, we 1401 // could let the LLVM RA do its thing, but we currently don't. Do a prepass 1402 // over the constraints, collecting fixed registers that we know we can't use. 1403 std::set<unsigned> OutputRegs, InputRegs; 1404 unsigned OpNum = 1; 1405 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) { 1406 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!"); 1407 std::string &ConstraintCode = Constraints[i].Codes[0]; 1408 1409 MVT::ValueType OpVT; 1410 1411 // Compute the value type for each operand and add it to ConstraintVTs. 1412 switch (Constraints[i].Type) { 1413 case InlineAsm::isOutput: 1414 if (!Constraints[i].isIndirectOutput) { 1415 assert(I.getType() != Type::VoidTy && "Bad inline asm!"); 1416 OpVT = TLI.getValueType(I.getType()); 1417 } else { 1418 const Type *OpTy = I.getOperand(OpNum)->getType(); 1419 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType()); 1420 OpNum++; // Consumes a call operand. 1421 } 1422 break; 1423 case InlineAsm::isInput: 1424 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType()); 1425 OpNum++; // Consumes a call operand. 1426 break; 1427 case InlineAsm::isClobber: 1428 OpVT = MVT::Other; 1429 break; 1430 } 1431 1432 ConstraintVTs.push_back(OpVT); 1433 1434 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0) 1435 continue; // Not assigned a fixed reg. 1436 1437 // Build a list of regs that this operand uses. This always has a single 1438 // element for promoted/expanded operands. 1439 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT, 1440 false, false, 1441 OutputRegs, InputRegs); 1442 1443 switch (Constraints[i].Type) { 1444 case InlineAsm::isOutput: 1445 // We can't assign any other output to this register. 1446 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end()); 1447 // If this is an early-clobber output, it cannot be assigned to the same 1448 // value as the input reg. 1449 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput) 1450 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end()); 1451 break; 1452 case InlineAsm::isInput: 1453 // We can't assign any other input to this register. 1454 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end()); 1455 break; 1456 case InlineAsm::isClobber: 1457 // Clobbered regs cannot be used as inputs or outputs. 1458 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end()); 1459 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end()); 1460 break; 1461 } 1462 } 1463 1464 // Loop over all of the inputs, copying the operand values into the 1465 // appropriate registers and processing the output regs. 1466 RegsForValue RetValRegs; 1467 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 1468 OpNum = 1; 1469 1470 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) { 1471 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!"); 1472 std::string &ConstraintCode = Constraints[i].Codes[0]; 1473 1474 switch (Constraints[i].Type) { 1475 case InlineAsm::isOutput: { 1476 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass; 1477 if (ConstraintCode.size() == 1) // not a physreg name. 1478 CTy = TLI.getConstraintType(ConstraintCode[0]); 1479 1480 if (CTy == TargetLowering::C_Memory) { 1481 // Memory output. 1482 SDOperand InOperandVal = getValue(I.getOperand(OpNum)); 1483 1484 // Check that the operand (the address to store to) isn't a float. 1485 if (!MVT::isInteger(InOperandVal.getValueType())) 1486 assert(0 && "MATCH FAIL!"); 1487 1488 if (!Constraints[i].isIndirectOutput) 1489 assert(0 && "MATCH FAIL!"); 1490 1491 OpNum++; // Consumes a call operand. 1492 1493 // Extend/truncate to the right pointer type if needed. 1494 MVT::ValueType PtrType = TLI.getPointerTy(); 1495 if (InOperandVal.getValueType() < PtrType) 1496 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal); 1497 else if (InOperandVal.getValueType() > PtrType) 1498 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal); 1499 1500 // Add information to the INLINEASM node to know about this output. 1501 unsigned ResOpType = 4/*MEM*/ | (1 << 3); 1502 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32)); 1503 AsmNodeOperands.push_back(InOperandVal); 1504 break; 1505 } 1506 1507 // Otherwise, this is a register output. 1508 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!"); 1509 1510 // If this is an early-clobber output, or if there is an input 1511 // constraint that matches this, we need to reserve the input register 1512 // so no other inputs allocate to it. 1513 bool UsesInputRegister = false; 1514 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput) 1515 UsesInputRegister = true; 1516 1517 // Copy the output from the appropriate register. Find a register that 1518 // we can use. 1519 RegsForValue Regs = 1520 GetRegistersForValue(ConstraintCode, ConstraintVTs[i], 1521 true, UsesInputRegister, 1522 OutputRegs, InputRegs); 1523 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!"); 1524 1525 if (!Constraints[i].isIndirectOutput) { 1526 assert(RetValRegs.Regs.empty() && 1527 "Cannot have multiple output constraints yet!"); 1528 assert(I.getType() != Type::VoidTy && "Bad inline asm!"); 1529 RetValRegs = Regs; 1530 } else { 1531 IndirectStoresToEmit.push_back(std::make_pair(Regs, 1532 I.getOperand(OpNum))); 1533 OpNum++; // Consumes a call operand. 1534 } 1535 1536 // Add information to the INLINEASM node to know that this register is 1537 // set. 1538 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands); 1539 break; 1540 } 1541 case InlineAsm::isInput: { 1542 SDOperand InOperandVal = getValue(I.getOperand(OpNum)); 1543 OpNum++; // Consumes a call operand. 1544 1545 if (isdigit(ConstraintCode[0])) { // Matching constraint? 1546 // If this is required to match an output register we have already set, 1547 // just use its register. 1548 unsigned OperandNo = atoi(ConstraintCode.c_str()); 1549 1550 // Scan until we find the definition we already emitted of this operand. 1551 // When we find it, create a RegsForValue operand. 1552 unsigned CurOp = 2; // The first operand. 1553 for (; OperandNo; --OperandNo) { 1554 // Advance to the next operand. 1555 unsigned NumOps = 1556 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue(); 1557 assert((NumOps & 7) == 2 /*REGDEF*/ && 1558 "Skipped past definitions?"); 1559 CurOp += (NumOps>>3)+1; 1560 } 1561 1562 unsigned NumOps = 1563 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue(); 1564 assert((NumOps & 7) == 2 /*REGDEF*/ && 1565 "Skipped past definitions?"); 1566 1567 // Add NumOps>>3 registers to MatchedRegs. 1568 RegsForValue MatchedRegs; 1569 MatchedRegs.ValueVT = InOperandVal.getValueType(); 1570 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType(); 1571 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) { 1572 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg(); 1573 MatchedRegs.Regs.push_back(Reg); 1574 } 1575 1576 // Use the produced MatchedRegs object to 1577 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag); 1578 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands); 1579 break; 1580 } 1581 1582 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass; 1583 if (ConstraintCode.size() == 1) // not a physreg name. 1584 CTy = TLI.getConstraintType(ConstraintCode[0]); 1585 1586 if (CTy == TargetLowering::C_Other) { 1587 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0])) 1588 assert(0 && "MATCH FAIL!"); 1589 1590 // Add information to the INLINEASM node to know about this input. 1591 unsigned ResOpType = 3 /*IMM*/ | (1 << 3); 1592 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32)); 1593 AsmNodeOperands.push_back(InOperandVal); 1594 break; 1595 } else if (CTy == TargetLowering::C_Memory) { 1596 // Memory input. 1597 1598 // Check that the operand isn't a float. 1599 if (!MVT::isInteger(InOperandVal.getValueType())) 1600 assert(0 && "MATCH FAIL!"); 1601 1602 // Extend/truncate to the right pointer type if needed. 1603 MVT::ValueType PtrType = TLI.getPointerTy(); 1604 if (InOperandVal.getValueType() < PtrType) 1605 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal); 1606 else if (InOperandVal.getValueType() > PtrType) 1607 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal); 1608 1609 // Add information to the INLINEASM node to know about this input. 1610 unsigned ResOpType = 4/*MEM*/ | (1 << 3); 1611 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32)); 1612 AsmNodeOperands.push_back(InOperandVal); 1613 break; 1614 } 1615 1616 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!"); 1617 1618 // Copy the input into the appropriate registers. 1619 RegsForValue InRegs = 1620 GetRegistersForValue(ConstraintCode, ConstraintVTs[i], 1621 false, true, OutputRegs, InputRegs); 1622 // FIXME: should be match fail. 1623 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!"); 1624 1625 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag); 1626 1627 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands); 1628 break; 1629 } 1630 case InlineAsm::isClobber: { 1631 RegsForValue ClobberedRegs = 1632 GetRegistersForValue(ConstraintCode, MVT::Other, false, false, 1633 OutputRegs, InputRegs); 1634 // Add the clobbered value to the operand list, so that the register 1635 // allocator is aware that the physreg got clobbered. 1636 if (!ClobberedRegs.Regs.empty()) 1637 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands); 1638 break; 1639 } 1640 } 1641 } 1642 1643 // Finish up input operands. 1644 AsmNodeOperands[0] = Chain; 1645 if (Flag.Val) AsmNodeOperands.push_back(Flag); 1646 1647 std::vector<MVT::ValueType> VTs; 1648 VTs.push_back(MVT::Other); 1649 VTs.push_back(MVT::Flag); 1650 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands); 1651 Flag = Chain.getValue(1); 1652 1653 // If this asm returns a register value, copy the result from that register 1654 // and set it as the value of the call. 1655 if (!RetValRegs.Regs.empty()) 1656 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag)); 1657 1658 std::vector<std::pair<SDOperand, Value*> > StoresToEmit; 1659 1660 // Process indirect outputs, first output all of the flagged copies out of 1661 // physregs. 1662 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 1663 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 1664 Value *Ptr = IndirectStoresToEmit[i].second; 1665 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag); 1666 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 1667 } 1668 1669 // Emit the non-flagged stores from the physregs. 1670 std::vector<SDOperand> OutChains; 1671 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) 1672 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain, 1673 StoresToEmit[i].first, 1674 getValue(StoresToEmit[i].second), 1675 DAG.getSrcValue(StoresToEmit[i].second))); 1676 if (!OutChains.empty()) 1677 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains); 1678 DAG.setRoot(Chain); 1679} 1680 1681 1682void SelectionDAGLowering::visitMalloc(MallocInst &I) { 1683 SDOperand Src = getValue(I.getOperand(0)); 1684 1685 MVT::ValueType IntPtr = TLI.getPointerTy(); 1686 1687 if (IntPtr < Src.getValueType()) 1688 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src); 1689 else if (IntPtr > Src.getValueType()) 1690 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src); 1691 1692 // Scale the source by the type size. 1693 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType()); 1694 Src = DAG.getNode(ISD::MUL, Src.getValueType(), 1695 Src, getIntPtrConstant(ElementSize)); 1696 1697 std::vector<std::pair<SDOperand, const Type*> > Args; 1698 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType())); 1699 1700 std::pair<SDOperand,SDOperand> Result = 1701 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true, 1702 DAG.getExternalSymbol("malloc", IntPtr), 1703 Args, DAG); 1704 setValue(&I, Result.first); // Pointers always fit in registers 1705 DAG.setRoot(Result.second); 1706} 1707 1708void SelectionDAGLowering::visitFree(FreeInst &I) { 1709 std::vector<std::pair<SDOperand, const Type*> > Args; 1710 Args.push_back(std::make_pair(getValue(I.getOperand(0)), 1711 TLI.getTargetData().getIntPtrType())); 1712 MVT::ValueType IntPtr = TLI.getPointerTy(); 1713 std::pair<SDOperand,SDOperand> Result = 1714 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true, 1715 DAG.getExternalSymbol("free", IntPtr), Args, DAG); 1716 DAG.setRoot(Result.second); 1717} 1718 1719// InsertAtEndOfBasicBlock - This method should be implemented by targets that 1720// mark instructions with the 'usesCustomDAGSchedInserter' flag. These 1721// instructions are special in various ways, which require special support to 1722// insert. The specified MachineInstr is created but not inserted into any 1723// basic blocks, and the scheduler passes ownership of it to this method. 1724MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI, 1725 MachineBasicBlock *MBB) { 1726 std::cerr << "If a target marks an instruction with " 1727 "'usesCustomDAGSchedInserter', it must implement " 1728 "TargetLowering::InsertAtEndOfBasicBlock!\n"; 1729 abort(); 1730 return 0; 1731} 1732 1733void SelectionDAGLowering::visitVAStart(CallInst &I) { 1734 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 1735 getValue(I.getOperand(1)), 1736 DAG.getSrcValue(I.getOperand(1)))); 1737} 1738 1739void SelectionDAGLowering::visitVAArg(VAArgInst &I) { 1740 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(), 1741 getValue(I.getOperand(0)), 1742 DAG.getSrcValue(I.getOperand(0))); 1743 setValue(&I, V); 1744 DAG.setRoot(V.getValue(1)); 1745} 1746 1747void SelectionDAGLowering::visitVAEnd(CallInst &I) { 1748 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(), 1749 getValue(I.getOperand(1)), 1750 DAG.getSrcValue(I.getOperand(1)))); 1751} 1752 1753void SelectionDAGLowering::visitVACopy(CallInst &I) { 1754 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 1755 getValue(I.getOperand(1)), 1756 getValue(I.getOperand(2)), 1757 DAG.getSrcValue(I.getOperand(1)), 1758 DAG.getSrcValue(I.getOperand(2)))); 1759} 1760 1761// It is always conservatively correct for llvm.returnaddress and 1762// llvm.frameaddress to return 0. 1763std::pair<SDOperand, SDOperand> 1764TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, 1765 unsigned Depth, SelectionDAG &DAG) { 1766 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain); 1767} 1768 1769SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) { 1770 assert(0 && "LowerOperation not implemented for this target!"); 1771 abort(); 1772 return SDOperand(); 1773} 1774 1775SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op, 1776 SelectionDAG &DAG) { 1777 assert(0 && "CustomPromoteOperation not implemented for this target!"); 1778 abort(); 1779 return SDOperand(); 1780} 1781 1782void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) { 1783 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue(); 1784 std::pair<SDOperand,SDOperand> Result = 1785 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG); 1786 setValue(&I, Result.first); 1787 DAG.setRoot(Result.second); 1788} 1789 1790/// getMemsetValue - Vectorized representation of the memset value 1791/// operand. 1792static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT, 1793 SelectionDAG &DAG) { 1794 MVT::ValueType CurVT = VT; 1795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 1796 uint64_t Val = C->getValue() & 255; 1797 unsigned Shift = 8; 1798 while (CurVT != MVT::i8) { 1799 Val = (Val << Shift) | Val; 1800 Shift <<= 1; 1801 CurVT = (MVT::ValueType)((unsigned)CurVT - 1); 1802 } 1803 return DAG.getConstant(Val, VT); 1804 } else { 1805 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value); 1806 unsigned Shift = 8; 1807 while (CurVT != MVT::i8) { 1808 Value = 1809 DAG.getNode(ISD::OR, VT, 1810 DAG.getNode(ISD::SHL, VT, Value, 1811 DAG.getConstant(Shift, MVT::i8)), Value); 1812 Shift <<= 1; 1813 CurVT = (MVT::ValueType)((unsigned)CurVT - 1); 1814 } 1815 1816 return Value; 1817 } 1818} 1819 1820/// getMemsetStringVal - Similar to getMemsetValue. Except this is only 1821/// used when a memcpy is turned into a memset when the source is a constant 1822/// string ptr. 1823static SDOperand getMemsetStringVal(MVT::ValueType VT, 1824 SelectionDAG &DAG, TargetLowering &TLI, 1825 std::string &Str, unsigned Offset) { 1826 MVT::ValueType CurVT = VT; 1827 uint64_t Val = 0; 1828 unsigned MSB = getSizeInBits(VT) / 8; 1829 if (TLI.isLittleEndian()) 1830 Offset = Offset + MSB - 1; 1831 for (unsigned i = 0; i != MSB; ++i) { 1832 Val = (Val << 8) | Str[Offset]; 1833 Offset += TLI.isLittleEndian() ? -1 : 1; 1834 } 1835 return DAG.getConstant(Val, VT); 1836} 1837 1838/// getMemBasePlusOffset - Returns base and offset node for the 1839static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset, 1840 SelectionDAG &DAG, TargetLowering &TLI) { 1841 MVT::ValueType VT = Base.getValueType(); 1842 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT)); 1843} 1844 1845/// MeetsMaxMemopRequirement - Determines if the number of memory ops required 1846/// to replace the memset / memcpy is below the threshold. It also returns the 1847/// types of the sequence of memory ops to perform memset / memcpy. 1848static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps, 1849 unsigned Limit, uint64_t Size, 1850 unsigned Align, TargetLowering &TLI) { 1851 MVT::ValueType VT; 1852 1853 if (TLI.allowsUnalignedMemoryAccesses()) { 1854 VT = MVT::i64; 1855 } else { 1856 switch (Align & 7) { 1857 case 0: 1858 VT = MVT::i64; 1859 break; 1860 case 4: 1861 VT = MVT::i32; 1862 break; 1863 case 2: 1864 VT = MVT::i16; 1865 break; 1866 default: 1867 VT = MVT::i8; 1868 break; 1869 } 1870 } 1871 1872 MVT::ValueType LVT = MVT::i64; 1873 while (!TLI.isTypeLegal(LVT)) 1874 LVT = (MVT::ValueType)((unsigned)LVT - 1); 1875 assert(MVT::isInteger(LVT)); 1876 1877 if (VT > LVT) 1878 VT = LVT; 1879 1880 unsigned NumMemOps = 0; 1881 while (Size != 0) { 1882 unsigned VTSize = getSizeInBits(VT) / 8; 1883 while (VTSize > Size) { 1884 VT = (MVT::ValueType)((unsigned)VT - 1); 1885 VTSize >>= 1; 1886 } 1887 assert(MVT::isInteger(VT)); 1888 1889 if (++NumMemOps > Limit) 1890 return false; 1891 MemOps.push_back(VT); 1892 Size -= VTSize; 1893 } 1894 1895 return true; 1896} 1897 1898void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) { 1899 SDOperand Op1 = getValue(I.getOperand(1)); 1900 SDOperand Op2 = getValue(I.getOperand(2)); 1901 SDOperand Op3 = getValue(I.getOperand(3)); 1902 SDOperand Op4 = getValue(I.getOperand(4)); 1903 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue(); 1904 if (Align == 0) Align = 1; 1905 1906 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) { 1907 std::vector<MVT::ValueType> MemOps; 1908 1909 // Expand memset / memcpy to a series of load / store ops 1910 // if the size operand falls below a certain threshold. 1911 std::vector<SDOperand> OutChains; 1912 switch (Op) { 1913 default: break; // Do nothing for now. 1914 case ISD::MEMSET: { 1915 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(), 1916 Size->getValue(), Align, TLI)) { 1917 unsigned NumMemOps = MemOps.size(); 1918 unsigned Offset = 0; 1919 for (unsigned i = 0; i < NumMemOps; i++) { 1920 MVT::ValueType VT = MemOps[i]; 1921 unsigned VTSize = getSizeInBits(VT) / 8; 1922 SDOperand Value = getMemsetValue(Op2, VT, DAG); 1923 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(), 1924 Value, 1925 getMemBasePlusOffset(Op1, Offset, DAG, TLI), 1926 DAG.getSrcValue(I.getOperand(1), Offset)); 1927 OutChains.push_back(Store); 1928 Offset += VTSize; 1929 } 1930 } 1931 break; 1932 } 1933 case ISD::MEMCPY: { 1934 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(), 1935 Size->getValue(), Align, TLI)) { 1936 unsigned NumMemOps = MemOps.size(); 1937 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0; 1938 GlobalAddressSDNode *G = NULL; 1939 std::string Str; 1940 bool CopyFromStr = false; 1941 1942 if (Op2.getOpcode() == ISD::GlobalAddress) 1943 G = cast<GlobalAddressSDNode>(Op2); 1944 else if (Op2.getOpcode() == ISD::ADD && 1945 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress && 1946 Op2.getOperand(1).getOpcode() == ISD::Constant) { 1947 G = cast<GlobalAddressSDNode>(Op2.getOperand(0)); 1948 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue(); 1949 } 1950 if (G) { 1951 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal()); 1952 if (GV) { 1953 Str = GV->getStringValue(); 1954 if (!Str.empty()) { 1955 CopyFromStr = true; 1956 SrcOff += SrcDelta; 1957 } 1958 } 1959 } 1960 1961 for (unsigned i = 0; i < NumMemOps; i++) { 1962 MVT::ValueType VT = MemOps[i]; 1963 unsigned VTSize = getSizeInBits(VT) / 8; 1964 SDOperand Value, Chain, Store; 1965 1966 if (CopyFromStr) { 1967 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff); 1968 Chain = getRoot(); 1969 Store = 1970 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value, 1971 getMemBasePlusOffset(Op1, DstOff, DAG, TLI), 1972 DAG.getSrcValue(I.getOperand(1), DstOff)); 1973 } else { 1974 Value = DAG.getLoad(VT, getRoot(), 1975 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI), 1976 DAG.getSrcValue(I.getOperand(2), SrcOff)); 1977 Chain = Value.getValue(1); 1978 Store = 1979 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value, 1980 getMemBasePlusOffset(Op1, DstOff, DAG, TLI), 1981 DAG.getSrcValue(I.getOperand(1), DstOff)); 1982 } 1983 OutChains.push_back(Store); 1984 SrcOff += VTSize; 1985 DstOff += VTSize; 1986 } 1987 } 1988 break; 1989 } 1990 } 1991 1992 if (!OutChains.empty()) { 1993 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains)); 1994 return; 1995 } 1996 } 1997 1998 std::vector<SDOperand> Ops; 1999 Ops.push_back(getRoot()); 2000 Ops.push_back(Op1); 2001 Ops.push_back(Op2); 2002 Ops.push_back(Op3); 2003 Ops.push_back(Op4); 2004 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops)); 2005} 2006 2007//===----------------------------------------------------------------------===// 2008// SelectionDAGISel code 2009//===----------------------------------------------------------------------===// 2010 2011unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) { 2012 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT)); 2013} 2014 2015void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { 2016 // FIXME: we only modify the CFG to split critical edges. This 2017 // updates dom and loop info. 2018} 2019 2020 2021/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset, 2022/// casting to the type of GEPI. 2023static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI, 2024 Value *Ptr, Value *PtrOffset) { 2025 if (V) return V; // Already computed. 2026 2027 BasicBlock::iterator InsertPt; 2028 if (BB == GEPI->getParent()) { 2029 // If insert into the GEP's block, insert right after the GEP. 2030 InsertPt = GEPI; 2031 ++InsertPt; 2032 } else { 2033 // Otherwise, insert at the top of BB, after any PHI nodes 2034 InsertPt = BB->begin(); 2035 while (isa<PHINode>(InsertPt)) ++InsertPt; 2036 } 2037 2038 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into 2039 // BB so that there is only one value live across basic blocks (the cast 2040 // operand). 2041 if (CastInst *CI = dyn_cast<CastInst>(Ptr)) 2042 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType())) 2043 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt); 2044 2045 // Add the offset, cast it to the right type. 2046 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt); 2047 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt); 2048 return V = Ptr; 2049} 2050 2051 2052/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction 2053/// selection, we want to be a bit careful about some things. In particular, if 2054/// we have a GEP instruction that is used in a different block than it is 2055/// defined, the addressing expression of the GEP cannot be folded into loads or 2056/// stores that use it. In this case, decompose the GEP and move constant 2057/// indices into blocks that use it. 2058static void OptimizeGEPExpression(GetElementPtrInst *GEPI, 2059 const TargetData &TD) { 2060 // If this GEP is only used inside the block it is defined in, there is no 2061 // need to rewrite it. 2062 bool isUsedOutsideDefBB = false; 2063 BasicBlock *DefBB = GEPI->getParent(); 2064 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end(); 2065 UI != E; ++UI) { 2066 if (cast<Instruction>(*UI)->getParent() != DefBB) { 2067 isUsedOutsideDefBB = true; 2068 break; 2069 } 2070 } 2071 if (!isUsedOutsideDefBB) return; 2072 2073 // If this GEP has no non-zero constant indices, there is nothing we can do, 2074 // ignore it. 2075 bool hasConstantIndex = false; 2076 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1, 2077 E = GEPI->op_end(); OI != E; ++OI) { 2078 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) 2079 if (CI->getRawValue()) { 2080 hasConstantIndex = true; 2081 break; 2082 } 2083 } 2084 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses. 2085 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return; 2086 2087 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the 2088 // constant offset (which we now know is non-zero) and deal with it later. 2089 uint64_t ConstantOffset = 0; 2090 const Type *UIntPtrTy = TD.getIntPtrType(); 2091 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI); 2092 const Type *Ty = GEPI->getOperand(0)->getType(); 2093 2094 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1, 2095 E = GEPI->op_end(); OI != E; ++OI) { 2096 Value *Idx = *OI; 2097 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 2098 unsigned Field = cast<ConstantUInt>(Idx)->getValue(); 2099 if (Field) 2100 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field]; 2101 Ty = StTy->getElementType(Field); 2102 } else { 2103 Ty = cast<SequentialType>(Ty)->getElementType(); 2104 2105 // Handle constant subscripts. 2106 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 2107 if (CI->getRawValue() == 0) continue; 2108 2109 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI)) 2110 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue(); 2111 else 2112 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue(); 2113 continue; 2114 } 2115 2116 // Ptr = Ptr + Idx * ElementSize; 2117 2118 // Cast Idx to UIntPtrTy if needed. 2119 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI); 2120 2121 uint64_t ElementSize = TD.getTypeSize(Ty); 2122 // Mask off bits that should not be set. 2123 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits()); 2124 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize); 2125 2126 // Multiply by the element size and add to the base. 2127 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI); 2128 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI); 2129 } 2130 } 2131 2132 // Make sure that the offset fits in uintptr_t. 2133 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits()); 2134 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset); 2135 2136 // Okay, we have now emitted all of the variable index parts to the BB that 2137 // the GEP is defined in. Loop over all of the using instructions, inserting 2138 // an "add Ptr, ConstantOffset" into each block that uses it and update the 2139 // instruction to use the newly computed value, making GEPI dead. When the 2140 // user is a load or store instruction address, we emit the add into the user 2141 // block, otherwise we use a canonical version right next to the gep (these 2142 // won't be foldable as addresses, so we might as well share the computation). 2143 2144 std::map<BasicBlock*,Value*> InsertedExprs; 2145 while (!GEPI->use_empty()) { 2146 Instruction *User = cast<Instruction>(GEPI->use_back()); 2147 2148 // If this use is not foldable into the addressing mode, use a version 2149 // emitted in the GEP block. 2150 Value *NewVal; 2151 if (!isa<LoadInst>(User) && 2152 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) { 2153 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI, 2154 Ptr, PtrOffset); 2155 } else { 2156 // Otherwise, insert the code in the User's block so it can be folded into 2157 // any users in that block. 2158 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()], 2159 User->getParent(), GEPI, 2160 Ptr, PtrOffset); 2161 } 2162 User->replaceUsesOfWith(GEPI, NewVal); 2163 } 2164 2165 // Finally, the GEP is dead, remove it. 2166 GEPI->eraseFromParent(); 2167} 2168 2169bool SelectionDAGISel::runOnFunction(Function &Fn) { 2170 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine()); 2171 RegMap = MF.getSSARegMap(); 2172 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n"); 2173 2174 // First, split all critical edges for PHI nodes with incoming values that are 2175 // constants, this way the load of the constant into a vreg will not be placed 2176 // into MBBs that are used some other way. 2177 // 2178 // In this pass we also look for GEP instructions that are used across basic 2179 // blocks and rewrites them to improve basic-block-at-a-time selection. 2180 // 2181 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 2182 PHINode *PN; 2183 BasicBlock::iterator BBI; 2184 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI) 2185 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 2186 if (isa<Constant>(PN->getIncomingValue(i))) 2187 SplitCriticalEdge(PN->getIncomingBlock(i), BB); 2188 2189 for (BasicBlock::iterator E = BB->end(); BBI != E; ) 2190 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++)) 2191 OptimizeGEPExpression(GEPI, TLI.getTargetData()); 2192 } 2193 2194 FunctionLoweringInfo FuncInfo(TLI, Fn, MF); 2195 2196 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) 2197 SelectBasicBlock(I, MF, FuncInfo); 2198 2199 return true; 2200} 2201 2202 2203SDOperand SelectionDAGISel:: 2204CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) { 2205 SDOperand Op = SDL.getValue(V); 2206 assert((Op.getOpcode() != ISD::CopyFromReg || 2207 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 2208 "Copy from a reg to the same reg!"); 2209 2210 // If this type is not legal, we must make sure to not create an invalid 2211 // register use. 2212 MVT::ValueType SrcVT = Op.getValueType(); 2213 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT); 2214 SelectionDAG &DAG = SDL.DAG; 2215 if (SrcVT == DestVT) { 2216 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op); 2217 } else if (SrcVT < DestVT) { 2218 // The src value is promoted to the register. 2219 if (MVT::isFloatingPoint(SrcVT)) 2220 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op); 2221 else 2222 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op); 2223 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op); 2224 } else { 2225 // The src value is expanded into multiple registers. 2226 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT, 2227 Op, DAG.getConstant(0, MVT::i32)); 2228 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT, 2229 Op, DAG.getConstant(1, MVT::i32)); 2230 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo); 2231 return DAG.getCopyToReg(Op, Reg+1, Hi); 2232 } 2233} 2234 2235void SelectionDAGISel:: 2236LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL, 2237 std::vector<SDOperand> &UnorderedChains) { 2238 // If this is the entry block, emit arguments. 2239 Function &F = *BB->getParent(); 2240 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo; 2241 SDOperand OldRoot = SDL.DAG.getRoot(); 2242 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG); 2243 2244 unsigned a = 0; 2245 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); 2246 AI != E; ++AI, ++a) 2247 if (!AI->use_empty()) { 2248 SDL.setValue(AI, Args[a]); 2249 2250 // If this argument is live outside of the entry block, insert a copy from 2251 // whereever we got it to the vreg that other BB's will reference it as. 2252 if (FuncInfo.ValueMap.count(AI)) { 2253 SDOperand Copy = 2254 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]); 2255 UnorderedChains.push_back(Copy); 2256 } 2257 } 2258 2259 // Next, if the function has live ins that need to be copied into vregs, 2260 // emit the copies now, into the top of the block. 2261 MachineFunction &MF = SDL.DAG.getMachineFunction(); 2262 if (MF.livein_begin() != MF.livein_end()) { 2263 SSARegMap *RegMap = MF.getSSARegMap(); 2264 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo(); 2265 for (MachineFunction::livein_iterator LI = MF.livein_begin(), 2266 E = MF.livein_end(); LI != E; ++LI) 2267 if (LI->second) 2268 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second, 2269 LI->first, RegMap->getRegClass(LI->second)); 2270 } 2271 2272 // Finally, if the target has anything special to do, allow it to do so. 2273 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction()); 2274} 2275 2276 2277void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB, 2278 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate, 2279 FunctionLoweringInfo &FuncInfo) { 2280 SelectionDAGLowering SDL(DAG, TLI, FuncInfo); 2281 2282 std::vector<SDOperand> UnorderedChains; 2283 2284 // Lower any arguments needed in this block if this is the entry block. 2285 if (LLVMBB == &LLVMBB->getParent()->front()) 2286 LowerArguments(LLVMBB, SDL, UnorderedChains); 2287 2288 BB = FuncInfo.MBBMap[LLVMBB]; 2289 SDL.setCurrentBasicBlock(BB); 2290 2291 // Lower all of the non-terminator instructions. 2292 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end(); 2293 I != E; ++I) 2294 SDL.visit(*I); 2295 2296 // Ensure that all instructions which are used outside of their defining 2297 // blocks are available as virtual registers. 2298 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I) 2299 if (!I->use_empty() && !isa<PHINode>(I)) { 2300 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I); 2301 if (VMI != FuncInfo.ValueMap.end()) 2302 UnorderedChains.push_back( 2303 CopyValueToVirtualRegister(SDL, I, VMI->second)); 2304 } 2305 2306 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 2307 // ensure constants are generated when needed. Remember the virtual registers 2308 // that need to be added to the Machine PHI nodes as input. We cannot just 2309 // directly add them, because expansion might result in multiple MBB's for one 2310 // BB. As such, the start of the BB might correspond to a different MBB than 2311 // the end. 2312 // 2313 2314 // Emit constants only once even if used by multiple PHI nodes. 2315 std::map<Constant*, unsigned> ConstantsOut; 2316 2317 // Check successor nodes PHI nodes that expect a constant to be available from 2318 // this block. 2319 TerminatorInst *TI = LLVMBB->getTerminator(); 2320 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 2321 BasicBlock *SuccBB = TI->getSuccessor(succ); 2322 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin(); 2323 PHINode *PN; 2324 2325 // At this point we know that there is a 1-1 correspondence between LLVM PHI 2326 // nodes and Machine PHI nodes, but the incoming operands have not been 2327 // emitted yet. 2328 for (BasicBlock::iterator I = SuccBB->begin(); 2329 (PN = dyn_cast<PHINode>(I)); ++I) 2330 if (!PN->use_empty()) { 2331 unsigned Reg; 2332 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 2333 if (Constant *C = dyn_cast<Constant>(PHIOp)) { 2334 unsigned &RegOut = ConstantsOut[C]; 2335 if (RegOut == 0) { 2336 RegOut = FuncInfo.CreateRegForValue(C); 2337 UnorderedChains.push_back( 2338 CopyValueToVirtualRegister(SDL, C, RegOut)); 2339 } 2340 Reg = RegOut; 2341 } else { 2342 Reg = FuncInfo.ValueMap[PHIOp]; 2343 if (Reg == 0) { 2344 assert(isa<AllocaInst>(PHIOp) && 2345 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 2346 "Didn't codegen value into a register!??"); 2347 Reg = FuncInfo.CreateRegForValue(PHIOp); 2348 UnorderedChains.push_back( 2349 CopyValueToVirtualRegister(SDL, PHIOp, Reg)); 2350 } 2351 } 2352 2353 // Remember that this register needs to added to the machine PHI node as 2354 // the input for this MBB. 2355 unsigned NumElements = 2356 TLI.getNumElements(TLI.getValueType(PN->getType())); 2357 for (unsigned i = 0, e = NumElements; i != e; ++i) 2358 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 2359 } 2360 } 2361 ConstantsOut.clear(); 2362 2363 // Turn all of the unordered chains into one factored node. 2364 if (!UnorderedChains.empty()) { 2365 SDOperand Root = SDL.getRoot(); 2366 if (Root.getOpcode() != ISD::EntryToken) { 2367 unsigned i = 0, e = UnorderedChains.size(); 2368 for (; i != e; ++i) { 2369 assert(UnorderedChains[i].Val->getNumOperands() > 1); 2370 if (UnorderedChains[i].Val->getOperand(0) == Root) 2371 break; // Don't add the root if we already indirectly depend on it. 2372 } 2373 2374 if (i == e) 2375 UnorderedChains.push_back(Root); 2376 } 2377 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains)); 2378 } 2379 2380 // Lower the terminator after the copies are emitted. 2381 SDL.visit(*LLVMBB->getTerminator()); 2382 2383 // Make sure the root of the DAG is up-to-date. 2384 DAG.setRoot(SDL.getRoot()); 2385} 2386 2387void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF, 2388 FunctionLoweringInfo &FuncInfo) { 2389 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>()); 2390 CurDAG = &DAG; 2391 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate; 2392 2393 // First step, lower LLVM code to some DAG. This DAG may use operations and 2394 // types that are not supported by the target. 2395 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo); 2396 2397 // Run the DAG combiner in pre-legalize mode. 2398 DAG.Combine(false); 2399 2400 DEBUG(std::cerr << "Lowered selection DAG:\n"); 2401 DEBUG(DAG.dump()); 2402 2403 // Second step, hack on the DAG until it only uses operations and types that 2404 // the target supports. 2405 DAG.Legalize(); 2406 2407 DEBUG(std::cerr << "Legalized selection DAG:\n"); 2408 DEBUG(DAG.dump()); 2409 2410 // Run the DAG combiner in post-legalize mode. 2411 DAG.Combine(true); 2412 2413 if (ViewISelDAGs) DAG.viewGraph(); 2414 2415 // Third, instruction select all of the operations to machine code, adding the 2416 // code to the MachineBasicBlock. 2417 InstructionSelectBasicBlock(DAG); 2418 2419 DEBUG(std::cerr << "Selected machine code:\n"); 2420 DEBUG(BB->dump()); 2421 2422 // Next, now that we know what the last MBB the LLVM BB expanded is, update 2423 // PHI nodes in successors. 2424 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) { 2425 MachineInstr *PHI = PHINodesToUpdate[i].first; 2426 assert(PHI->getOpcode() == TargetInstrInfo::PHI && 2427 "This is not a machine PHI node that we are updating!"); 2428 PHI->addRegOperand(PHINodesToUpdate[i].second); 2429 PHI->addMachineBasicBlockOperand(BB); 2430 } 2431 2432 // Finally, add the CFG edges from the last selected MBB to the successor 2433 // MBBs. 2434 TerminatorInst *TI = LLVMBB->getTerminator(); 2435 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { 2436 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)]; 2437 BB->addSuccessor(Succ0MBB); 2438 } 2439} 2440 2441//===----------------------------------------------------------------------===// 2442/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each 2443/// target node in the graph. 2444void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) { 2445 if (ViewSchedDAGs) DAG.viewGraph(); 2446 ScheduleDAG *SL = NULL; 2447 2448 switch (ISHeuristic) { 2449 default: assert(0 && "Unrecognized scheduling heuristic"); 2450 case defaultScheduling: 2451 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) 2452 SL = createSimpleDAGScheduler(noScheduling, DAG, BB); 2453 else /* TargetLowering::SchedulingForRegPressure */ 2454 SL = createBURRListDAGScheduler(DAG, BB); 2455 break; 2456 case noScheduling: 2457 SL = createBFS_DAGScheduler(DAG, BB); 2458 break; 2459 case simpleScheduling: 2460 SL = createSimpleDAGScheduler(false, DAG, BB); 2461 break; 2462 case simpleNoItinScheduling: 2463 SL = createSimpleDAGScheduler(true, DAG, BB); 2464 break; 2465 case listSchedulingBURR: 2466 SL = createBURRListDAGScheduler(DAG, BB); 2467 break; 2468 case listSchedulingTD: 2469 SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer()); 2470 break; 2471 } 2472 BB = SL->Run(); 2473 delete SL; 2474} 2475 2476HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() { 2477 return new HazardRecognizer(); 2478} 2479 2480/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 2481/// by tblgen. Others should not call it. 2482void SelectionDAGISel:: 2483SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) { 2484 std::vector<SDOperand> InOps; 2485 std::swap(InOps, Ops); 2486 2487 Ops.push_back(InOps[0]); // input chain. 2488 Ops.push_back(InOps[1]); // input asm string. 2489 2490 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol(); 2491 unsigned i = 2, e = InOps.size(); 2492 if (InOps[e-1].getValueType() == MVT::Flag) 2493 --e; // Don't process a flag operand if it is here. 2494 2495 while (i != e) { 2496 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue(); 2497 if ((Flags & 7) != 4 /*MEM*/) { 2498 // Just skip over this operand, copying the operands verbatim. 2499 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1); 2500 i += (Flags >> 3) + 1; 2501 } else { 2502 assert((Flags >> 3) == 1 && "Memory operand with multiple values?"); 2503 // Otherwise, this is a memory operand. Ask the target to select it. 2504 std::vector<SDOperand> SelOps; 2505 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) { 2506 std::cerr << "Could not match memory address. Inline asm failure!\n"; 2507 exit(1); 2508 } 2509 2510 // Add this to the output node. 2511 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32)); 2512 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 2513 i += 2; 2514 } 2515 } 2516 2517 // Add the flag input back if present. 2518 if (e != InOps.size()) 2519 Ops.push_back(InOps.back()); 2520} 2521