1 //===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===// 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 file describes how to lower LLVM code to machine code. This has two 11 // main components: 12 // 13 // 1. Which ValueTypes are natively supported by the target. 14 // 2. Which operations are supported for supported ValueTypes. 15 // 3. Cost thresholds for alternative implementations of certain operations. 16 // 17 // In addition it has a few other components, like information about FP 18 // immediates. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #ifndef LLVM_TARGET_TARGETLOWERING_H 23 #define LLVM_TARGET_TARGETLOWERING_H 24 25 #include "llvm/CallingConv.h" 26 #include "llvm/InlineAsm.h" 27 #include "llvm/Attributes.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/CodeGen/SelectionDAGNodes.h" 30 #include "llvm/CodeGen/RuntimeLibcalls.h" 31 #include "llvm/Support/DebugLoc.h" 32 #include "llvm/Target/TargetCallingConv.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include <climits> 35 #include <map> 36 #include <vector> 37 38 namespace llvm { 39 class AllocaInst; 40 class APFloat; 41 class CallInst; 42 class CCState; 43 class Function; 44 class FastISel; 45 class FunctionLoweringInfo; 46 class ImmutableCallSite; 47 class MachineBasicBlock; 48 class MachineFunction; 49 class MachineFrameInfo; 50 class MachineInstr; 51 class MachineJumpTableInfo; 52 class MCContext; 53 class MCExpr; 54 class SDNode; 55 class SDValue; 56 class SelectionDAG; 57 template<typename T> class SmallVectorImpl; 58 class TargetData; 59 class TargetMachine; 60 class TargetRegisterClass; 61 class TargetLoweringObjectFile; 62 class Value; 63 64 // FIXME: should this be here? 65 namespace TLSModel { 66 enum Model { 67 GeneralDynamic, 68 LocalDynamic, 69 InitialExec, 70 LocalExec 71 }; 72 } 73 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc); 74 75 76 //===----------------------------------------------------------------------===// 77 /// TargetLowering - This class defines information used to lower LLVM code to 78 /// legal SelectionDAG operators that the target instruction selector can accept 79 /// natively. 80 /// 81 /// This class also defines callbacks that targets must implement to lower 82 /// target-specific constructs to SelectionDAG operators. 83 /// 84 class TargetLowering { 85 TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT 86 void operator=(const TargetLowering&); // DO NOT IMPLEMENT 87 public: 88 /// LegalizeAction - This enum indicates whether operations are valid for a 89 /// target, and if not, what action should be used to make them valid. 90 enum LegalizeAction { 91 Legal, // The target natively supports this operation. 92 Promote, // This operation should be executed in a larger type. 93 Expand, // Try to expand this to other ops, otherwise use a libcall. 94 Custom // Use the LowerOperation hook to implement custom lowering. 95 }; 96 97 /// LegalizeAction - This enum indicates whether a types are legal for a 98 /// target, and if not, what action should be used to make them valid. 99 enum LegalizeTypeAction { 100 TypeLegal, // The target natively supports this type. 101 TypePromoteInteger, // Replace this integer with a larger one. 102 TypeExpandInteger, // Split this integer into two of half the size. 103 TypeSoftenFloat, // Convert this float to a same size integer type. 104 TypeExpandFloat, // Split this float into two of half the size. 105 TypeScalarizeVector, // Replace this one-element vector with its element. 106 TypeSplitVector, // Split this vector into two of half the size. 107 TypeWidenVector // This vector should be widened into a larger vector. 108 }; 109 110 enum BooleanContent { // How the target represents true/false values. 111 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage. 112 ZeroOrOneBooleanContent, // All bits zero except for bit 0. 113 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0. 114 }; 115 116 /// NOTE: The constructor takes ownership of TLOF. 117 explicit TargetLowering(const TargetMachine &TM, 118 const TargetLoweringObjectFile *TLOF); 119 virtual ~TargetLowering(); 120 121 const TargetMachine &getTargetMachine() const { return TM; } 122 const TargetData *getTargetData() const { return TD; } 123 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; } 124 125 bool isBigEndian() const { return !IsLittleEndian; } 126 bool isLittleEndian() const { return IsLittleEndian; } 127 MVT getPointerTy() const { return PointerTy; } 128 virtual MVT getShiftAmountTy(EVT LHSTy) const; 129 130 /// isSelectExpensive - Return true if the select operation is expensive for 131 /// this target. 132 bool isSelectExpensive() const { return SelectIsExpensive; } 133 134 /// isIntDivCheap() - Return true if integer divide is usually cheaper than 135 /// a sequence of several shifts, adds, and multiplies for this target. 136 bool isIntDivCheap() const { return IntDivIsCheap; } 137 138 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of 139 /// srl/add/sra. 140 bool isPow2DivCheap() const { return Pow2DivIsCheap; } 141 142 /// isJumpExpensive() - Return true if Flow Control is an expensive operation 143 /// that should be avoided. 144 bool isJumpExpensive() const { return JumpIsExpensive; } 145 146 /// getSetCCResultType - Return the ValueType of the result of SETCC 147 /// operations. Also used to obtain the target's preferred type for 148 /// the condition operand of SELECT and BRCOND nodes. In the case of 149 /// BRCOND the argument passed is MVT::Other since there are no other 150 /// operands to get a type hint from. 151 virtual 152 MVT::SimpleValueType getSetCCResultType(EVT VT) const; 153 154 /// getCmpLibcallReturnType - Return the ValueType for comparison 155 /// libcalls. Comparions libcalls include floating point comparion calls, 156 /// and Ordered/Unordered check calls on floating point numbers. 157 virtual 158 MVT::SimpleValueType getCmpLibcallReturnType() const; 159 160 /// getBooleanContents - For targets without i1 registers, this gives the 161 /// nature of the high-bits of boolean values held in types wider than i1. 162 /// "Boolean values" are special true/false values produced by nodes like 163 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND. 164 /// Not to be confused with general values promoted from i1. 165 BooleanContent getBooleanContents() const { return BooleanContents;} 166 167 /// getSchedulingPreference - Return target scheduling preference. 168 Sched::Preference getSchedulingPreference() const { 169 return SchedPreferenceInfo; 170 } 171 172 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to 173 /// different scheduling heuristics for different nodes. This function returns 174 /// the preference (or none) for the given node. 175 virtual Sched::Preference getSchedulingPreference(SDNode *N) const { 176 return Sched::None; 177 } 178 179 /// getRegClassFor - Return the register class that should be used for the 180 /// specified value type. 181 virtual TargetRegisterClass *getRegClassFor(EVT VT) const { 182 assert(VT.isSimple() && "getRegClassFor called on illegal type!"); 183 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy]; 184 assert(RC && "This value type is not natively supported!"); 185 return RC; 186 } 187 188 /// getRepRegClassFor - Return the 'representative' register class for the 189 /// specified value type. The 'representative' register class is the largest 190 /// legal super-reg register class for the register class of the value type. 191 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32; 192 /// while the rep register class is GR64 on x86_64. 193 virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const { 194 assert(VT.isSimple() && "getRepRegClassFor called on illegal type!"); 195 const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy]; 196 return RC; 197 } 198 199 /// getRepRegClassCostFor - Return the cost of the 'representative' register 200 /// class for the specified value type. 201 virtual uint8_t getRepRegClassCostFor(EVT VT) const { 202 assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!"); 203 return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy]; 204 } 205 206 /// isTypeLegal - Return true if the target has native support for the 207 /// specified value type. This means that it has a register that directly 208 /// holds it without promotions or expansions. 209 bool isTypeLegal(EVT VT) const { 210 assert(!VT.isSimple() || 211 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)); 212 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0; 213 } 214 215 class ValueTypeActionImpl { 216 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum 217 /// that indicates how instruction selection should deal with the type. 218 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE]; 219 220 public: 221 ValueTypeActionImpl() { 222 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0); 223 } 224 225 LegalizeTypeAction getTypeAction(MVT VT) const { 226 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy]; 227 } 228 229 void setTypeAction(EVT VT, LegalizeTypeAction Action) { 230 unsigned I = VT.getSimpleVT().SimpleTy; 231 ValueTypeActions[I] = Action; 232 } 233 }; 234 235 const ValueTypeActionImpl &getValueTypeActions() const { 236 return ValueTypeActions; 237 } 238 239 /// getTypeAction - Return how we should legalize values of this type, either 240 /// it is already legal (return 'Legal') or we need to promote it to a larger 241 /// type (return 'Promote'), or we need to expand it into multiple registers 242 /// of smaller integer type (return 'Expand'). 'Custom' is not an option. 243 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const { 244 return getTypeConversion(Context, VT).first; 245 } 246 LegalizeTypeAction getTypeAction(MVT VT) const { 247 return ValueTypeActions.getTypeAction(VT); 248 } 249 250 /// getTypeToTransformTo - For types supported by the target, this is an 251 /// identity function. For types that must be promoted to larger types, this 252 /// returns the larger type to promote to. For integer types that are larger 253 /// than the largest integer register, this contains one step in the expansion 254 /// to get to the smaller register. For illegal floating point types, this 255 /// returns the integer type to transform to. 256 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const { 257 return getTypeConversion(Context, VT).second; 258 } 259 260 /// getTypeToExpandTo - For types supported by the target, this is an 261 /// identity function. For types that must be expanded (i.e. integer types 262 /// that are larger than the largest integer register or illegal floating 263 /// point types), this returns the largest legal type it will be expanded to. 264 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const { 265 assert(!VT.isVector()); 266 while (true) { 267 switch (getTypeAction(Context, VT)) { 268 case Legal: 269 return VT; 270 case Expand: 271 VT = getTypeToTransformTo(Context, VT); 272 break; 273 default: 274 assert(false && "Type is not legal nor is it to be expanded!"); 275 return VT; 276 } 277 } 278 return VT; 279 } 280 281 /// getVectorTypeBreakdown - Vector types are broken down into some number of 282 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32 283 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack. 284 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86. 285 /// 286 /// This method returns the number of registers needed, and the VT for each 287 /// register. It also returns the VT and quantity of the intermediate values 288 /// before they are promoted/expanded. 289 /// 290 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT, 291 EVT &IntermediateVT, 292 unsigned &NumIntermediates, 293 EVT &RegisterVT) const; 294 295 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the 296 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If 297 /// this is the case, it returns true and store the intrinsic 298 /// information into the IntrinsicInfo that was passed to the function. 299 struct IntrinsicInfo { 300 unsigned opc; // target opcode 301 EVT memVT; // memory VT 302 const Value* ptrVal; // value representing memory location 303 int offset; // offset off of ptrVal 304 unsigned align; // alignment 305 bool vol; // is volatile? 306 bool readMem; // reads memory? 307 bool writeMem; // writes memory? 308 }; 309 310 virtual bool getTgtMemIntrinsic(IntrinsicInfo &Info, 311 const CallInst &I, unsigned Intrinsic) const { 312 return false; 313 } 314 315 /// isFPImmLegal - Returns true if the target can instruction select the 316 /// specified FP immediate natively. If false, the legalizer will materialize 317 /// the FP immediate as a load from a constant pool. 318 virtual bool isFPImmLegal(const APFloat &Imm, EVT VT) const { 319 return false; 320 } 321 322 /// isShuffleMaskLegal - Targets can use this to indicate that they only 323 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 324 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 325 /// are assumed to be legal. 326 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask, 327 EVT VT) const { 328 return true; 329 } 330 331 /// canOpTrap - Returns true if the operation can trap for the value type. 332 /// VT must be a legal type. By default, we optimistically assume most 333 /// operations don't trap except for divide and remainder. 334 virtual bool canOpTrap(unsigned Op, EVT VT) const; 335 336 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is 337 /// used by Targets can use this to indicate if there is a suitable 338 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant 339 /// pool entry. 340 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 341 EVT VT) const { 342 return false; 343 } 344 345 /// getOperationAction - Return how this operation should be treated: either 346 /// it is legal, needs to be promoted to a larger size, needs to be 347 /// expanded to some other code sequence, or the target has a custom expander 348 /// for it. 349 LegalizeAction getOperationAction(unsigned Op, EVT VT) const { 350 if (VT.isExtended()) return Expand; 351 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!"); 352 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy; 353 return (LegalizeAction)OpActions[I][Op]; 354 } 355 356 /// isOperationLegalOrCustom - Return true if the specified operation is 357 /// legal on this target or can be made legal with custom lowering. This 358 /// is used to help guide high-level lowering decisions. 359 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const { 360 return (VT == MVT::Other || isTypeLegal(VT)) && 361 (getOperationAction(Op, VT) == Legal || 362 getOperationAction(Op, VT) == Custom); 363 } 364 365 /// isOperationLegal - Return true if the specified operation is legal on this 366 /// target. 367 bool isOperationLegal(unsigned Op, EVT VT) const { 368 return (VT == MVT::Other || isTypeLegal(VT)) && 369 getOperationAction(Op, VT) == Legal; 370 } 371 372 /// getLoadExtAction - Return how this load with extension should be treated: 373 /// either it is legal, needs to be promoted to a larger size, needs to be 374 /// expanded to some other code sequence, or the target has a custom expander 375 /// for it. 376 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const { 377 assert(ExtType < ISD::LAST_LOADEXT_TYPE && 378 VT.getSimpleVT() < MVT::LAST_VALUETYPE && 379 "Table isn't big enough!"); 380 return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType]; 381 } 382 383 /// isLoadExtLegal - Return true if the specified load with extension is legal 384 /// on this target. 385 bool isLoadExtLegal(unsigned ExtType, EVT VT) const { 386 return VT.isSimple() && getLoadExtAction(ExtType, VT) == Legal; 387 } 388 389 /// getTruncStoreAction - Return how this store with truncation should be 390 /// treated: either it is legal, needs to be promoted to a larger size, needs 391 /// to be expanded to some other code sequence, or the target has a custom 392 /// expander for it. 393 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const { 394 assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE && 395 MemVT.getSimpleVT() < MVT::LAST_VALUETYPE && 396 "Table isn't big enough!"); 397 return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy] 398 [MemVT.getSimpleVT().SimpleTy]; 399 } 400 401 /// isTruncStoreLegal - Return true if the specified store with truncation is 402 /// legal on this target. 403 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const { 404 return isTypeLegal(ValVT) && MemVT.isSimple() && 405 getTruncStoreAction(ValVT, MemVT) == Legal; 406 } 407 408 /// getIndexedLoadAction - Return how the indexed load should be treated: 409 /// either it is legal, needs to be promoted to a larger size, needs to be 410 /// expanded to some other code sequence, or the target has a custom expander 411 /// for it. 412 LegalizeAction 413 getIndexedLoadAction(unsigned IdxMode, EVT VT) const { 414 assert(IdxMode < ISD::LAST_INDEXED_MODE && 415 VT.getSimpleVT() < MVT::LAST_VALUETYPE && 416 "Table isn't big enough!"); 417 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy; 418 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4); 419 } 420 421 /// isIndexedLoadLegal - Return true if the specified indexed load is legal 422 /// on this target. 423 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const { 424 return VT.isSimple() && 425 (getIndexedLoadAction(IdxMode, VT) == Legal || 426 getIndexedLoadAction(IdxMode, VT) == Custom); 427 } 428 429 /// getIndexedStoreAction - Return how the indexed store should be treated: 430 /// either it is legal, needs to be promoted to a larger size, needs to be 431 /// expanded to some other code sequence, or the target has a custom expander 432 /// for it. 433 LegalizeAction 434 getIndexedStoreAction(unsigned IdxMode, EVT VT) const { 435 assert(IdxMode < ISD::LAST_INDEXED_MODE && 436 VT.getSimpleVT() < MVT::LAST_VALUETYPE && 437 "Table isn't big enough!"); 438 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy; 439 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f); 440 } 441 442 /// isIndexedStoreLegal - Return true if the specified indexed load is legal 443 /// on this target. 444 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const { 445 return VT.isSimple() && 446 (getIndexedStoreAction(IdxMode, VT) == Legal || 447 getIndexedStoreAction(IdxMode, VT) == Custom); 448 } 449 450 /// getCondCodeAction - Return how the condition code should be treated: 451 /// either it is legal, needs to be expanded to some other code sequence, 452 /// or the target has a custom expander for it. 453 LegalizeAction 454 getCondCodeAction(ISD::CondCode CC, EVT VT) const { 455 assert((unsigned)CC < array_lengthof(CondCodeActions) && 456 (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 && 457 "Table isn't big enough!"); 458 LegalizeAction Action = (LegalizeAction) 459 ((CondCodeActions[CC] >> (2*VT.getSimpleVT().SimpleTy)) & 3); 460 assert(Action != Promote && "Can't promote condition code!"); 461 return Action; 462 } 463 464 /// isCondCodeLegal - Return true if the specified condition code is legal 465 /// on this target. 466 bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const { 467 return getCondCodeAction(CC, VT) == Legal || 468 getCondCodeAction(CC, VT) == Custom; 469 } 470 471 472 /// getTypeToPromoteTo - If the action for this operation is to promote, this 473 /// method returns the ValueType to promote to. 474 EVT getTypeToPromoteTo(unsigned Op, EVT VT) const { 475 assert(getOperationAction(Op, VT) == Promote && 476 "This operation isn't promoted!"); 477 478 // See if this has an explicit type specified. 479 std::map<std::pair<unsigned, MVT::SimpleValueType>, 480 MVT::SimpleValueType>::const_iterator PTTI = 481 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy)); 482 if (PTTI != PromoteToType.end()) return PTTI->second; 483 484 assert((VT.isInteger() || VT.isFloatingPoint()) && 485 "Cannot autopromote this type, add it with AddPromotedToType."); 486 487 EVT NVT = VT; 488 do { 489 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1); 490 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && 491 "Didn't find type to promote to!"); 492 } while (!isTypeLegal(NVT) || 493 getOperationAction(Op, NVT) == Promote); 494 return NVT; 495 } 496 497 /// getValueType - Return the EVT corresponding to this LLVM type. 498 /// This is fixed by the LLVM operations except for the pointer size. If 499 /// AllowUnknown is true, this will return MVT::Other for types with no EVT 500 /// counterpart (e.g. structs), otherwise it will assert. 501 EVT getValueType(Type *Ty, bool AllowUnknown = false) const { 502 EVT VT = EVT::getEVT(Ty, AllowUnknown); 503 return VT == MVT::iPTR ? PointerTy : VT; 504 } 505 506 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 507 /// function arguments in the caller parameter area. This is the actual 508 /// alignment, not its logarithm. 509 virtual unsigned getByValTypeAlignment(Type *Ty) const; 510 511 /// getRegisterType - Return the type of registers that this ValueType will 512 /// eventually require. 513 EVT getRegisterType(MVT VT) const { 514 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT)); 515 return RegisterTypeForVT[VT.SimpleTy]; 516 } 517 518 /// getRegisterType - Return the type of registers that this ValueType will 519 /// eventually require. 520 EVT getRegisterType(LLVMContext &Context, EVT VT) const { 521 if (VT.isSimple()) { 522 assert((unsigned)VT.getSimpleVT().SimpleTy < 523 array_lengthof(RegisterTypeForVT)); 524 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy]; 525 } 526 if (VT.isVector()) { 527 EVT VT1, RegisterVT; 528 unsigned NumIntermediates; 529 (void)getVectorTypeBreakdown(Context, VT, VT1, 530 NumIntermediates, RegisterVT); 531 return RegisterVT; 532 } 533 if (VT.isInteger()) { 534 return getRegisterType(Context, getTypeToTransformTo(Context, VT)); 535 } 536 assert(0 && "Unsupported extended type!"); 537 return EVT(MVT::Other); // Not reached 538 } 539 540 /// getNumRegisters - Return the number of registers that this ValueType will 541 /// eventually require. This is one for any types promoted to live in larger 542 /// registers, but may be more than one for types (like i64) that are split 543 /// into pieces. For types like i140, which are first promoted then expanded, 544 /// it is the number of registers needed to hold all the bits of the original 545 /// type. For an i140 on a 32 bit machine this means 5 registers. 546 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const { 547 if (VT.isSimple()) { 548 assert((unsigned)VT.getSimpleVT().SimpleTy < 549 array_lengthof(NumRegistersForVT)); 550 return NumRegistersForVT[VT.getSimpleVT().SimpleTy]; 551 } 552 if (VT.isVector()) { 553 EVT VT1, VT2; 554 unsigned NumIntermediates; 555 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2); 556 } 557 if (VT.isInteger()) { 558 unsigned BitWidth = VT.getSizeInBits(); 559 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits(); 560 return (BitWidth + RegWidth - 1) / RegWidth; 561 } 562 assert(0 && "Unsupported extended type!"); 563 return 0; // Not reached 564 } 565 566 /// ShouldShrinkFPConstant - If true, then instruction selection should 567 /// seek to shrink the FP constant of the specified type to a smaller type 568 /// in order to save space and / or reduce runtime. 569 virtual bool ShouldShrinkFPConstant(EVT VT) const { return true; } 570 571 /// hasTargetDAGCombine - If true, the target has custom DAG combine 572 /// transformations that it can perform for the specified node. 573 bool hasTargetDAGCombine(ISD::NodeType NT) const { 574 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)); 575 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7)); 576 } 577 578 /// This function returns the maximum number of store operations permitted 579 /// to replace a call to llvm.memset. The value is set by the target at the 580 /// performance threshold for such a replacement. If OptSize is true, 581 /// return the limit for functions that have OptSize attribute. 582 /// @brief Get maximum # of store operations permitted for llvm.memset 583 unsigned getMaxStoresPerMemset(bool OptSize) const { 584 return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset; 585 } 586 587 /// This function returns the maximum number of store operations permitted 588 /// to replace a call to llvm.memcpy. The value is set by the target at the 589 /// performance threshold for such a replacement. If OptSize is true, 590 /// return the limit for functions that have OptSize attribute. 591 /// @brief Get maximum # of store operations permitted for llvm.memcpy 592 unsigned getMaxStoresPerMemcpy(bool OptSize) const { 593 return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy; 594 } 595 596 /// This function returns the maximum number of store operations permitted 597 /// to replace a call to llvm.memmove. The value is set by the target at the 598 /// performance threshold for such a replacement. If OptSize is true, 599 /// return the limit for functions that have OptSize attribute. 600 /// @brief Get maximum # of store operations permitted for llvm.memmove 601 unsigned getMaxStoresPerMemmove(bool OptSize) const { 602 return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove; 603 } 604 605 /// This function returns true if the target allows unaligned memory accesses. 606 /// of the specified type. This is used, for example, in situations where an 607 /// array copy/move/set is converted to a sequence of store operations. It's 608 /// use helps to ensure that such replacements don't generate code that causes 609 /// an alignment error (trap) on the target machine. 610 /// @brief Determine if the target supports unaligned memory accesses. 611 virtual bool allowsUnalignedMemoryAccesses(EVT VT) const { 612 return false; 613 } 614 615 /// This function returns true if the target would benefit from code placement 616 /// optimization. 617 /// @brief Determine if the target should perform code placement optimization. 618 bool shouldOptimizeCodePlacement() const { 619 return benefitFromCodePlacementOpt; 620 } 621 622 /// getOptimalMemOpType - Returns the target specific optimal type for load 623 /// and store operations as a result of memset, memcpy, and memmove 624 /// lowering. If DstAlign is zero that means it's safe to destination 625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 626 /// means there isn't a need to check it against alignment requirement, 627 /// probably because the source does not need to be loaded. If 628 /// 'NonScalarIntSafe' is true, that means it's safe to return a 629 /// non-scalar-integer type, e.g. empty string source, constant, or loaded 630 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 631 /// constant so it does not need to be loaded. 632 /// It returns EVT::Other if the type should be determined using generic 633 /// target-independent logic. 634 virtual EVT getOptimalMemOpType(uint64_t Size, 635 unsigned DstAlign, unsigned SrcAlign, 636 bool NonScalarIntSafe, bool MemcpyStrSrc, 637 MachineFunction &MF) const { 638 return MVT::Other; 639 } 640 641 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp 642 /// to implement llvm.setjmp. 643 bool usesUnderscoreSetJmp() const { 644 return UseUnderscoreSetJmp; 645 } 646 647 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp 648 /// to implement llvm.longjmp. 649 bool usesUnderscoreLongJmp() const { 650 return UseUnderscoreLongJmp; 651 } 652 653 /// getStackPointerRegisterToSaveRestore - If a physical register, this 654 /// specifies the register that llvm.savestack/llvm.restorestack should save 655 /// and restore. 656 unsigned getStackPointerRegisterToSaveRestore() const { 657 return StackPointerRegisterToSaveRestore; 658 } 659 660 /// getExceptionAddressRegister - If a physical register, this returns 661 /// the register that receives the exception address on entry to a landing 662 /// pad. 663 unsigned getExceptionAddressRegister() const { 664 return ExceptionPointerRegister; 665 } 666 667 /// getExceptionSelectorRegister - If a physical register, this returns 668 /// the register that receives the exception typeid on entry to a landing 669 /// pad. 670 unsigned getExceptionSelectorRegister() const { 671 return ExceptionSelectorRegister; 672 } 673 674 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never 675 /// set, the default is 200) 676 unsigned getJumpBufSize() const { 677 return JumpBufSize; 678 } 679 680 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes 681 /// (if never set, the default is 0) 682 unsigned getJumpBufAlignment() const { 683 return JumpBufAlignment; 684 } 685 686 /// getMinStackArgumentAlignment - return the minimum stack alignment of an 687 /// argument. 688 unsigned getMinStackArgumentAlignment() const { 689 return MinStackArgumentAlignment; 690 } 691 692 /// getMinFunctionAlignment - return the minimum function alignment. 693 /// 694 unsigned getMinFunctionAlignment() const { 695 return MinFunctionAlignment; 696 } 697 698 /// getPrefFunctionAlignment - return the preferred function alignment. 699 /// 700 unsigned getPrefFunctionAlignment() const { 701 return PrefFunctionAlignment; 702 } 703 704 /// getPrefLoopAlignment - return the preferred loop alignment. 705 /// 706 unsigned getPrefLoopAlignment() const { 707 return PrefLoopAlignment; 708 } 709 710 /// getShouldFoldAtomicFences - return whether the combiner should fold 711 /// fence MEMBARRIER instructions into the atomic intrinsic instructions. 712 /// 713 bool getShouldFoldAtomicFences() const { 714 return ShouldFoldAtomicFences; 715 } 716 717 /// getPreIndexedAddressParts - returns true by value, base pointer and 718 /// offset pointer and addressing mode by reference if the node's address 719 /// can be legally represented as pre-indexed load / store address. 720 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, 721 SDValue &Offset, 722 ISD::MemIndexedMode &AM, 723 SelectionDAG &DAG) const { 724 return false; 725 } 726 727 /// getPostIndexedAddressParts - returns true by value, base pointer and 728 /// offset pointer and addressing mode by reference if this node can be 729 /// combined with a load / store to form a post-indexed load / store. 730 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, 731 SDValue &Base, SDValue &Offset, 732 ISD::MemIndexedMode &AM, 733 SelectionDAG &DAG) const { 734 return false; 735 } 736 737 /// getJumpTableEncoding - Return the entry encoding for a jump table in the 738 /// current function. The returned value is a member of the 739 /// MachineJumpTableInfo::JTEntryKind enum. 740 virtual unsigned getJumpTableEncoding() const; 741 742 virtual const MCExpr * 743 LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 744 const MachineBasicBlock *MBB, unsigned uid, 745 MCContext &Ctx) const { 746 assert(0 && "Need to implement this hook if target has custom JTIs"); 747 return 0; 748 } 749 750 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 751 /// jumptable. 752 virtual SDValue getPICJumpTableRelocBase(SDValue Table, 753 SelectionDAG &DAG) const; 754 755 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 756 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 757 /// MCExpr. 758 virtual const MCExpr * 759 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 760 unsigned JTI, MCContext &Ctx) const; 761 762 /// isOffsetFoldingLegal - Return true if folding a constant offset 763 /// with the given GlobalAddress is legal. It is frequently not legal in 764 /// PIC relocation models. 765 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const; 766 767 /// getStackCookieLocation - Return true if the target stores stack 768 /// protector cookies at a fixed offset in some non-standard address 769 /// space, and populates the address space and offset as 770 /// appropriate. 771 virtual bool getStackCookieLocation(unsigned &AddressSpace, unsigned &Offset) const { 772 return false; 773 } 774 775 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be 776 /// used for loads / stores from the global. 777 virtual unsigned getMaximalGlobalOffset() const { 778 return 0; 779 } 780 781 //===--------------------------------------------------------------------===// 782 // TargetLowering Optimization Methods 783 // 784 785 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two 786 /// SDValues for returning information from TargetLowering to its clients 787 /// that want to combine 788 struct TargetLoweringOpt { 789 SelectionDAG &DAG; 790 bool LegalTys; 791 bool LegalOps; 792 SDValue Old; 793 SDValue New; 794 795 explicit TargetLoweringOpt(SelectionDAG &InDAG, 796 bool LT, bool LO) : 797 DAG(InDAG), LegalTys(LT), LegalOps(LO) {} 798 799 bool LegalTypes() const { return LegalTys; } 800 bool LegalOperations() const { return LegalOps; } 801 802 bool CombineTo(SDValue O, SDValue N) { 803 Old = O; 804 New = N; 805 return true; 806 } 807 808 /// ShrinkDemandedConstant - Check to see if the specified operand of the 809 /// specified instruction is a constant integer. If so, check to see if 810 /// there are any bits set in the constant that are not demanded. If so, 811 /// shrink the constant and return true. 812 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded); 813 814 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the 815 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening 816 /// cast, but it could be generalized for targets with other types of 817 /// implicit widening casts. 818 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded, 819 DebugLoc dl); 820 }; 821 822 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the 823 /// DemandedMask bits of the result of Op are ever used downstream. If we can 824 /// use this information to simplify Op, create a new simplified DAG node and 825 /// return true, returning the original and new nodes in Old and New. 826 /// Otherwise, analyze the expression and return a mask of KnownOne and 827 /// KnownZero bits for the expression (used to simplify the caller). 828 /// The KnownZero/One bits may only be accurate for those bits in the 829 /// DemandedMask. 830 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask, 831 APInt &KnownZero, APInt &KnownOne, 832 TargetLoweringOpt &TLO, unsigned Depth = 0) const; 833 834 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in 835 /// Mask are known to be either zero or one and return them in the 836 /// KnownZero/KnownOne bitsets. 837 virtual void computeMaskedBitsForTargetNode(const SDValue Op, 838 const APInt &Mask, 839 APInt &KnownZero, 840 APInt &KnownOne, 841 const SelectionDAG &DAG, 842 unsigned Depth = 0) const; 843 844 /// ComputeNumSignBitsForTargetNode - This method can be implemented by 845 /// targets that want to expose additional information about sign bits to the 846 /// DAG Combiner. 847 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op, 848 unsigned Depth = 0) const; 849 850 struct DAGCombinerInfo { 851 void *DC; // The DAG Combiner object. 852 bool BeforeLegalize; 853 bool BeforeLegalizeOps; 854 bool CalledByLegalizer; 855 public: 856 SelectionDAG &DAG; 857 858 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc) 859 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo), 860 CalledByLegalizer(cl), DAG(dag) {} 861 862 bool isBeforeLegalize() const { return BeforeLegalize; } 863 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; } 864 bool isCalledByLegalizer() const { return CalledByLegalizer; } 865 866 void AddToWorklist(SDNode *N); 867 void RemoveFromWorklist(SDNode *N); 868 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To, 869 bool AddTo = true); 870 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true); 871 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true); 872 873 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO); 874 }; 875 876 /// SimplifySetCC - Try to simplify a setcc built with the specified operands 877 /// and cc. If it is unable to simplify it, return a null SDValue. 878 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 879 ISD::CondCode Cond, bool foldBooleans, 880 DAGCombinerInfo &DCI, DebugLoc dl) const; 881 882 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 883 /// node is a GlobalAddress + offset. 884 virtual bool 885 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const; 886 887 /// PerformDAGCombine - This method will be invoked for all target nodes and 888 /// for any target-independent nodes that the target has registered with 889 /// invoke it for. 890 /// 891 /// The semantics are as follows: 892 /// Return Value: 893 /// SDValue.Val == 0 - No change was made 894 /// SDValue.Val == N - N was replaced, is dead, and is already handled. 895 /// otherwise - N should be replaced by the returned Operand. 896 /// 897 /// In addition, methods provided by DAGCombinerInfo may be used to perform 898 /// more complex transformations. 899 /// 900 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const; 901 902 /// isTypeDesirableForOp - Return true if the target has native support for 903 /// the specified value type and it is 'desirable' to use the type for the 904 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16 905 /// instruction encodings are longer and some i16 instructions are slow. 906 virtual bool isTypeDesirableForOp(unsigned Opc, EVT VT) const { 907 // By default, assume all legal types are desirable. 908 return isTypeLegal(VT); 909 } 910 911 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner 912 /// to transform a floating point op of specified opcode to a equivalent op of 913 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM. 914 virtual bool isDesirableToTransformToIntegerOp(unsigned Opc, EVT VT) const { 915 return false; 916 } 917 918 /// IsDesirableToPromoteOp - This method query the target whether it is 919 /// beneficial for dag combiner to promote the specified node. If true, it 920 /// should return the desired promotion type by reference. 921 virtual bool IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 922 return false; 923 } 924 925 //===--------------------------------------------------------------------===// 926 // TargetLowering Configuration Methods - These methods should be invoked by 927 // the derived class constructor to configure this object for the target. 928 // 929 930 protected: 931 /// setBooleanContents - Specify how the target extends the result of a 932 /// boolean value from i1 to a wider type. See getBooleanContents. 933 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; } 934 935 /// setSchedulingPreference - Specify the target scheduling preference. 936 void setSchedulingPreference(Sched::Preference Pref) { 937 SchedPreferenceInfo = Pref; 938 } 939 940 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to 941 /// use _setjmp to implement llvm.setjmp or the non _ version. 942 /// Defaults to false. 943 void setUseUnderscoreSetJmp(bool Val) { 944 UseUnderscoreSetJmp = Val; 945 } 946 947 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to 948 /// use _longjmp to implement llvm.longjmp or the non _ version. 949 /// Defaults to false. 950 void setUseUnderscoreLongJmp(bool Val) { 951 UseUnderscoreLongJmp = Val; 952 } 953 954 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this 955 /// specifies the register that llvm.savestack/llvm.restorestack should save 956 /// and restore. 957 void setStackPointerRegisterToSaveRestore(unsigned R) { 958 StackPointerRegisterToSaveRestore = R; 959 } 960 961 /// setExceptionPointerRegister - If set to a physical register, this sets 962 /// the register that receives the exception address on entry to a landing 963 /// pad. 964 void setExceptionPointerRegister(unsigned R) { 965 ExceptionPointerRegister = R; 966 } 967 968 /// setExceptionSelectorRegister - If set to a physical register, this sets 969 /// the register that receives the exception typeid on entry to a landing 970 /// pad. 971 void setExceptionSelectorRegister(unsigned R) { 972 ExceptionSelectorRegister = R; 973 } 974 975 /// SelectIsExpensive - Tells the code generator not to expand operations 976 /// into sequences that use the select operations if possible. 977 void setSelectIsExpensive(bool isExpensive = true) { 978 SelectIsExpensive = isExpensive; 979 } 980 981 /// JumpIsExpensive - Tells the code generator not to expand sequence of 982 /// operations into a separate sequences that increases the amount of 983 /// flow control. 984 void setJumpIsExpensive(bool isExpensive = true) { 985 JumpIsExpensive = isExpensive; 986 } 987 988 /// setIntDivIsCheap - Tells the code generator that integer divide is 989 /// expensive, and if possible, should be replaced by an alternate sequence 990 /// of instructions not containing an integer divide. 991 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; } 992 993 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate 994 /// srl/add/sra for a signed divide by power of two, and let the target handle 995 /// it. 996 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; } 997 998 /// addRegisterClass - Add the specified register class as an available 999 /// regclass for the specified value type. This indicates the selector can 1000 /// handle values of that class natively. 1001 void addRegisterClass(EVT VT, TargetRegisterClass *RC) { 1002 assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)); 1003 AvailableRegClasses.push_back(std::make_pair(VT, RC)); 1004 RegClassForVT[VT.getSimpleVT().SimpleTy] = RC; 1005 } 1006 1007 /// findRepresentativeClass - Return the largest legal super-reg register class 1008 /// of the register class for the specified type and its associated "cost". 1009 virtual std::pair<const TargetRegisterClass*, uint8_t> 1010 findRepresentativeClass(EVT VT) const; 1011 1012 /// computeRegisterProperties - Once all of the register classes are added, 1013 /// this allows us to compute derived properties we expose. 1014 void computeRegisterProperties(); 1015 1016 /// setOperationAction - Indicate that the specified operation does not work 1017 /// with the specified type and indicate what to do about it. 1018 void setOperationAction(unsigned Op, MVT VT, 1019 LegalizeAction Action) { 1020 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!"); 1021 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action; 1022 } 1023 1024 /// setLoadExtAction - Indicate that the specified load with extension does 1025 /// not work with the specified type and indicate what to do about it. 1026 void setLoadExtAction(unsigned ExtType, MVT VT, 1027 LegalizeAction Action) { 1028 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE && 1029 "Table isn't big enough!"); 1030 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action; 1031 } 1032 1033 /// setTruncStoreAction - Indicate that the specified truncating store does 1034 /// not work with the specified type and indicate what to do about it. 1035 void setTruncStoreAction(MVT ValVT, MVT MemVT, 1036 LegalizeAction Action) { 1037 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE && 1038 "Table isn't big enough!"); 1039 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action; 1040 } 1041 1042 /// setIndexedLoadAction - Indicate that the specified indexed load does or 1043 /// does not work with the specified type and indicate what to do abort 1044 /// it. NOTE: All indexed mode loads are initialized to Expand in 1045 /// TargetLowering.cpp 1046 void setIndexedLoadAction(unsigned IdxMode, MVT VT, 1047 LegalizeAction Action) { 1048 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE && 1049 (unsigned)Action < 0xf && "Table isn't big enough!"); 1050 // Load action are kept in the upper half. 1051 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0; 1052 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4; 1053 } 1054 1055 /// setIndexedStoreAction - Indicate that the specified indexed store does or 1056 /// does not work with the specified type and indicate what to do about 1057 /// it. NOTE: All indexed mode stores are initialized to Expand in 1058 /// TargetLowering.cpp 1059 void setIndexedStoreAction(unsigned IdxMode, MVT VT, 1060 LegalizeAction Action) { 1061 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE && 1062 (unsigned)Action < 0xf && "Table isn't big enough!"); 1063 // Store action are kept in the lower half. 1064 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f; 1065 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action); 1066 } 1067 1068 /// setCondCodeAction - Indicate that the specified condition code is or isn't 1069 /// supported on the target and indicate what to do about it. 1070 void setCondCodeAction(ISD::CondCode CC, MVT VT, 1071 LegalizeAction Action) { 1072 assert(VT < MVT::LAST_VALUETYPE && 1073 (unsigned)CC < array_lengthof(CondCodeActions) && 1074 "Table isn't big enough!"); 1075 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.SimpleTy*2); 1076 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.SimpleTy*2; 1077 } 1078 1079 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the 1080 /// promotion code defaults to trying a larger integer/fp until it can find 1081 /// one that works. If that default is insufficient, this method can be used 1082 /// by the target to override the default. 1083 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) { 1084 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy; 1085 } 1086 1087 /// setTargetDAGCombine - Targets should invoke this method for each target 1088 /// independent node that they want to provide a custom DAG combiner for by 1089 /// implementing the PerformDAGCombine virtual method. 1090 void setTargetDAGCombine(ISD::NodeType NT) { 1091 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)); 1092 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7); 1093 } 1094 1095 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in 1096 /// bytes); default is 200 1097 void setJumpBufSize(unsigned Size) { 1098 JumpBufSize = Size; 1099 } 1100 1101 /// setJumpBufAlignment - Set the target's required jmp_buf buffer 1102 /// alignment (in bytes); default is 0 1103 void setJumpBufAlignment(unsigned Align) { 1104 JumpBufAlignment = Align; 1105 } 1106 1107 /// setMinFunctionAlignment - Set the target's minimum function alignment. 1108 void setMinFunctionAlignment(unsigned Align) { 1109 MinFunctionAlignment = Align; 1110 } 1111 1112 /// setPrefFunctionAlignment - Set the target's preferred function alignment. 1113 /// This should be set if there is a performance benefit to 1114 /// higher-than-minimum alignment 1115 void setPrefFunctionAlignment(unsigned Align) { 1116 PrefFunctionAlignment = Align; 1117 } 1118 1119 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default 1120 /// alignment is zero, it means the target does not care about loop alignment. 1121 void setPrefLoopAlignment(unsigned Align) { 1122 PrefLoopAlignment = Align; 1123 } 1124 1125 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an 1126 /// argument. 1127 void setMinStackArgumentAlignment(unsigned Align) { 1128 MinStackArgumentAlignment = Align; 1129 } 1130 1131 /// setShouldFoldAtomicFences - Set if the target's implementation of the 1132 /// atomic operation intrinsics includes locking. Default is false. 1133 void setShouldFoldAtomicFences(bool fold) { 1134 ShouldFoldAtomicFences = fold; 1135 } 1136 1137 public: 1138 //===--------------------------------------------------------------------===// 1139 // Lowering methods - These methods must be implemented by targets so that 1140 // the SelectionDAGLowering code knows how to lower these. 1141 // 1142 1143 /// LowerFormalArguments - This hook must be implemented to lower the 1144 /// incoming (formal) arguments, described by the Ins array, into the 1145 /// specified DAG. The implementation should fill in the InVals array 1146 /// with legal-type argument values, and return the resulting token 1147 /// chain value. 1148 /// 1149 virtual SDValue 1150 LowerFormalArguments(SDValue Chain, 1151 CallingConv::ID CallConv, bool isVarArg, 1152 const SmallVectorImpl<ISD::InputArg> &Ins, 1153 DebugLoc dl, SelectionDAG &DAG, 1154 SmallVectorImpl<SDValue> &InVals) const { 1155 assert(0 && "Not Implemented"); 1156 return SDValue(); // this is here to silence compiler errors 1157 } 1158 1159 /// LowerCallTo - This function lowers an abstract call to a function into an 1160 /// actual call. This returns a pair of operands. The first element is the 1161 /// return value for the function (if RetTy is not VoidTy). The second 1162 /// element is the outgoing token chain. It calls LowerCall to do the actual 1163 /// lowering. 1164 struct ArgListEntry { 1165 SDValue Node; 1166 Type* Ty; 1167 bool isSExt : 1; 1168 bool isZExt : 1; 1169 bool isInReg : 1; 1170 bool isSRet : 1; 1171 bool isNest : 1; 1172 bool isByVal : 1; 1173 uint16_t Alignment; 1174 1175 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false), 1176 isSRet(false), isNest(false), isByVal(false), Alignment(0) { } 1177 }; 1178 typedef std::vector<ArgListEntry> ArgListTy; 1179 std::pair<SDValue, SDValue> 1180 LowerCallTo(SDValue Chain, Type *RetTy, bool RetSExt, bool RetZExt, 1181 bool isVarArg, bool isInreg, unsigned NumFixedArgs, 1182 CallingConv::ID CallConv, bool isTailCall, 1183 bool isReturnValueUsed, SDValue Callee, ArgListTy &Args, 1184 SelectionDAG &DAG, DebugLoc dl) const; 1185 1186 /// LowerCall - This hook must be implemented to lower calls into the 1187 /// the specified DAG. The outgoing arguments to the call are described 1188 /// by the Outs array, and the values to be returned by the call are 1189 /// described by the Ins array. The implementation should fill in the 1190 /// InVals array with legal-type return values from the call, and return 1191 /// the resulting token chain value. 1192 virtual SDValue 1193 LowerCall(SDValue Chain, SDValue Callee, 1194 CallingConv::ID CallConv, bool isVarArg, bool &isTailCall, 1195 const SmallVectorImpl<ISD::OutputArg> &Outs, 1196 const SmallVectorImpl<SDValue> &OutVals, 1197 const SmallVectorImpl<ISD::InputArg> &Ins, 1198 DebugLoc dl, SelectionDAG &DAG, 1199 SmallVectorImpl<SDValue> &InVals) const { 1200 assert(0 && "Not Implemented"); 1201 return SDValue(); // this is here to silence compiler errors 1202 } 1203 1204 /// HandleByVal - Target-specific cleanup for formal ByVal parameters. 1205 virtual void HandleByVal(CCState *, unsigned &) const {} 1206 1207 /// CanLowerReturn - This hook should be implemented to check whether the 1208 /// return values described by the Outs array can fit into the return 1209 /// registers. If false is returned, an sret-demotion is performed. 1210 /// 1211 virtual bool CanLowerReturn(CallingConv::ID CallConv, 1212 MachineFunction &MF, bool isVarArg, 1213 const SmallVectorImpl<ISD::OutputArg> &Outs, 1214 LLVMContext &Context) const 1215 { 1216 // Return true by default to get preexisting behavior. 1217 return true; 1218 } 1219 1220 /// LowerReturn - This hook must be implemented to lower outgoing 1221 /// return values, described by the Outs array, into the specified 1222 /// DAG. The implementation should return the resulting token chain 1223 /// value. 1224 /// 1225 virtual SDValue 1226 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1227 const SmallVectorImpl<ISD::OutputArg> &Outs, 1228 const SmallVectorImpl<SDValue> &OutVals, 1229 DebugLoc dl, SelectionDAG &DAG) const { 1230 assert(0 && "Not Implemented"); 1231 return SDValue(); // this is here to silence compiler errors 1232 } 1233 1234 /// isUsedByReturnOnly - Return true if result of the specified node is used 1235 /// by a return node only. This is used to determine whether it is possible 1236 /// to codegen a libcall as tail call at legalization time. 1237 virtual bool isUsedByReturnOnly(SDNode *N) const { 1238 return false; 1239 } 1240 1241 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the 1242 /// call instruction as a tail call. This is used by optimization passes to 1243 /// determine if it's profitable to duplicate return instructions to enable 1244 /// tailcall optimization. 1245 virtual bool mayBeEmittedAsTailCall(CallInst *CI) const { 1246 return false; 1247 } 1248 1249 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or 1250 /// sign extend a zeroext/signext integer argument or return value. 1251 /// FIXME: Most C calling convention requires the return type to be promoted, 1252 /// but this is not true all the time, e.g. i1 on x86-64. It is also not 1253 /// necessary for non-C calling conventions. The frontend should handle this 1254 /// and include all of the necessary information. 1255 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT, 1256 ISD::NodeType ExtendKind) const { 1257 EVT MinVT = getRegisterType(Context, MVT::i32); 1258 return VT.bitsLT(MinVT) ? MinVT : VT; 1259 } 1260 1261 /// LowerOperationWrapper - This callback is invoked by the type legalizer 1262 /// to legalize nodes with an illegal operand type but legal result types. 1263 /// It replaces the LowerOperation callback in the type Legalizer. 1264 /// The reason we can not do away with LowerOperation entirely is that 1265 /// LegalizeDAG isn't yet ready to use this callback. 1266 /// TODO: Consider merging with ReplaceNodeResults. 1267 1268 /// The target places new result values for the node in Results (their number 1269 /// and types must exactly match those of the original return values of 1270 /// the node), or leaves Results empty, which indicates that the node is not 1271 /// to be custom lowered after all. 1272 /// The default implementation calls LowerOperation. 1273 virtual void LowerOperationWrapper(SDNode *N, 1274 SmallVectorImpl<SDValue> &Results, 1275 SelectionDAG &DAG) const; 1276 1277 /// LowerOperation - This callback is invoked for operations that are 1278 /// unsupported by the target, which are registered to use 'custom' lowering, 1279 /// and whose defined values are all legal. 1280 /// If the target has no operations that require custom lowering, it need not 1281 /// implement this. The default implementation of this aborts. 1282 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const; 1283 1284 /// ReplaceNodeResults - This callback is invoked when a node result type is 1285 /// illegal for the target, and the operation was registered to use 'custom' 1286 /// lowering for that result type. The target places new result values for 1287 /// the node in Results (their number and types must exactly match those of 1288 /// the original return values of the node), or leaves Results empty, which 1289 /// indicates that the node is not to be custom lowered after all. 1290 /// 1291 /// If the target has no operations that require custom lowering, it need not 1292 /// implement this. The default implementation aborts. 1293 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 1294 SelectionDAG &DAG) const { 1295 assert(0 && "ReplaceNodeResults not implemented for this target!"); 1296 } 1297 1298 /// getTargetNodeName() - This method returns the name of a target specific 1299 /// DAG node. 1300 virtual const char *getTargetNodeName(unsigned Opcode) const; 1301 1302 /// createFastISel - This method returns a target specific FastISel object, 1303 /// or null if the target does not support "fast" ISel. 1304 virtual FastISel *createFastISel(FunctionLoweringInfo &funcInfo) const { 1305 return 0; 1306 } 1307 1308 //===--------------------------------------------------------------------===// 1309 // Inline Asm Support hooks 1310 // 1311 1312 /// ExpandInlineAsm - This hook allows the target to expand an inline asm 1313 /// call to be explicit llvm code if it wants to. This is useful for 1314 /// turning simple inline asms into LLVM intrinsics, which gives the 1315 /// compiler more information about the behavior of the code. 1316 virtual bool ExpandInlineAsm(CallInst *CI) const { 1317 return false; 1318 } 1319 1320 enum ConstraintType { 1321 C_Register, // Constraint represents specific register(s). 1322 C_RegisterClass, // Constraint represents any of register(s) in class. 1323 C_Memory, // Memory constraint. 1324 C_Other, // Something else. 1325 C_Unknown // Unsupported constraint. 1326 }; 1327 1328 enum ConstraintWeight { 1329 // Generic weights. 1330 CW_Invalid = -1, // No match. 1331 CW_Okay = 0, // Acceptable. 1332 CW_Good = 1, // Good weight. 1333 CW_Better = 2, // Better weight. 1334 CW_Best = 3, // Best weight. 1335 1336 // Well-known weights. 1337 CW_SpecificReg = CW_Okay, // Specific register operands. 1338 CW_Register = CW_Good, // Register operands. 1339 CW_Memory = CW_Better, // Memory operands. 1340 CW_Constant = CW_Best, // Constant operand. 1341 CW_Default = CW_Okay // Default or don't know type. 1342 }; 1343 1344 /// AsmOperandInfo - This contains information for each constraint that we are 1345 /// lowering. 1346 struct AsmOperandInfo : public InlineAsm::ConstraintInfo { 1347 /// ConstraintCode - This contains the actual string for the code, like "m". 1348 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that 1349 /// most closely matches the operand. 1350 std::string ConstraintCode; 1351 1352 /// ConstraintType - Information about the constraint code, e.g. Register, 1353 /// RegisterClass, Memory, Other, Unknown. 1354 TargetLowering::ConstraintType ConstraintType; 1355 1356 /// CallOperandval - If this is the result output operand or a 1357 /// clobber, this is null, otherwise it is the incoming operand to the 1358 /// CallInst. This gets modified as the asm is processed. 1359 Value *CallOperandVal; 1360 1361 /// ConstraintVT - The ValueType for the operand value. 1362 EVT ConstraintVT; 1363 1364 /// isMatchingInputConstraint - Return true of this is an input operand that 1365 /// is a matching constraint like "4". 1366 bool isMatchingInputConstraint() const; 1367 1368 /// getMatchedOperand - If this is an input matching constraint, this method 1369 /// returns the output operand it matches. 1370 unsigned getMatchedOperand() const; 1371 1372 /// Copy constructor for copying from an AsmOperandInfo. 1373 AsmOperandInfo(const AsmOperandInfo &info) 1374 : InlineAsm::ConstraintInfo(info), 1375 ConstraintCode(info.ConstraintCode), 1376 ConstraintType(info.ConstraintType), 1377 CallOperandVal(info.CallOperandVal), 1378 ConstraintVT(info.ConstraintVT) { 1379 } 1380 1381 /// Copy constructor for copying from a ConstraintInfo. 1382 AsmOperandInfo(const InlineAsm::ConstraintInfo &info) 1383 : InlineAsm::ConstraintInfo(info), 1384 ConstraintType(TargetLowering::C_Unknown), 1385 CallOperandVal(0), ConstraintVT(MVT::Other) { 1386 } 1387 }; 1388 1389 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector; 1390 1391 /// ParseConstraints - Split up the constraint string from the inline 1392 /// assembly value into the specific constraints and their prefixes, 1393 /// and also tie in the associated operand values. 1394 /// If this returns an empty vector, and if the constraint string itself 1395 /// isn't empty, there was an error parsing. 1396 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const; 1397 1398 /// Examine constraint type and operand type and determine a weight value. 1399 /// The operand object must already have been set up with the operand type. 1400 virtual ConstraintWeight getMultipleConstraintMatchWeight( 1401 AsmOperandInfo &info, int maIndex) const; 1402 1403 /// Examine constraint string and operand type and determine a weight value. 1404 /// The operand object must already have been set up with the operand type. 1405 virtual ConstraintWeight getSingleConstraintMatchWeight( 1406 AsmOperandInfo &info, const char *constraint) const; 1407 1408 /// ComputeConstraintToUse - Determines the constraint code and constraint 1409 /// type to use for the specific AsmOperandInfo, setting 1410 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand 1411 /// being passed in is available, it can be passed in as Op, otherwise an 1412 /// empty SDValue can be passed. 1413 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, 1414 SDValue Op, 1415 SelectionDAG *DAG = 0) const; 1416 1417 /// getConstraintType - Given a constraint, return the type of constraint it 1418 /// is for this target. 1419 virtual ConstraintType getConstraintType(const std::string &Constraint) const; 1420 1421 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g. 1422 /// {edx}), return the register number and the register class for the 1423 /// register. 1424 /// 1425 /// Given a register class constraint, like 'r', if this corresponds directly 1426 /// to an LLVM register class, return a register of 0 and the register class 1427 /// pointer. 1428 /// 1429 /// This should only be used for C_Register constraints. On error, 1430 /// this returns a register number of 0 and a null register class pointer.. 1431 virtual std::pair<unsigned, const TargetRegisterClass*> 1432 getRegForInlineAsmConstraint(const std::string &Constraint, 1433 EVT VT) const; 1434 1435 /// LowerXConstraint - try to replace an X constraint, which matches anything, 1436 /// with another that has more specific requirements based on the type of the 1437 /// corresponding operand. This returns null if there is no replacement to 1438 /// make. 1439 virtual const char *LowerXConstraint(EVT ConstraintVT) const; 1440 1441 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 1442 /// vector. If it is invalid, don't add anything to Ops. 1443 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint, 1444 std::vector<SDValue> &Ops, 1445 SelectionDAG &DAG) const; 1446 1447 //===--------------------------------------------------------------------===// 1448 // Instruction Emitting Hooks 1449 // 1450 1451 // EmitInstrWithCustomInserter - This method should be implemented by targets 1452 // that mark instructions with the 'usesCustomInserter' flag. These 1453 // instructions are special in various ways, which require special support to 1454 // insert. The specified MachineInstr is created but not inserted into any 1455 // basic blocks, and this method is called to expand it into a sequence of 1456 // instructions, potentially also creating new basic blocks and control flow. 1457 virtual MachineBasicBlock * 1458 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const; 1459 1460 //===--------------------------------------------------------------------===// 1461 // Addressing mode description hooks (used by LSR etc). 1462 // 1463 1464 /// AddrMode - This represents an addressing mode of: 1465 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg 1466 /// If BaseGV is null, there is no BaseGV. 1467 /// If BaseOffs is zero, there is no base offset. 1468 /// If HasBaseReg is false, there is no base register. 1469 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with 1470 /// no scale. 1471 /// 1472 struct AddrMode { 1473 GlobalValue *BaseGV; 1474 int64_t BaseOffs; 1475 bool HasBaseReg; 1476 int64_t Scale; 1477 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {} 1478 }; 1479 1480 /// isLegalAddressingMode - Return true if the addressing mode represented by 1481 /// AM is legal for this target, for a load/store of the specified type. 1482 /// The type may be VoidTy, in which case only return true if the addressing 1483 /// mode is legal for a load/store of any legal type. 1484 /// TODO: Handle pre/postinc as well. 1485 virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty) const; 1486 1487 /// isTruncateFree - Return true if it's free to truncate a value of 1488 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in 1489 /// register EAX to i16 by referencing its sub-register AX. 1490 virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const { 1491 return false; 1492 } 1493 1494 virtual bool isTruncateFree(EVT VT1, EVT VT2) const { 1495 return false; 1496 } 1497 1498 /// isZExtFree - Return true if any actual instruction that defines a 1499 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result 1500 /// register. This does not necessarily include registers defined in 1501 /// unknown ways, such as incoming arguments, or copies from unknown 1502 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this 1503 /// does not necessarily apply to truncate instructions. e.g. on x86-64, 1504 /// all instructions that define 32-bit values implicit zero-extend the 1505 /// result out to 64 bits. 1506 virtual bool isZExtFree(Type *Ty1, Type *Ty2) const { 1507 return false; 1508 } 1509 1510 virtual bool isZExtFree(EVT VT1, EVT VT2) const { 1511 return false; 1512 } 1513 1514 /// isNarrowingProfitable - Return true if it's profitable to narrow 1515 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow 1516 /// from i32 to i8 but not from i32 to i16. 1517 virtual bool isNarrowingProfitable(EVT VT1, EVT VT2) const { 1518 return false; 1519 } 1520 1521 /// isLegalICmpImmediate - Return true if the specified immediate is legal 1522 /// icmp immediate, that is the target has icmp instructions which can compare 1523 /// a register against the immediate without having to materialize the 1524 /// immediate into a register. 1525 virtual bool isLegalICmpImmediate(int64_t Imm) const { 1526 return true; 1527 } 1528 1529 /// isLegalAddImmediate - Return true if the specified immediate is legal 1530 /// add immediate, that is the target has add instructions which can add 1531 /// a register with the immediate without having to materialize the 1532 /// immediate into a register. 1533 virtual bool isLegalAddImmediate(int64_t Imm) const { 1534 return true; 1535 } 1536 1537 //===--------------------------------------------------------------------===// 1538 // Div utility functions 1539 // 1540 SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl, 1541 SelectionDAG &DAG) const; 1542 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, 1543 std::vector<SDNode*>* Created) const; 1544 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, 1545 std::vector<SDNode*>* Created) const; 1546 1547 1548 //===--------------------------------------------------------------------===// 1549 // Runtime Library hooks 1550 // 1551 1552 /// setLibcallName - Rename the default libcall routine name for the specified 1553 /// libcall. 1554 void setLibcallName(RTLIB::Libcall Call, const char *Name) { 1555 LibcallRoutineNames[Call] = Name; 1556 } 1557 1558 /// getLibcallName - Get the libcall routine name for the specified libcall. 1559 /// 1560 const char *getLibcallName(RTLIB::Libcall Call) const { 1561 return LibcallRoutineNames[Call]; 1562 } 1563 1564 /// setCmpLibcallCC - Override the default CondCode to be used to test the 1565 /// result of the comparison libcall against zero. 1566 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) { 1567 CmpLibcallCCs[Call] = CC; 1568 } 1569 1570 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of 1571 /// the comparison libcall against zero. 1572 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const { 1573 return CmpLibcallCCs[Call]; 1574 } 1575 1576 /// setLibcallCallingConv - Set the CallingConv that should be used for the 1577 /// specified libcall. 1578 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) { 1579 LibcallCallingConvs[Call] = CC; 1580 } 1581 1582 /// getLibcallCallingConv - Get the CallingConv that should be used for the 1583 /// specified libcall. 1584 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const { 1585 return LibcallCallingConvs[Call]; 1586 } 1587 1588 private: 1589 const TargetMachine &TM; 1590 const TargetData *TD; 1591 const TargetLoweringObjectFile &TLOF; 1592 1593 /// We are in the process of implementing a new TypeLegalization action 1594 /// which is the promotion of vector elements. This feature is under 1595 /// development. Until this feature is complete, it is only enabled using a 1596 /// flag. We pass this flag using a member because of circular dep issues. 1597 /// This member will be removed with the flag once we complete the transition. 1598 bool mayPromoteElements; 1599 1600 /// PointerTy - The type to use for pointers, usually i32 or i64. 1601 /// 1602 MVT PointerTy; 1603 1604 /// IsLittleEndian - True if this is a little endian target. 1605 /// 1606 bool IsLittleEndian; 1607 1608 /// SelectIsExpensive - Tells the code generator not to expand operations 1609 /// into sequences that use the select operations if possible. 1610 bool SelectIsExpensive; 1611 1612 /// IntDivIsCheap - Tells the code generator not to expand integer divides by 1613 /// constants into a sequence of muls, adds, and shifts. This is a hack until 1614 /// a real cost model is in place. If we ever optimize for size, this will be 1615 /// set to true unconditionally. 1616 bool IntDivIsCheap; 1617 1618 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate 1619 /// srl/add/sra for a signed divide by power of two, and let the target handle 1620 /// it. 1621 bool Pow2DivIsCheap; 1622 1623 /// JumpIsExpensive - Tells the code generator that it shouldn't generate 1624 /// extra flow control instructions and should attempt to combine flow 1625 /// control instructions via predication. 1626 bool JumpIsExpensive; 1627 1628 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement 1629 /// llvm.setjmp. Defaults to false. 1630 bool UseUnderscoreSetJmp; 1631 1632 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement 1633 /// llvm.longjmp. Defaults to false. 1634 bool UseUnderscoreLongJmp; 1635 1636 /// BooleanContents - Information about the contents of the high-bits in 1637 /// boolean values held in a type wider than i1. See getBooleanContents. 1638 BooleanContent BooleanContents; 1639 1640 /// SchedPreferenceInfo - The target scheduling preference: shortest possible 1641 /// total cycles or lowest register usage. 1642 Sched::Preference SchedPreferenceInfo; 1643 1644 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers 1645 unsigned JumpBufSize; 1646 1647 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf 1648 /// buffers 1649 unsigned JumpBufAlignment; 1650 1651 /// MinStackArgumentAlignment - The minimum alignment that any argument 1652 /// on the stack needs to have. 1653 /// 1654 unsigned MinStackArgumentAlignment; 1655 1656 /// MinFunctionAlignment - The minimum function alignment (used when 1657 /// optimizing for size, and to prevent explicitly provided alignment 1658 /// from leading to incorrect code). 1659 /// 1660 unsigned MinFunctionAlignment; 1661 1662 /// PrefFunctionAlignment - The preferred function alignment (used when 1663 /// alignment unspecified and optimizing for speed). 1664 /// 1665 unsigned PrefFunctionAlignment; 1666 1667 /// PrefLoopAlignment - The preferred loop alignment. 1668 /// 1669 unsigned PrefLoopAlignment; 1670 1671 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should 1672 /// be folded into the enclosed atomic intrinsic instruction by the 1673 /// combiner. 1674 bool ShouldFoldAtomicFences; 1675 1676 /// StackPointerRegisterToSaveRestore - If set to a physical register, this 1677 /// specifies the register that llvm.savestack/llvm.restorestack should save 1678 /// and restore. 1679 unsigned StackPointerRegisterToSaveRestore; 1680 1681 /// ExceptionPointerRegister - If set to a physical register, this specifies 1682 /// the register that receives the exception address on entry to a landing 1683 /// pad. 1684 unsigned ExceptionPointerRegister; 1685 1686 /// ExceptionSelectorRegister - If set to a physical register, this specifies 1687 /// the register that receives the exception typeid on entry to a landing 1688 /// pad. 1689 unsigned ExceptionSelectorRegister; 1690 1691 /// RegClassForVT - This indicates the default register class to use for 1692 /// each ValueType the target supports natively. 1693 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE]; 1694 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE]; 1695 EVT RegisterTypeForVT[MVT::LAST_VALUETYPE]; 1696 1697 /// RepRegClassForVT - This indicates the "representative" register class to 1698 /// use for each ValueType the target supports natively. This information is 1699 /// used by the scheduler to track register pressure. By default, the 1700 /// representative register class is the largest legal super-reg register 1701 /// class of the register class of the specified type. e.g. On x86, i8, i16, 1702 /// and i32's representative class would be GR32. 1703 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE]; 1704 1705 /// RepRegClassCostForVT - This indicates the "cost" of the "representative" 1706 /// register class for each ValueType. The cost is used by the scheduler to 1707 /// approximate register pressure. 1708 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE]; 1709 1710 /// TransformToType - For any value types we are promoting or expanding, this 1711 /// contains the value type that we are changing to. For Expanded types, this 1712 /// contains one step of the expand (e.g. i64 -> i32), even if there are 1713 /// multiple steps required (e.g. i64 -> i16). For types natively supported 1714 /// by the system, this holds the same type (e.g. i32 -> i32). 1715 EVT TransformToType[MVT::LAST_VALUETYPE]; 1716 1717 /// OpActions - For each operation and each value type, keep a LegalizeAction 1718 /// that indicates how instruction selection should deal with the operation. 1719 /// Most operations are Legal (aka, supported natively by the target), but 1720 /// operations that are not should be described. Note that operations on 1721 /// non-legal value types are not described here. 1722 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END]; 1723 1724 /// LoadExtActions - For each load extension type and each value type, 1725 /// keep a LegalizeAction that indicates how instruction selection should deal 1726 /// with a load of a specific value type and extension type. 1727 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE]; 1728 1729 /// TruncStoreActions - For each value type pair keep a LegalizeAction that 1730 /// indicates whether a truncating store of a specific value type and 1731 /// truncating type is legal. 1732 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE]; 1733 1734 /// IndexedModeActions - For each indexed mode and each value type, 1735 /// keep a pair of LegalizeAction that indicates how instruction 1736 /// selection should deal with the load / store. The first dimension is the 1737 /// value_type for the reference. The second dimension represents the various 1738 /// modes for load store. 1739 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE]; 1740 1741 /// CondCodeActions - For each condition code (ISD::CondCode) keep a 1742 /// LegalizeAction that indicates how instruction selection should 1743 /// deal with the condition code. 1744 uint64_t CondCodeActions[ISD::SETCC_INVALID]; 1745 1746 ValueTypeActionImpl ValueTypeActions; 1747 1748 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind; 1749 1750 LegalizeKind 1751 getTypeConversion(LLVMContext &Context, EVT VT) const { 1752 // If this is a simple type, use the ComputeRegisterProp mechanism. 1753 if (VT.isSimple()) { 1754 assert((unsigned)VT.getSimpleVT().SimpleTy < 1755 array_lengthof(TransformToType)); 1756 EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy]; 1757 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT()); 1758 1759 assert( 1760 (!(NVT.isSimple() && LA != TypeLegal) || 1761 ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger) 1762 && "Promote may not follow Expand or Promote"); 1763 1764 return LegalizeKind(LA, NVT); 1765 } 1766 1767 // Handle Extended Scalar Types. 1768 if (!VT.isVector()) { 1769 assert(VT.isInteger() && "Float types must be simple"); 1770 unsigned BitSize = VT.getSizeInBits(); 1771 // First promote to a power-of-two size, then expand if necessary. 1772 if (BitSize < 8 || !isPowerOf2_32(BitSize)) { 1773 EVT NVT = VT.getRoundIntegerType(Context); 1774 assert(NVT != VT && "Unable to round integer VT"); 1775 LegalizeKind NextStep = getTypeConversion(Context, NVT); 1776 // Avoid multi-step promotion. 1777 if (NextStep.first == TypePromoteInteger) return NextStep; 1778 // Return rounded integer type. 1779 return LegalizeKind(TypePromoteInteger, NVT); 1780 } 1781 1782 return LegalizeKind(TypeExpandInteger, 1783 EVT::getIntegerVT(Context, VT.getSizeInBits()/2)); 1784 } 1785 1786 // Handle vector types. 1787 unsigned NumElts = VT.getVectorNumElements(); 1788 EVT EltVT = VT.getVectorElementType(); 1789 1790 // Vectors with only one element are always scalarized. 1791 if (NumElts == 1) 1792 return LegalizeKind(TypeScalarizeVector, EltVT); 1793 1794 // If we allow the promotion of vector elements using a flag, 1795 // then try to widen vector elements until a legal type is found. 1796 if (mayPromoteElements && EltVT.isInteger()) { 1797 // Vectors with a number of elements that is not a power of two are always 1798 // widened, for example <3 x float> -> <4 x float>. 1799 if (!VT.isPow2VectorType()) { 1800 NumElts = (unsigned)NextPowerOf2(NumElts); 1801 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts); 1802 return LegalizeKind(TypeWidenVector, NVT); 1803 } 1804 1805 // Examine the element type. 1806 LegalizeKind LK = getTypeConversion(Context, EltVT); 1807 1808 // If type is to be expanded, split the vector. 1809 // <4 x i140> -> <2 x i140> 1810 if (LK.first == TypeExpandInteger) 1811 return LegalizeKind(TypeSplitVector, 1812 EVT::getVectorVT(Context, EltVT, NumElts / 2)); 1813 1814 // Promote the integer element types until a legal vector type is found 1815 // or until the element integer type is too big. If a legal type was not 1816 // found, fallback to the usual mechanism of widening/splitting the 1817 // vector. 1818 while (1) { 1819 // Increase the bitwidth of the element to the next pow-of-two 1820 // (which is greater than 8 bits). 1821 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits() 1822 ).getRoundIntegerType(Context); 1823 1824 // Stop trying when getting a non-simple element type. 1825 // Note that vector elements may be greater than legal vector element 1826 // types. Example: X86 XMM registers hold 64bit element on 32bit systems. 1827 if (!EltVT.isSimple()) break; 1828 1829 // Build a new vector type and check if it is legal. 1830 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1831 // Found a legal promoted vector type. 1832 if (NVT != MVT() && ValueTypeActions.getTypeAction(NVT) == TypeLegal) 1833 return LegalizeKind(TypePromoteInteger, 1834 EVT::getVectorVT(Context, EltVT, NumElts)); 1835 } 1836 } 1837 1838 // Try to widen the vector until a legal type is found. 1839 // If there is no wider legal type, split the vector. 1840 while (1) { 1841 // Round up to the next power of 2. 1842 NumElts = (unsigned)NextPowerOf2(NumElts); 1843 1844 // If there is no simple vector type with this many elements then there 1845 // cannot be a larger legal vector type. Note that this assumes that 1846 // there are no skipped intermediate vector types in the simple types. 1847 if (!EltVT.isSimple()) break; 1848 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1849 if (LargerVector == MVT()) break; 1850 1851 // If this type is legal then widen the vector. 1852 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal) 1853 return LegalizeKind(TypeWidenVector, LargerVector); 1854 } 1855 1856 // Widen odd vectors to next power of two. 1857 if (!VT.isPow2VectorType()) { 1858 EVT NVT = VT.getPow2VectorType(Context); 1859 return LegalizeKind(TypeWidenVector, NVT); 1860 } 1861 1862 // Vectors with illegal element types are expanded. 1863 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2); 1864 return LegalizeKind(TypeSplitVector, NVT); 1865 1866 assert(false && "Unable to handle this kind of vector type"); 1867 return LegalizeKind(TypeLegal, VT); 1868 } 1869 1870 std::vector<std::pair<EVT, TargetRegisterClass*> > AvailableRegClasses; 1871 1872 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would 1873 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(), 1874 /// which sets a bit in this array. 1875 unsigned char 1876 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT]; 1877 1878 /// PromoteToType - For operations that must be promoted to a specific type, 1879 /// this holds the destination type. This map should be sparse, so don't hold 1880 /// it as an array. 1881 /// 1882 /// Targets add entries to this map with AddPromotedToType(..), clients access 1883 /// this with getTypeToPromoteTo(..). 1884 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType> 1885 PromoteToType; 1886 1887 /// LibcallRoutineNames - Stores the name each libcall. 1888 /// 1889 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL]; 1890 1891 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result 1892 /// of each of the comparison libcall against zero. 1893 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL]; 1894 1895 /// LibcallCallingConvs - Stores the CallingConv that should be used for each 1896 /// libcall. 1897 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL]; 1898 1899 protected: 1900 /// When lowering \@llvm.memset this field specifies the maximum number of 1901 /// store operations that may be substituted for the call to memset. Targets 1902 /// must set this value based on the cost threshold for that target. Targets 1903 /// should assume that the memset will be done using as many of the largest 1904 /// store operations first, followed by smaller ones, if necessary, per 1905 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine 1906 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte 1907 /// store. This only applies to setting a constant array of a constant size. 1908 /// @brief Specify maximum number of store instructions per memset call. 1909 unsigned maxStoresPerMemset; 1910 1911 /// Maximum number of stores operations that may be substituted for the call 1912 /// to memset, used for functions with OptSize attribute. 1913 unsigned maxStoresPerMemsetOptSize; 1914 1915 /// When lowering \@llvm.memcpy this field specifies the maximum number of 1916 /// store operations that may be substituted for a call to memcpy. Targets 1917 /// must set this value based on the cost threshold for that target. Targets 1918 /// should assume that the memcpy will be done using as many of the largest 1919 /// store operations first, followed by smaller ones, if necessary, per 1920 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine 1921 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store 1922 /// and one 1-byte store. This only applies to copying a constant array of 1923 /// constant size. 1924 /// @brief Specify maximum bytes of store instructions per memcpy call. 1925 unsigned maxStoresPerMemcpy; 1926 1927 /// Maximum number of store operations that may be substituted for a call 1928 /// to memcpy, used for functions with OptSize attribute. 1929 unsigned maxStoresPerMemcpyOptSize; 1930 1931 /// When lowering \@llvm.memmove this field specifies the maximum number of 1932 /// store instructions that may be substituted for a call to memmove. Targets 1933 /// must set this value based on the cost threshold for that target. Targets 1934 /// should assume that the memmove will be done using as many of the largest 1935 /// store operations first, followed by smaller ones, if necessary, per 1936 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine 1937 /// with 8-bit alignment would result in nine 1-byte stores. This only 1938 /// applies to copying a constant array of constant size. 1939 /// @brief Specify maximum bytes of store instructions per memmove call. 1940 unsigned maxStoresPerMemmove; 1941 1942 /// Maximum number of store instructions that may be substituted for a call 1943 /// to memmove, used for functions with OpSize attribute. 1944 unsigned maxStoresPerMemmoveOptSize; 1945 1946 /// This field specifies whether the target can benefit from code placement 1947 /// optimization. 1948 bool benefitFromCodePlacementOpt; 1949 1950 private: 1951 /// isLegalRC - Return true if the value types that can be represented by the 1952 /// specified register class are all legal. 1953 bool isLegalRC(const TargetRegisterClass *RC) const; 1954 1955 /// hasLegalSuperRegRegClasses - Return true if the specified register class 1956 /// has one or more super-reg register classes that are legal. 1957 bool hasLegalSuperRegRegClasses(const TargetRegisterClass *RC) const; 1958 }; 1959 1960 /// GetReturnInfo - Given an LLVM IR type and return type attributes, 1961 /// compute the return value EVTs and flags, and optionally also 1962 /// the offsets, if the return value is being lowered to memory. 1963 void GetReturnInfo(Type* ReturnType, Attributes attr, 1964 SmallVectorImpl<ISD::OutputArg> &Outs, 1965 const TargetLowering &TLI, 1966 SmallVectorImpl<uint64_t> *Offsets = 0); 1967 1968 } // end llvm namespace 1969 1970 #endif 1971