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