1 //===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the SelectionDAG::Legalize method. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/APFloat.h" 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/CodeGen/ISDOpcodes.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineJumpTableInfo.h" 23 #include "llvm/CodeGen/MachineMemOperand.h" 24 #include "llvm/CodeGen/RuntimeLibcalls.h" 25 #include "llvm/CodeGen/SelectionDAG.h" 26 #include "llvm/CodeGen/SelectionDAGNodes.h" 27 #include "llvm/CodeGen/TargetFrameLowering.h" 28 #include "llvm/CodeGen/TargetLowering.h" 29 #include "llvm/CodeGen/TargetSubtargetInfo.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/CallingConv.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/DerivedTypes.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/Metadata.h" 37 #include "llvm/IR/Type.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/Compiler.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/MachineValueType.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/raw_ostream.h" 45 #include "llvm/Target/TargetMachine.h" 46 #include "llvm/Target/TargetOptions.h" 47 #include <algorithm> 48 #include <cassert> 49 #include <cstdint> 50 #include <tuple> 51 #include <utility> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "legalizedag" 56 57 namespace { 58 59 /// Keeps track of state when getting the sign of a floating-point value as an 60 /// integer. 61 struct FloatSignAsInt { 62 EVT FloatVT; 63 SDValue Chain; 64 SDValue FloatPtr; 65 SDValue IntPtr; 66 MachinePointerInfo IntPointerInfo; 67 MachinePointerInfo FloatPointerInfo; 68 SDValue IntValue; 69 APInt SignMask; 70 uint8_t SignBit; 71 }; 72 73 //===----------------------------------------------------------------------===// 74 /// This takes an arbitrary SelectionDAG as input and 75 /// hacks on it until the target machine can handle it. This involves 76 /// eliminating value sizes the machine cannot handle (promoting small sizes to 77 /// large sizes or splitting up large values into small values) as well as 78 /// eliminating operations the machine cannot handle. 79 /// 80 /// This code also does a small amount of optimization and recognition of idioms 81 /// as part of its processing. For example, if a target does not support a 82 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this 83 /// will attempt merge setcc and brc instructions into brcc's. 84 class SelectionDAGLegalize { 85 const TargetMachine &TM; 86 const TargetLowering &TLI; 87 SelectionDAG &DAG; 88 89 /// The set of nodes which have already been legalized. We hold a 90 /// reference to it in order to update as necessary on node deletion. 91 SmallPtrSetImpl<SDNode *> &LegalizedNodes; 92 93 /// A set of all the nodes updated during legalization. 94 SmallSetVector<SDNode *, 16> *UpdatedNodes; 95 96 EVT getSetCCResultType(EVT VT) const { 97 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 98 } 99 100 // Libcall insertion helpers. 101 102 public: 103 SelectionDAGLegalize(SelectionDAG &DAG, 104 SmallPtrSetImpl<SDNode *> &LegalizedNodes, 105 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr) 106 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG), 107 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {} 108 109 /// Legalizes the given operation. 110 void LegalizeOp(SDNode *Node); 111 112 private: 113 SDValue OptimizeFloatStore(StoreSDNode *ST); 114 115 void LegalizeLoadOps(SDNode *Node); 116 void LegalizeStoreOps(SDNode *Node); 117 118 /// Some targets cannot handle a variable 119 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it 120 /// is necessary to spill the vector being inserted into to memory, perform 121 /// the insert there, and then read the result back. 122 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx, 123 const SDLoc &dl); 124 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, 125 const SDLoc &dl); 126 127 /// Return a vector shuffle operation which 128 /// performs the same shuffe in terms of order or result bytes, but on a type 129 /// whose vector element type is narrower than the original shuffle type. 130 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 131 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl, 132 SDValue N1, SDValue N2, 133 ArrayRef<int> Mask) const; 134 135 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, 136 bool &NeedInvert, const SDLoc &dl); 137 138 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned); 139 SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops, 140 unsigned NumOps, bool isSigned, const SDLoc &dl); 141 142 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC, 143 SDNode *Node, bool isSigned); 144 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32, 145 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80, 146 RTLIB::Libcall Call_F128, 147 RTLIB::Libcall Call_PPCF128); 148 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, 149 RTLIB::Libcall Call_I8, 150 RTLIB::Libcall Call_I16, 151 RTLIB::Libcall Call_I32, 152 RTLIB::Libcall Call_I64, 153 RTLIB::Libcall Call_I128); 154 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 155 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 156 157 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, 158 const SDLoc &dl); 159 SDValue ExpandBUILD_VECTOR(SDNode *Node); 160 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node); 161 void ExpandDYNAMIC_STACKALLOC(SDNode *Node, 162 SmallVectorImpl<SDValue> &Results); 163 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL, 164 SDValue Value) const; 165 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL, 166 SDValue NewIntValue) const; 167 SDValue ExpandFCOPYSIGN(SDNode *Node) const; 168 SDValue ExpandFABS(SDNode *Node) const; 169 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0, EVT DestVT, 170 const SDLoc &dl); 171 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned, 172 const SDLoc &dl); 173 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned, 174 const SDLoc &dl); 175 176 SDValue ExpandBITREVERSE(SDValue Op, const SDLoc &dl); 177 SDValue ExpandBSWAP(SDValue Op, const SDLoc &dl); 178 179 SDValue ExpandExtractFromVectorThroughStack(SDValue Op); 180 SDValue ExpandInsertToVectorThroughStack(SDValue Op); 181 SDValue ExpandVectorBuildThroughStack(SDNode* Node); 182 183 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP); 184 SDValue ExpandConstant(ConstantSDNode *CP); 185 186 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall 187 bool ExpandNode(SDNode *Node); 188 void ConvertNodeToLibcall(SDNode *Node); 189 void PromoteNode(SDNode *Node); 190 191 public: 192 // Node replacement helpers 193 194 void ReplacedNode(SDNode *N) { 195 LegalizedNodes.erase(N); 196 if (UpdatedNodes) 197 UpdatedNodes->insert(N); 198 } 199 200 void ReplaceNode(SDNode *Old, SDNode *New) { 201 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 202 dbgs() << " with: "; New->dump(&DAG)); 203 204 assert(Old->getNumValues() == New->getNumValues() && 205 "Replacing one node with another that produces a different number " 206 "of values!"); 207 DAG.ReplaceAllUsesWith(Old, New); 208 if (UpdatedNodes) 209 UpdatedNodes->insert(New); 210 ReplacedNode(Old); 211 } 212 213 void ReplaceNode(SDValue Old, SDValue New) { 214 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 215 dbgs() << " with: "; New->dump(&DAG)); 216 217 DAG.ReplaceAllUsesWith(Old, New); 218 if (UpdatedNodes) 219 UpdatedNodes->insert(New.getNode()); 220 ReplacedNode(Old.getNode()); 221 } 222 223 void ReplaceNode(SDNode *Old, const SDValue *New) { 224 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG)); 225 226 DAG.ReplaceAllUsesWith(Old, New); 227 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) { 228 LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: "); 229 New[i]->dump(&DAG)); 230 if (UpdatedNodes) 231 UpdatedNodes->insert(New[i].getNode()); 232 } 233 ReplacedNode(Old); 234 } 235 }; 236 237 } // end anonymous namespace 238 239 /// Return a vector shuffle operation which 240 /// performs the same shuffle in terms of order or result bytes, but on a type 241 /// whose vector element type is narrower than the original shuffle type. 242 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 243 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType( 244 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, 245 ArrayRef<int> Mask) const { 246 unsigned NumMaskElts = VT.getVectorNumElements(); 247 unsigned NumDestElts = NVT.getVectorNumElements(); 248 unsigned NumEltsGrowth = NumDestElts / NumMaskElts; 249 250 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!"); 251 252 if (NumEltsGrowth == 1) 253 return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask); 254 255 SmallVector<int, 8> NewMask; 256 for (unsigned i = 0; i != NumMaskElts; ++i) { 257 int Idx = Mask[i]; 258 for (unsigned j = 0; j != NumEltsGrowth; ++j) { 259 if (Idx < 0) 260 NewMask.push_back(-1); 261 else 262 NewMask.push_back(Idx * NumEltsGrowth + j); 263 } 264 } 265 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?"); 266 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?"); 267 return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask); 268 } 269 270 /// Expands the ConstantFP node to an integer constant or 271 /// a load from the constant pool. 272 SDValue 273 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) { 274 bool Extend = false; 275 SDLoc dl(CFP); 276 277 // If a FP immediate is precise when represented as a float and if the 278 // target can do an extending load from float to double, we put it into 279 // the constant pool as a float, even if it's is statically typed as a 280 // double. This shrinks FP constants and canonicalizes them for targets where 281 // an FP extending load is the same cost as a normal load (such as on the x87 282 // fp stack or PPC FP unit). 283 EVT VT = CFP->getValueType(0); 284 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue()); 285 if (!UseCP) { 286 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion"); 287 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl, 288 (VT == MVT::f64) ? MVT::i64 : MVT::i32); 289 } 290 291 APFloat APF = CFP->getValueAPF(); 292 EVT OrigVT = VT; 293 EVT SVT = VT; 294 295 // We don't want to shrink SNaNs. Converting the SNaN back to its real type 296 // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ). 297 if (!APF.isSignaling()) { 298 while (SVT != MVT::f32 && SVT != MVT::f16) { 299 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1); 300 if (ConstantFPSDNode::isValueValidForType(SVT, APF) && 301 // Only do this if the target has a native EXTLOAD instruction from 302 // smaller type. 303 TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) && 304 TLI.ShouldShrinkFPConstant(OrigVT)) { 305 Type *SType = SVT.getTypeForEVT(*DAG.getContext()); 306 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType)); 307 VT = SVT; 308 Extend = true; 309 } 310 } 311 } 312 313 SDValue CPIdx = 314 DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout())); 315 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 316 if (Extend) { 317 SDValue Result = DAG.getExtLoad( 318 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx, 319 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT, 320 Alignment); 321 return Result; 322 } 323 SDValue Result = DAG.getLoad( 324 OrigVT, dl, DAG.getEntryNode(), CPIdx, 325 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment); 326 return Result; 327 } 328 329 /// Expands the Constant node to a load from the constant pool. 330 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) { 331 SDLoc dl(CP); 332 EVT VT = CP->getValueType(0); 333 SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(), 334 TLI.getPointerTy(DAG.getDataLayout())); 335 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 336 SDValue Result = DAG.getLoad( 337 VT, dl, DAG.getEntryNode(), CPIdx, 338 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment); 339 return Result; 340 } 341 342 /// Some target cannot handle a variable insertion index for the 343 /// INSERT_VECTOR_ELT instruction. In this case, it 344 /// is necessary to spill the vector being inserted into to memory, perform 345 /// the insert there, and then read the result back. 346 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec, 347 SDValue Val, 348 SDValue Idx, 349 const SDLoc &dl) { 350 SDValue Tmp1 = Vec; 351 SDValue Tmp2 = Val; 352 SDValue Tmp3 = Idx; 353 354 // If the target doesn't support this, we have to spill the input vector 355 // to a temporary stack slot, update the element, then reload it. This is 356 // badness. We could also load the value into a vector register (either 357 // with a "move to register" or "extload into register" instruction, then 358 // permute it into place, if the idx is a constant and if the idx is 359 // supported by the target. 360 EVT VT = Tmp1.getValueType(); 361 EVT EltVT = VT.getVectorElementType(); 362 SDValue StackPtr = DAG.CreateStackTemporary(VT); 363 364 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 365 366 // Store the vector. 367 SDValue Ch = DAG.getStore( 368 DAG.getEntryNode(), dl, Tmp1, StackPtr, 369 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI)); 370 371 SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3); 372 373 // Store the scalar value. 374 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT); 375 // Load the updated vector. 376 return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack( 377 DAG.getMachineFunction(), SPFI)); 378 } 379 380 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, 381 SDValue Idx, 382 const SDLoc &dl) { 383 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) { 384 // SCALAR_TO_VECTOR requires that the type of the value being inserted 385 // match the element type of the vector being created, except for 386 // integers in which case the inserted value can be over width. 387 EVT EltVT = Vec.getValueType().getVectorElementType(); 388 if (Val.getValueType() == EltVT || 389 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) { 390 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 391 Vec.getValueType(), Val); 392 393 unsigned NumElts = Vec.getValueType().getVectorNumElements(); 394 // We generate a shuffle of InVec and ScVec, so the shuffle mask 395 // should be 0,1,2,3,4,5... with the appropriate element replaced with 396 // elt 0 of the RHS. 397 SmallVector<int, 8> ShufOps; 398 for (unsigned i = 0; i != NumElts; ++i) 399 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts); 400 401 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps); 402 } 403 } 404 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl); 405 } 406 407 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) { 408 LLVM_DEBUG(dbgs() << "Optimizing float store operations\n"); 409 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 410 // FIXME: We shouldn't do this for TargetConstantFP's. 411 // FIXME: move this to the DAG Combiner! Note that we can't regress due 412 // to phase ordering between legalized code and the dag combiner. This 413 // probably means that we need to integrate dag combiner and legalizer 414 // together. 415 // We generally can't do this one for long doubles. 416 SDValue Chain = ST->getChain(); 417 SDValue Ptr = ST->getBasePtr(); 418 unsigned Alignment = ST->getAlignment(); 419 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 420 AAMDNodes AAInfo = ST->getAAInfo(); 421 SDLoc dl(ST); 422 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) { 423 if (CFP->getValueType(0) == MVT::f32 && 424 TLI.isTypeLegal(MVT::i32)) { 425 SDValue Con = DAG.getConstant(CFP->getValueAPF(). 426 bitcastToAPInt().zextOrTrunc(32), 427 SDLoc(CFP), MVT::i32); 428 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), Alignment, 429 MMOFlags, AAInfo); 430 } 431 432 if (CFP->getValueType(0) == MVT::f64) { 433 // If this target supports 64-bit registers, do a single 64-bit store. 434 if (TLI.isTypeLegal(MVT::i64)) { 435 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 436 zextOrTrunc(64), SDLoc(CFP), MVT::i64); 437 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), 438 Alignment, MMOFlags, AAInfo); 439 } 440 441 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) { 442 // Otherwise, if the target supports 32-bit registers, use 2 32-bit 443 // stores. If the target supports neither 32- nor 64-bits, this 444 // xform is certainly not worth it. 445 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt(); 446 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32); 447 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32); 448 if (DAG.getDataLayout().isBigEndian()) 449 std::swap(Lo, Hi); 450 451 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), Alignment, 452 MMOFlags, AAInfo); 453 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 454 DAG.getConstant(4, dl, Ptr.getValueType())); 455 Hi = DAG.getStore(Chain, dl, Hi, Ptr, 456 ST->getPointerInfo().getWithOffset(4), 457 MinAlign(Alignment, 4U), MMOFlags, AAInfo); 458 459 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 460 } 461 } 462 } 463 return SDValue(nullptr, 0); 464 } 465 466 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) { 467 StoreSDNode *ST = cast<StoreSDNode>(Node); 468 SDValue Chain = ST->getChain(); 469 SDValue Ptr = ST->getBasePtr(); 470 SDLoc dl(Node); 471 472 unsigned Alignment = ST->getAlignment(); 473 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 474 AAMDNodes AAInfo = ST->getAAInfo(); 475 476 if (!ST->isTruncatingStore()) { 477 LLVM_DEBUG(dbgs() << "Legalizing store operation\n"); 478 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) { 479 ReplaceNode(ST, OptStore); 480 return; 481 } 482 483 SDValue Value = ST->getValue(); 484 MVT VT = Value.getSimpleValueType(); 485 switch (TLI.getOperationAction(ISD::STORE, VT)) { 486 default: llvm_unreachable("This action is not supported yet!"); 487 case TargetLowering::Legal: { 488 // If this is an unaligned store and the target doesn't support it, 489 // expand it. 490 EVT MemVT = ST->getMemoryVT(); 491 unsigned AS = ST->getAddressSpace(); 492 unsigned Align = ST->getAlignment(); 493 const DataLayout &DL = DAG.getDataLayout(); 494 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 495 LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n"); 496 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 497 ReplaceNode(SDValue(ST, 0), Result); 498 } else 499 LLVM_DEBUG(dbgs() << "Legal store\n"); 500 break; 501 } 502 case TargetLowering::Custom: { 503 LLVM_DEBUG(dbgs() << "Trying custom lowering\n"); 504 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 505 if (Res && Res != SDValue(Node, 0)) 506 ReplaceNode(SDValue(Node, 0), Res); 507 return; 508 } 509 case TargetLowering::Promote: { 510 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT); 511 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 512 "Can only promote stores to same size type"); 513 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value); 514 SDValue Result = 515 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 516 Alignment, MMOFlags, AAInfo); 517 ReplaceNode(SDValue(Node, 0), Result); 518 break; 519 } 520 } 521 return; 522 } 523 524 LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n"); 525 SDValue Value = ST->getValue(); 526 EVT StVT = ST->getMemoryVT(); 527 unsigned StWidth = StVT.getSizeInBits(); 528 auto &DL = DAG.getDataLayout(); 529 530 if (StWidth != StVT.getStoreSizeInBits()) { 531 // Promote to a byte-sized store with upper bits zero if not 532 // storing an integral number of bytes. For example, promote 533 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1) 534 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), 535 StVT.getStoreSizeInBits()); 536 Value = DAG.getZeroExtendInReg(Value, dl, StVT); 537 SDValue Result = 538 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT, 539 Alignment, MMOFlags, AAInfo); 540 ReplaceNode(SDValue(Node, 0), Result); 541 } else if (StWidth & (StWidth - 1)) { 542 // If not storing a power-of-2 number of bits, expand as two stores. 543 assert(!StVT.isVector() && "Unsupported truncstore!"); 544 unsigned RoundWidth = 1 << Log2_32(StWidth); 545 assert(RoundWidth < StWidth); 546 unsigned ExtraWidth = StWidth - RoundWidth; 547 assert(ExtraWidth < RoundWidth); 548 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 549 "Store size not an integral number of bytes!"); 550 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 551 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 552 SDValue Lo, Hi; 553 unsigned IncrementSize; 554 555 if (DL.isLittleEndian()) { 556 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16) 557 // Store the bottom RoundWidth bits. 558 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 559 RoundVT, Alignment, MMOFlags, AAInfo); 560 561 // Store the remaining ExtraWidth bits. 562 IncrementSize = RoundWidth / 8; 563 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 564 DAG.getConstant(IncrementSize, dl, 565 Ptr.getValueType())); 566 Hi = DAG.getNode( 567 ISD::SRL, dl, Value.getValueType(), Value, 568 DAG.getConstant(RoundWidth, dl, 569 TLI.getShiftAmountTy(Value.getValueType(), DL))); 570 Hi = DAG.getTruncStore( 571 Chain, dl, Hi, Ptr, 572 ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT, 573 MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo); 574 } else { 575 // Big endian - avoid unaligned stores. 576 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X 577 // Store the top RoundWidth bits. 578 Hi = DAG.getNode( 579 ISD::SRL, dl, Value.getValueType(), Value, 580 DAG.getConstant(ExtraWidth, dl, 581 TLI.getShiftAmountTy(Value.getValueType(), DL))); 582 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), 583 RoundVT, Alignment, MMOFlags, AAInfo); 584 585 // Store the remaining ExtraWidth bits. 586 IncrementSize = RoundWidth / 8; 587 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 588 DAG.getConstant(IncrementSize, dl, 589 Ptr.getValueType())); 590 Lo = DAG.getTruncStore( 591 Chain, dl, Value, Ptr, 592 ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT, 593 MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo); 594 } 595 596 // The order of the stores doesn't matter. 597 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 598 ReplaceNode(SDValue(Node, 0), Result); 599 } else { 600 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) { 601 default: llvm_unreachable("This action is not supported yet!"); 602 case TargetLowering::Legal: { 603 EVT MemVT = ST->getMemoryVT(); 604 unsigned AS = ST->getAddressSpace(); 605 unsigned Align = ST->getAlignment(); 606 // If this is an unaligned store and the target doesn't support it, 607 // expand it. 608 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 609 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 610 ReplaceNode(SDValue(ST, 0), Result); 611 } 612 break; 613 } 614 case TargetLowering::Custom: { 615 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 616 if (Res && Res != SDValue(Node, 0)) 617 ReplaceNode(SDValue(Node, 0), Res); 618 return; 619 } 620 case TargetLowering::Expand: 621 assert(!StVT.isVector() && 622 "Vector Stores are handled in LegalizeVectorOps"); 623 624 SDValue Result; 625 626 // TRUNCSTORE:i16 i32 -> STORE i16 627 if (TLI.isTypeLegal(StVT)) { 628 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value); 629 Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 630 Alignment, MMOFlags, AAInfo); 631 } else { 632 // The in-memory type isn't legal. Truncate to the type it would promote 633 // to, and then do a truncstore. 634 Value = DAG.getNode(ISD::TRUNCATE, dl, 635 TLI.getTypeToTransformTo(*DAG.getContext(), StVT), 636 Value); 637 Result = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 638 StVT, Alignment, MMOFlags, AAInfo); 639 } 640 641 ReplaceNode(SDValue(Node, 0), Result); 642 break; 643 } 644 } 645 } 646 647 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) { 648 LoadSDNode *LD = cast<LoadSDNode>(Node); 649 SDValue Chain = LD->getChain(); // The chain. 650 SDValue Ptr = LD->getBasePtr(); // The base pointer. 651 SDValue Value; // The value returned by the load op. 652 SDLoc dl(Node); 653 654 ISD::LoadExtType ExtType = LD->getExtensionType(); 655 if (ExtType == ISD::NON_EXTLOAD) { 656 LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n"); 657 MVT VT = Node->getSimpleValueType(0); 658 SDValue RVal = SDValue(Node, 0); 659 SDValue RChain = SDValue(Node, 1); 660 661 switch (TLI.getOperationAction(Node->getOpcode(), VT)) { 662 default: llvm_unreachable("This action is not supported yet!"); 663 case TargetLowering::Legal: { 664 EVT MemVT = LD->getMemoryVT(); 665 unsigned AS = LD->getAddressSpace(); 666 unsigned Align = LD->getAlignment(); 667 const DataLayout &DL = DAG.getDataLayout(); 668 // If this is an unaligned load and the target doesn't support it, 669 // expand it. 670 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 671 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG); 672 } 673 break; 674 } 675 case TargetLowering::Custom: 676 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) { 677 RVal = Res; 678 RChain = Res.getValue(1); 679 } 680 break; 681 682 case TargetLowering::Promote: { 683 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT); 684 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 685 "Can only promote loads to same size type"); 686 687 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand()); 688 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res); 689 RChain = Res.getValue(1); 690 break; 691 } 692 } 693 if (RChain.getNode() != Node) { 694 assert(RVal.getNode() != Node && "Load must be completely replaced"); 695 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal); 696 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain); 697 if (UpdatedNodes) { 698 UpdatedNodes->insert(RVal.getNode()); 699 UpdatedNodes->insert(RChain.getNode()); 700 } 701 ReplacedNode(Node); 702 } 703 return; 704 } 705 706 LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n"); 707 EVT SrcVT = LD->getMemoryVT(); 708 unsigned SrcWidth = SrcVT.getSizeInBits(); 709 unsigned Alignment = LD->getAlignment(); 710 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 711 AAMDNodes AAInfo = LD->getAAInfo(); 712 713 if (SrcWidth != SrcVT.getStoreSizeInBits() && 714 // Some targets pretend to have an i1 loading operation, and actually 715 // load an i8. This trick is correct for ZEXTLOAD because the top 7 716 // bits are guaranteed to be zero; it helps the optimizers understand 717 // that these bits are zero. It is also useful for EXTLOAD, since it 718 // tells the optimizers that those bits are undefined. It would be 719 // nice to have an effective generic way of getting these benefits... 720 // Until such a way is found, don't insist on promoting i1 here. 721 (SrcVT != MVT::i1 || 722 TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) == 723 TargetLowering::Promote)) { 724 // Promote to a byte-sized load if not loading an integral number of 725 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24. 726 unsigned NewWidth = SrcVT.getStoreSizeInBits(); 727 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth); 728 SDValue Ch; 729 730 // The extra bits are guaranteed to be zero, since we stored them that 731 // way. A zext load from NVT thus automatically gives zext from SrcVT. 732 733 ISD::LoadExtType NewExtType = 734 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD; 735 736 SDValue Result = 737 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0), Chain, Ptr, 738 LD->getPointerInfo(), NVT, Alignment, MMOFlags, AAInfo); 739 740 Ch = Result.getValue(1); // The chain. 741 742 if (ExtType == ISD::SEXTLOAD) 743 // Having the top bits zero doesn't help when sign extending. 744 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 745 Result.getValueType(), 746 Result, DAG.getValueType(SrcVT)); 747 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType()) 748 // All the top bits are guaranteed to be zero - inform the optimizers. 749 Result = DAG.getNode(ISD::AssertZext, dl, 750 Result.getValueType(), Result, 751 DAG.getValueType(SrcVT)); 752 753 Value = Result; 754 Chain = Ch; 755 } else if (SrcWidth & (SrcWidth - 1)) { 756 // If not loading a power-of-2 number of bits, expand as two loads. 757 assert(!SrcVT.isVector() && "Unsupported extload!"); 758 unsigned RoundWidth = 1 << Log2_32(SrcWidth); 759 assert(RoundWidth < SrcWidth); 760 unsigned ExtraWidth = SrcWidth - RoundWidth; 761 assert(ExtraWidth < RoundWidth); 762 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 763 "Load size not an integral number of bytes!"); 764 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 765 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 766 SDValue Lo, Hi, Ch; 767 unsigned IncrementSize; 768 auto &DL = DAG.getDataLayout(); 769 770 if (DL.isLittleEndian()) { 771 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16) 772 // Load the bottom RoundWidth bits. 773 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr, 774 LD->getPointerInfo(), RoundVT, Alignment, MMOFlags, 775 AAInfo); 776 777 // Load the remaining ExtraWidth bits. 778 IncrementSize = RoundWidth / 8; 779 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 780 DAG.getConstant(IncrementSize, dl, 781 Ptr.getValueType())); 782 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 783 LD->getPointerInfo().getWithOffset(IncrementSize), 784 ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags, 785 AAInfo); 786 787 // Build a factor node to remember that this load is independent of 788 // the other one. 789 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 790 Hi.getValue(1)); 791 792 // Move the top bits to the right place. 793 Hi = DAG.getNode( 794 ISD::SHL, dl, Hi.getValueType(), Hi, 795 DAG.getConstant(RoundWidth, dl, 796 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 797 798 // Join the hi and lo parts. 799 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 800 } else { 801 // Big endian - avoid unaligned loads. 802 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8 803 // Load the top RoundWidth bits. 804 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 805 LD->getPointerInfo(), RoundVT, Alignment, MMOFlags, 806 AAInfo); 807 808 // Load the remaining ExtraWidth bits. 809 IncrementSize = RoundWidth / 8; 810 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 811 DAG.getConstant(IncrementSize, dl, 812 Ptr.getValueType())); 813 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr, 814 LD->getPointerInfo().getWithOffset(IncrementSize), 815 ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags, 816 AAInfo); 817 818 // Build a factor node to remember that this load is independent of 819 // the other one. 820 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 821 Hi.getValue(1)); 822 823 // Move the top bits to the right place. 824 Hi = DAG.getNode( 825 ISD::SHL, dl, Hi.getValueType(), Hi, 826 DAG.getConstant(ExtraWidth, dl, 827 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 828 829 // Join the hi and lo parts. 830 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 831 } 832 833 Chain = Ch; 834 } else { 835 bool isCustom = false; 836 switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0), 837 SrcVT.getSimpleVT())) { 838 default: llvm_unreachable("This action is not supported yet!"); 839 case TargetLowering::Custom: 840 isCustom = true; 841 LLVM_FALLTHROUGH; 842 case TargetLowering::Legal: 843 Value = SDValue(Node, 0); 844 Chain = SDValue(Node, 1); 845 846 if (isCustom) { 847 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 848 Value = Res; 849 Chain = Res.getValue(1); 850 } 851 } else { 852 // If this is an unaligned load and the target doesn't support it, 853 // expand it. 854 EVT MemVT = LD->getMemoryVT(); 855 unsigned AS = LD->getAddressSpace(); 856 unsigned Align = LD->getAlignment(); 857 const DataLayout &DL = DAG.getDataLayout(); 858 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 859 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG); 860 } 861 } 862 break; 863 864 case TargetLowering::Expand: { 865 EVT DestVT = Node->getValueType(0); 866 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) { 867 // If the source type is not legal, see if there is a legal extload to 868 // an intermediate type that we can then extend further. 869 EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT()); 870 if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT? 871 TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) { 872 // If we are loading a legal type, this is a non-extload followed by a 873 // full extend. 874 ISD::LoadExtType MidExtType = 875 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType; 876 877 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr, 878 SrcVT, LD->getMemOperand()); 879 unsigned ExtendOp = 880 ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType); 881 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load); 882 Chain = Load.getValue(1); 883 break; 884 } 885 886 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the 887 // normal undefined upper bits behavior to allow using an in-reg extend 888 // with the illegal FP type, so load as an integer and do the 889 // from-integer conversion. 890 if (SrcVT.getScalarType() == MVT::f16) { 891 EVT ISrcVT = SrcVT.changeTypeToInteger(); 892 EVT IDestVT = DestVT.changeTypeToInteger(); 893 EVT LoadVT = TLI.getRegisterType(IDestVT.getSimpleVT()); 894 895 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, LoadVT, 896 Chain, Ptr, ISrcVT, 897 LD->getMemOperand()); 898 Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result); 899 Chain = Result.getValue(1); 900 break; 901 } 902 } 903 904 assert(!SrcVT.isVector() && 905 "Vector Loads are handled in LegalizeVectorOps"); 906 907 // FIXME: This does not work for vectors on most targets. Sign- 908 // and zero-extend operations are currently folded into extending 909 // loads, whether they are legal or not, and then we end up here 910 // without any support for legalizing them. 911 assert(ExtType != ISD::EXTLOAD && 912 "EXTLOAD should always be supported!"); 913 // Turn the unsupported load into an EXTLOAD followed by an 914 // explicit zero/sign extend inreg. 915 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl, 916 Node->getValueType(0), 917 Chain, Ptr, SrcVT, 918 LD->getMemOperand()); 919 SDValue ValRes; 920 if (ExtType == ISD::SEXTLOAD) 921 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 922 Result.getValueType(), 923 Result, DAG.getValueType(SrcVT)); 924 else 925 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType()); 926 Value = ValRes; 927 Chain = Result.getValue(1); 928 break; 929 } 930 } 931 } 932 933 // Since loads produce two values, make sure to remember that we legalized 934 // both of them. 935 if (Chain.getNode() != Node) { 936 assert(Value.getNode() != Node && "Load must be completely replaced"); 937 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value); 938 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 939 if (UpdatedNodes) { 940 UpdatedNodes->insert(Value.getNode()); 941 UpdatedNodes->insert(Chain.getNode()); 942 } 943 ReplacedNode(Node); 944 } 945 } 946 947 /// Return a legal replacement for the given operation, with all legal operands. 948 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) { 949 LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG)); 950 951 // Allow illegal target nodes and illegal registers. 952 if (Node->getOpcode() == ISD::TargetConstant || 953 Node->getOpcode() == ISD::Register) 954 return; 955 956 #ifndef NDEBUG 957 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) 958 assert((TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) == 959 TargetLowering::TypeLegal || 960 TLI.isTypeLegal(Node->getValueType(i))) && 961 "Unexpected illegal type!"); 962 963 for (const SDValue &Op : Node->op_values()) 964 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) == 965 TargetLowering::TypeLegal || 966 TLI.isTypeLegal(Op.getValueType()) || 967 Op.getOpcode() == ISD::TargetConstant || 968 Op.getOpcode() == ISD::Register) && 969 "Unexpected illegal type!"); 970 #endif 971 972 // Figure out the correct action; the way to query this varies by opcode 973 TargetLowering::LegalizeAction Action = TargetLowering::Legal; 974 bool SimpleFinishLegalizing = true; 975 switch (Node->getOpcode()) { 976 case ISD::INTRINSIC_W_CHAIN: 977 case ISD::INTRINSIC_WO_CHAIN: 978 case ISD::INTRINSIC_VOID: 979 case ISD::STACKSAVE: 980 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 981 break; 982 case ISD::GET_DYNAMIC_AREA_OFFSET: 983 Action = TLI.getOperationAction(Node->getOpcode(), 984 Node->getValueType(0)); 985 break; 986 case ISD::VAARG: 987 Action = TLI.getOperationAction(Node->getOpcode(), 988 Node->getValueType(0)); 989 if (Action != TargetLowering::Promote) 990 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 991 break; 992 case ISD::FP_TO_FP16: 993 case ISD::SINT_TO_FP: 994 case ISD::UINT_TO_FP: 995 case ISD::EXTRACT_VECTOR_ELT: 996 Action = TLI.getOperationAction(Node->getOpcode(), 997 Node->getOperand(0).getValueType()); 998 break; 999 case ISD::FP_ROUND_INREG: 1000 case ISD::SIGN_EXTEND_INREG: { 1001 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT(); 1002 Action = TLI.getOperationAction(Node->getOpcode(), InnerType); 1003 break; 1004 } 1005 case ISD::ATOMIC_STORE: 1006 Action = TLI.getOperationAction(Node->getOpcode(), 1007 Node->getOperand(2).getValueType()); 1008 break; 1009 case ISD::SELECT_CC: 1010 case ISD::SETCC: 1011 case ISD::BR_CC: { 1012 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 : 1013 Node->getOpcode() == ISD::SETCC ? 2 : 1; 1014 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0; 1015 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType(); 1016 ISD::CondCode CCCode = 1017 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get(); 1018 Action = TLI.getCondCodeAction(CCCode, OpVT); 1019 if (Action == TargetLowering::Legal) { 1020 if (Node->getOpcode() == ISD::SELECT_CC) 1021 Action = TLI.getOperationAction(Node->getOpcode(), 1022 Node->getValueType(0)); 1023 else 1024 Action = TLI.getOperationAction(Node->getOpcode(), OpVT); 1025 } 1026 break; 1027 } 1028 case ISD::LOAD: 1029 case ISD::STORE: 1030 // FIXME: Model these properly. LOAD and STORE are complicated, and 1031 // STORE expects the unlegalized operand in some cases. 1032 SimpleFinishLegalizing = false; 1033 break; 1034 case ISD::CALLSEQ_START: 1035 case ISD::CALLSEQ_END: 1036 // FIXME: This shouldn't be necessary. These nodes have special properties 1037 // dealing with the recursive nature of legalization. Removing this 1038 // special case should be done as part of making LegalizeDAG non-recursive. 1039 SimpleFinishLegalizing = false; 1040 break; 1041 case ISD::EXTRACT_ELEMENT: 1042 case ISD::FLT_ROUNDS_: 1043 case ISD::MERGE_VALUES: 1044 case ISD::EH_RETURN: 1045 case ISD::FRAME_TO_ARGS_OFFSET: 1046 case ISD::EH_DWARF_CFA: 1047 case ISD::EH_SJLJ_SETJMP: 1048 case ISD::EH_SJLJ_LONGJMP: 1049 case ISD::EH_SJLJ_SETUP_DISPATCH: 1050 // These operations lie about being legal: when they claim to be legal, 1051 // they should actually be expanded. 1052 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1053 if (Action == TargetLowering::Legal) 1054 Action = TargetLowering::Expand; 1055 break; 1056 case ISD::INIT_TRAMPOLINE: 1057 case ISD::ADJUST_TRAMPOLINE: 1058 case ISD::FRAMEADDR: 1059 case ISD::RETURNADDR: 1060 case ISD::ADDROFRETURNADDR: 1061 case ISD::SPONENTRY: 1062 // These operations lie about being legal: when they claim to be legal, 1063 // they should actually be custom-lowered. 1064 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1065 if (Action == TargetLowering::Legal) 1066 Action = TargetLowering::Custom; 1067 break; 1068 case ISD::READCYCLECOUNTER: 1069 // READCYCLECOUNTER returns an i64, even if type legalization might have 1070 // expanded that to several smaller types. 1071 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64); 1072 break; 1073 case ISD::READ_REGISTER: 1074 case ISD::WRITE_REGISTER: 1075 // Named register is legal in the DAG, but blocked by register name 1076 // selection if not implemented by target (to chose the correct register) 1077 // They'll be converted to Copy(To/From)Reg. 1078 Action = TargetLowering::Legal; 1079 break; 1080 case ISD::DEBUGTRAP: 1081 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1082 if (Action == TargetLowering::Expand) { 1083 // replace ISD::DEBUGTRAP with ISD::TRAP 1084 SDValue NewVal; 1085 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(), 1086 Node->getOperand(0)); 1087 ReplaceNode(Node, NewVal.getNode()); 1088 LegalizeOp(NewVal.getNode()); 1089 return; 1090 } 1091 break; 1092 case ISD::STRICT_FADD: 1093 case ISD::STRICT_FSUB: 1094 case ISD::STRICT_FMUL: 1095 case ISD::STRICT_FDIV: 1096 case ISD::STRICT_FREM: 1097 case ISD::STRICT_FSQRT: 1098 case ISD::STRICT_FMA: 1099 case ISD::STRICT_FPOW: 1100 case ISD::STRICT_FPOWI: 1101 case ISD::STRICT_FSIN: 1102 case ISD::STRICT_FCOS: 1103 case ISD::STRICT_FEXP: 1104 case ISD::STRICT_FEXP2: 1105 case ISD::STRICT_FLOG: 1106 case ISD::STRICT_FLOG10: 1107 case ISD::STRICT_FLOG2: 1108 case ISD::STRICT_FRINT: 1109 case ISD::STRICT_FNEARBYINT: 1110 case ISD::STRICT_FMAXNUM: 1111 case ISD::STRICT_FMINNUM: 1112 case ISD::STRICT_FCEIL: 1113 case ISD::STRICT_FFLOOR: 1114 case ISD::STRICT_FROUND: 1115 case ISD::STRICT_FTRUNC: 1116 // These pseudo-ops get legalized as if they were their non-strict 1117 // equivalent. For instance, if ISD::FSQRT is legal then ISD::STRICT_FSQRT 1118 // is also legal, but if ISD::FSQRT requires expansion then so does 1119 // ISD::STRICT_FSQRT. 1120 Action = TLI.getStrictFPOperationAction(Node->getOpcode(), 1121 Node->getValueType(0)); 1122 break; 1123 case ISD::SADDSAT: 1124 case ISD::UADDSAT: 1125 case ISD::SSUBSAT: 1126 case ISD::USUBSAT: { 1127 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1128 break; 1129 } 1130 case ISD::SMULFIX: { 1131 unsigned Scale = Node->getConstantOperandVal(2); 1132 Action = TLI.getFixedPointOperationAction(Node->getOpcode(), 1133 Node->getValueType(0), Scale); 1134 break; 1135 } 1136 case ISD::MSCATTER: 1137 Action = TLI.getOperationAction(Node->getOpcode(), 1138 cast<MaskedScatterSDNode>(Node)->getValue().getValueType()); 1139 break; 1140 case ISD::MSTORE: 1141 Action = TLI.getOperationAction(Node->getOpcode(), 1142 cast<MaskedStoreSDNode>(Node)->getValue().getValueType()); 1143 break; 1144 default: 1145 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) { 1146 Action = TargetLowering::Legal; 1147 } else { 1148 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1149 } 1150 break; 1151 } 1152 1153 if (SimpleFinishLegalizing) { 1154 SDNode *NewNode = Node; 1155 switch (Node->getOpcode()) { 1156 default: break; 1157 case ISD::SHL: 1158 case ISD::SRL: 1159 case ISD::SRA: 1160 case ISD::ROTL: 1161 case ISD::ROTR: { 1162 // Legalizing shifts/rotates requires adjusting the shift amount 1163 // to the appropriate width. 1164 SDValue Op0 = Node->getOperand(0); 1165 SDValue Op1 = Node->getOperand(1); 1166 if (!Op1.getValueType().isVector()) { 1167 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1); 1168 // The getShiftAmountOperand() may create a new operand node or 1169 // return the existing one. If new operand is created we need 1170 // to update the parent node. 1171 // Do not try to legalize SAO here! It will be automatically legalized 1172 // in the next round. 1173 if (SAO != Op1) 1174 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO); 1175 } 1176 } 1177 break; 1178 case ISD::FSHL: 1179 case ISD::FSHR: 1180 case ISD::SRL_PARTS: 1181 case ISD::SRA_PARTS: 1182 case ISD::SHL_PARTS: { 1183 // Legalizing shifts/rotates requires adjusting the shift amount 1184 // to the appropriate width. 1185 SDValue Op0 = Node->getOperand(0); 1186 SDValue Op1 = Node->getOperand(1); 1187 SDValue Op2 = Node->getOperand(2); 1188 if (!Op2.getValueType().isVector()) { 1189 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2); 1190 // The getShiftAmountOperand() may create a new operand node or 1191 // return the existing one. If new operand is created we need 1192 // to update the parent node. 1193 if (SAO != Op2) 1194 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO); 1195 } 1196 break; 1197 } 1198 } 1199 1200 if (NewNode != Node) { 1201 ReplaceNode(Node, NewNode); 1202 Node = NewNode; 1203 } 1204 switch (Action) { 1205 case TargetLowering::Legal: 1206 LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n"); 1207 return; 1208 case TargetLowering::Custom: 1209 LLVM_DEBUG(dbgs() << "Trying custom legalization\n"); 1210 // FIXME: The handling for custom lowering with multiple results is 1211 // a complete mess. 1212 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 1213 if (!(Res.getNode() != Node || Res.getResNo() != 0)) 1214 return; 1215 1216 if (Node->getNumValues() == 1) { 1217 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n"); 1218 // We can just directly replace this node with the lowered value. 1219 ReplaceNode(SDValue(Node, 0), Res); 1220 return; 1221 } 1222 1223 SmallVector<SDValue, 8> ResultVals; 1224 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) 1225 ResultVals.push_back(Res.getValue(i)); 1226 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n"); 1227 ReplaceNode(Node, ResultVals.data()); 1228 return; 1229 } 1230 LLVM_DEBUG(dbgs() << "Could not custom legalize node\n"); 1231 LLVM_FALLTHROUGH; 1232 case TargetLowering::Expand: 1233 if (ExpandNode(Node)) 1234 return; 1235 LLVM_FALLTHROUGH; 1236 case TargetLowering::LibCall: 1237 ConvertNodeToLibcall(Node); 1238 return; 1239 case TargetLowering::Promote: 1240 PromoteNode(Node); 1241 return; 1242 } 1243 } 1244 1245 switch (Node->getOpcode()) { 1246 default: 1247 #ifndef NDEBUG 1248 dbgs() << "NODE: "; 1249 Node->dump( &DAG); 1250 dbgs() << "\n"; 1251 #endif 1252 llvm_unreachable("Do not know how to legalize this operator!"); 1253 1254 case ISD::CALLSEQ_START: 1255 case ISD::CALLSEQ_END: 1256 break; 1257 case ISD::LOAD: 1258 return LegalizeLoadOps(Node); 1259 case ISD::STORE: 1260 return LegalizeStoreOps(Node); 1261 } 1262 } 1263 1264 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) { 1265 SDValue Vec = Op.getOperand(0); 1266 SDValue Idx = Op.getOperand(1); 1267 SDLoc dl(Op); 1268 1269 // Before we generate a new store to a temporary stack slot, see if there is 1270 // already one that we can use. There often is because when we scalarize 1271 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole 1272 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in 1273 // the vector. If all are expanded here, we don't want one store per vector 1274 // element. 1275 1276 // Caches for hasPredecessorHelper 1277 SmallPtrSet<const SDNode *, 32> Visited; 1278 SmallVector<const SDNode *, 16> Worklist; 1279 Visited.insert(Op.getNode()); 1280 Worklist.push_back(Idx.getNode()); 1281 SDValue StackPtr, Ch; 1282 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(), 1283 UE = Vec.getNode()->use_end(); UI != UE; ++UI) { 1284 SDNode *User = *UI; 1285 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) { 1286 if (ST->isIndexed() || ST->isTruncatingStore() || 1287 ST->getValue() != Vec) 1288 continue; 1289 1290 // Make sure that nothing else could have stored into the destination of 1291 // this store. 1292 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode())) 1293 continue; 1294 1295 // If the index is dependent on the store we will introduce a cycle when 1296 // creating the load (the load uses the index, and by replacing the chain 1297 // we will make the index dependent on the load). Also, the store might be 1298 // dependent on the extractelement and introduce a cycle when creating 1299 // the load. 1300 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) || 1301 ST->hasPredecessor(Op.getNode())) 1302 continue; 1303 1304 StackPtr = ST->getBasePtr(); 1305 Ch = SDValue(ST, 0); 1306 break; 1307 } 1308 } 1309 1310 EVT VecVT = Vec.getValueType(); 1311 1312 if (!Ch.getNode()) { 1313 // Store the value to a temporary stack slot, then LOAD the returned part. 1314 StackPtr = DAG.CreateStackTemporary(VecVT); 1315 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, 1316 MachinePointerInfo()); 1317 } 1318 1319 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx); 1320 1321 SDValue NewLoad; 1322 1323 if (Op.getValueType().isVector()) 1324 NewLoad = 1325 DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo()); 1326 else 1327 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr, 1328 MachinePointerInfo(), 1329 VecVT.getVectorElementType()); 1330 1331 // Replace the chain going out of the store, by the one out of the load. 1332 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1)); 1333 1334 // We introduced a cycle though, so update the loads operands, making sure 1335 // to use the original store's chain as an incoming chain. 1336 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(), 1337 NewLoad->op_end()); 1338 NewLoadOperands[0] = Ch; 1339 NewLoad = 1340 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0); 1341 return NewLoad; 1342 } 1343 1344 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) { 1345 assert(Op.getValueType().isVector() && "Non-vector insert subvector!"); 1346 1347 SDValue Vec = Op.getOperand(0); 1348 SDValue Part = Op.getOperand(1); 1349 SDValue Idx = Op.getOperand(2); 1350 SDLoc dl(Op); 1351 1352 // Store the value to a temporary stack slot, then LOAD the returned part. 1353 EVT VecVT = Vec.getValueType(); 1354 SDValue StackPtr = DAG.CreateStackTemporary(VecVT); 1355 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1356 MachinePointerInfo PtrInfo = 1357 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1358 1359 // First store the whole vector. 1360 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo); 1361 1362 // Then store the inserted part. 1363 SDValue SubStackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx); 1364 1365 // Store the subvector. 1366 Ch = DAG.getStore(Ch, dl, Part, SubStackPtr, MachinePointerInfo()); 1367 1368 // Finally, load the updated vector. 1369 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo); 1370 } 1371 1372 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) { 1373 // We can't handle this case efficiently. Allocate a sufficiently 1374 // aligned object on the stack, store each element into it, then load 1375 // the result as a vector. 1376 // Create the stack frame object. 1377 EVT VT = Node->getValueType(0); 1378 EVT EltVT = VT.getVectorElementType(); 1379 SDLoc dl(Node); 1380 SDValue FIPtr = DAG.CreateStackTemporary(VT); 1381 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex(); 1382 MachinePointerInfo PtrInfo = 1383 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1384 1385 // Emit a store of each element to the stack slot. 1386 SmallVector<SDValue, 8> Stores; 1387 unsigned TypeByteSize = EltVT.getSizeInBits() / 8; 1388 // Store (in the right endianness) the elements to memory. 1389 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) { 1390 // Ignore undef elements. 1391 if (Node->getOperand(i).isUndef()) continue; 1392 1393 unsigned Offset = TypeByteSize*i; 1394 1395 SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType()); 1396 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx); 1397 1398 // If the destination vector element type is narrower than the source 1399 // element type, only store the bits necessary. 1400 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) { 1401 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl, 1402 Node->getOperand(i), Idx, 1403 PtrInfo.getWithOffset(Offset), EltVT)); 1404 } else 1405 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i), 1406 Idx, PtrInfo.getWithOffset(Offset))); 1407 } 1408 1409 SDValue StoreChain; 1410 if (!Stores.empty()) // Not all undef elements? 1411 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 1412 else 1413 StoreChain = DAG.getEntryNode(); 1414 1415 // Result is a load from the stack slot. 1416 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo); 1417 } 1418 1419 /// Bitcast a floating-point value to an integer value. Only bitcast the part 1420 /// containing the sign bit if the target has no integer value capable of 1421 /// holding all bits of the floating-point value. 1422 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State, 1423 const SDLoc &DL, 1424 SDValue Value) const { 1425 EVT FloatVT = Value.getValueType(); 1426 unsigned NumBits = FloatVT.getSizeInBits(); 1427 State.FloatVT = FloatVT; 1428 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 1429 // Convert to an integer of the same size. 1430 if (TLI.isTypeLegal(IVT)) { 1431 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value); 1432 State.SignMask = APInt::getSignMask(NumBits); 1433 State.SignBit = NumBits - 1; 1434 return; 1435 } 1436 1437 auto &DataLayout = DAG.getDataLayout(); 1438 // Store the float to memory, then load the sign part out as an integer. 1439 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8); 1440 // First create a temporary that is aligned for both the load and store. 1441 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy); 1442 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1443 // Then store the float to it. 1444 State.FloatPtr = StackPtr; 1445 MachineFunction &MF = DAG.getMachineFunction(); 1446 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI); 1447 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr, 1448 State.FloatPointerInfo); 1449 1450 SDValue IntPtr; 1451 if (DataLayout.isBigEndian()) { 1452 assert(FloatVT.isByteSized() && "Unsupported floating point type!"); 1453 // Load out a legal integer with the same sign bit as the float. 1454 IntPtr = StackPtr; 1455 State.IntPointerInfo = State.FloatPointerInfo; 1456 } else { 1457 // Advance the pointer so that the loaded byte will contain the sign bit. 1458 unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1; 1459 IntPtr = DAG.getNode(ISD::ADD, DL, StackPtr.getValueType(), StackPtr, 1460 DAG.getConstant(ByteOffset, DL, StackPtr.getValueType())); 1461 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI, 1462 ByteOffset); 1463 } 1464 1465 State.IntPtr = IntPtr; 1466 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr, 1467 State.IntPointerInfo, MVT::i8); 1468 State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7); 1469 State.SignBit = 7; 1470 } 1471 1472 /// Replace the integer value produced by getSignAsIntValue() with a new value 1473 /// and cast the result back to a floating-point type. 1474 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State, 1475 const SDLoc &DL, 1476 SDValue NewIntValue) const { 1477 if (!State.Chain) 1478 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue); 1479 1480 // Override the part containing the sign bit in the value stored on the stack. 1481 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr, 1482 State.IntPointerInfo, MVT::i8); 1483 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr, 1484 State.FloatPointerInfo); 1485 } 1486 1487 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const { 1488 SDLoc DL(Node); 1489 SDValue Mag = Node->getOperand(0); 1490 SDValue Sign = Node->getOperand(1); 1491 1492 // Get sign bit into an integer value. 1493 FloatSignAsInt SignAsInt; 1494 getSignAsIntValue(SignAsInt, DL, Sign); 1495 1496 EVT IntVT = SignAsInt.IntValue.getValueType(); 1497 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT); 1498 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue, 1499 SignMask); 1500 1501 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X) 1502 EVT FloatVT = Mag.getValueType(); 1503 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) && 1504 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) { 1505 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag); 1506 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue); 1507 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit, 1508 DAG.getConstant(0, DL, IntVT), ISD::SETNE); 1509 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue); 1510 } 1511 1512 // Transform Mag value to integer, and clear the sign bit. 1513 FloatSignAsInt MagAsInt; 1514 getSignAsIntValue(MagAsInt, DL, Mag); 1515 EVT MagVT = MagAsInt.IntValue.getValueType(); 1516 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT); 1517 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue, 1518 ClearSignMask); 1519 1520 // Get the signbit at the right position for MagAsInt. 1521 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit; 1522 EVT ShiftVT = IntVT; 1523 if (SignBit.getValueSizeInBits() < ClearedSign.getValueSizeInBits()) { 1524 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit); 1525 ShiftVT = MagVT; 1526 } 1527 if (ShiftAmount > 0) { 1528 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT); 1529 SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst); 1530 } else if (ShiftAmount < 0) { 1531 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT); 1532 SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst); 1533 } 1534 if (SignBit.getValueSizeInBits() > ClearedSign.getValueSizeInBits()) { 1535 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit); 1536 } 1537 1538 // Store the part with the modified sign and convert back to float. 1539 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit); 1540 return modifySignAsInt(MagAsInt, DL, CopiedSign); 1541 } 1542 1543 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const { 1544 SDLoc DL(Node); 1545 SDValue Value = Node->getOperand(0); 1546 1547 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal. 1548 EVT FloatVT = Value.getValueType(); 1549 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) { 1550 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT); 1551 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero); 1552 } 1553 1554 // Transform value to integer, clear the sign bit and transform back. 1555 FloatSignAsInt ValueAsInt; 1556 getSignAsIntValue(ValueAsInt, DL, Value); 1557 EVT IntVT = ValueAsInt.IntValue.getValueType(); 1558 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT); 1559 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue, 1560 ClearSignMask); 1561 return modifySignAsInt(ValueAsInt, DL, ClearedSign); 1562 } 1563 1564 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node, 1565 SmallVectorImpl<SDValue> &Results) { 1566 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore(); 1567 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and" 1568 " not tell us which reg is the stack pointer!"); 1569 SDLoc dl(Node); 1570 EVT VT = Node->getValueType(0); 1571 SDValue Tmp1 = SDValue(Node, 0); 1572 SDValue Tmp2 = SDValue(Node, 1); 1573 SDValue Tmp3 = Node->getOperand(2); 1574 SDValue Chain = Tmp1.getOperand(0); 1575 1576 // Chain the dynamic stack allocation so that it doesn't modify the stack 1577 // pointer when other instructions are using the stack. 1578 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 1579 1580 SDValue Size = Tmp2.getOperand(1); 1581 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 1582 Chain = SP.getValue(1); 1583 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue(); 1584 unsigned StackAlign = 1585 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 1586 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value 1587 if (Align > StackAlign) 1588 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 1589 DAG.getConstant(-(uint64_t)Align, dl, VT)); 1590 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 1591 1592 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 1593 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 1594 1595 Results.push_back(Tmp1); 1596 Results.push_back(Tmp2); 1597 } 1598 1599 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current 1600 /// target. 1601 /// 1602 /// If the SETCC has been legalized using AND / OR, then the legalized node 1603 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert 1604 /// will be set to false. 1605 /// 1606 /// If the SETCC has been legalized by using getSetCCSwappedOperands(), 1607 /// then the values of LHS and RHS will be swapped, CC will be set to the 1608 /// new condition, and NeedInvert will be set to false. 1609 /// 1610 /// If the SETCC has been legalized using the inverse condcode, then LHS and 1611 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert 1612 /// will be set to true. The caller must invert the result of the SETCC with 1613 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect 1614 /// of a true/false result. 1615 /// 1616 /// \returns true if the SetCC has been legalized, false if it hasn't. 1617 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT, SDValue &LHS, 1618 SDValue &RHS, SDValue &CC, 1619 bool &NeedInvert, 1620 const SDLoc &dl) { 1621 MVT OpVT = LHS.getSimpleValueType(); 1622 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 1623 NeedInvert = false; 1624 bool NeedSwap = false; 1625 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 1626 default: llvm_unreachable("Unknown condition code action!"); 1627 case TargetLowering::Legal: 1628 // Nothing to do. 1629 break; 1630 case TargetLowering::Expand: { 1631 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 1632 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 1633 std::swap(LHS, RHS); 1634 CC = DAG.getCondCode(InvCC); 1635 return true; 1636 } 1637 // Swapping operands didn't work. Try inverting the condition. 1638 InvCC = getSetCCInverse(CCCode, OpVT.isInteger()); 1639 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 1640 // If inverting the condition is not enough, try swapping operands 1641 // on top of it. 1642 InvCC = ISD::getSetCCSwappedOperands(InvCC); 1643 NeedSwap = true; 1644 } 1645 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) { 1646 CC = DAG.getCondCode(InvCC); 1647 NeedInvert = true; 1648 if (NeedSwap) 1649 std::swap(LHS, RHS); 1650 return true; 1651 } 1652 1653 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 1654 unsigned Opc = 0; 1655 switch (CCCode) { 1656 default: llvm_unreachable("Don't know how to expand this condition!"); 1657 case ISD::SETO: 1658 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) 1659 && "If SETO is expanded, SETOEQ must be legal!"); 1660 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break; 1661 case ISD::SETUO: 1662 assert(TLI.isCondCodeLegal(ISD::SETUNE, OpVT) 1663 && "If SETUO is expanded, SETUNE must be legal!"); 1664 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break; 1665 case ISD::SETOEQ: 1666 case ISD::SETOGT: 1667 case ISD::SETOGE: 1668 case ISD::SETOLT: 1669 case ISD::SETOLE: 1670 case ISD::SETONE: 1671 case ISD::SETUEQ: 1672 case ISD::SETUNE: 1673 case ISD::SETUGT: 1674 case ISD::SETUGE: 1675 case ISD::SETULT: 1676 case ISD::SETULE: 1677 // If we are floating point, assign and break, otherwise fall through. 1678 if (!OpVT.isInteger()) { 1679 // We can use the 4th bit to tell if we are the unordered 1680 // or ordered version of the opcode. 1681 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 1682 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 1683 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 1684 break; 1685 } 1686 // Fallthrough if we are unsigned integer. 1687 LLVM_FALLTHROUGH; 1688 case ISD::SETLE: 1689 case ISD::SETGT: 1690 case ISD::SETGE: 1691 case ISD::SETLT: 1692 case ISD::SETNE: 1693 case ISD::SETEQ: 1694 // If all combinations of inverting the condition and swapping operands 1695 // didn't work then we have no means to expand the condition. 1696 llvm_unreachable("Don't know how to expand this condition!"); 1697 } 1698 1699 SDValue SetCC1, SetCC2; 1700 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 1701 // If we aren't the ordered or unorder operation, 1702 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 1703 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1); 1704 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2); 1705 } else { 1706 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 1707 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1); 1708 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2); 1709 } 1710 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 1711 RHS = SDValue(); 1712 CC = SDValue(); 1713 return true; 1714 } 1715 } 1716 return false; 1717 } 1718 1719 /// Emit a store/load combination to the stack. This stores 1720 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does 1721 /// a load from the stack slot to DestVT, extending it if needed. 1722 /// The resultant code need not be legal. 1723 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT, 1724 EVT DestVT, const SDLoc &dl) { 1725 // Create the stack frame object. 1726 unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment( 1727 SrcOp.getValueType().getTypeForEVT(*DAG.getContext())); 1728 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign); 1729 1730 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr); 1731 int SPFI = StackPtrFI->getIndex(); 1732 MachinePointerInfo PtrInfo = 1733 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 1734 1735 unsigned SrcSize = SrcOp.getValueSizeInBits(); 1736 unsigned SlotSize = SlotVT.getSizeInBits(); 1737 unsigned DestSize = DestVT.getSizeInBits(); 1738 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext()); 1739 unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType); 1740 1741 // Emit a store to the stack slot. Use a truncstore if the input value is 1742 // later than DestVT. 1743 SDValue Store; 1744 1745 if (SrcSize > SlotSize) 1746 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, PtrInfo, 1747 SlotVT, SrcAlign); 1748 else { 1749 assert(SrcSize == SlotSize && "Invalid store"); 1750 Store = 1751 DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, PtrInfo, SrcAlign); 1752 } 1753 1754 // Result is a load from the stack slot. 1755 if (SlotSize == DestSize) 1756 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign); 1757 1758 assert(SlotSize < DestSize && "Unknown extension!"); 1759 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT, 1760 DestAlign); 1761 } 1762 1763 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) { 1764 SDLoc dl(Node); 1765 // Create a vector sized/aligned stack slot, store the value to element #0, 1766 // then load the whole vector back out. 1767 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0)); 1768 1769 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr); 1770 int SPFI = StackPtrFI->getIndex(); 1771 1772 SDValue Ch = DAG.getTruncStore( 1773 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr, 1774 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), 1775 Node->getValueType(0).getVectorElementType()); 1776 return DAG.getLoad( 1777 Node->getValueType(0), dl, Ch, StackPtr, 1778 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI)); 1779 } 1780 1781 static bool 1782 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG, 1783 const TargetLowering &TLI, SDValue &Res) { 1784 unsigned NumElems = Node->getNumOperands(); 1785 SDLoc dl(Node); 1786 EVT VT = Node->getValueType(0); 1787 1788 // Try to group the scalars into pairs, shuffle the pairs together, then 1789 // shuffle the pairs of pairs together, etc. until the vector has 1790 // been built. This will work only if all of the necessary shuffle masks 1791 // are legal. 1792 1793 // We do this in two phases; first to check the legality of the shuffles, 1794 // and next, assuming that all shuffles are legal, to create the new nodes. 1795 for (int Phase = 0; Phase < 2; ++Phase) { 1796 SmallVector<std::pair<SDValue, SmallVector<int, 16>>, 16> IntermedVals, 1797 NewIntermedVals; 1798 for (unsigned i = 0; i < NumElems; ++i) { 1799 SDValue V = Node->getOperand(i); 1800 if (V.isUndef()) 1801 continue; 1802 1803 SDValue Vec; 1804 if (Phase) 1805 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V); 1806 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i))); 1807 } 1808 1809 while (IntermedVals.size() > 2) { 1810 NewIntermedVals.clear(); 1811 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) { 1812 // This vector and the next vector are shuffled together (simply to 1813 // append the one to the other). 1814 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1815 1816 SmallVector<int, 16> FinalIndices; 1817 FinalIndices.reserve(IntermedVals[i].second.size() + 1818 IntermedVals[i+1].second.size()); 1819 1820 int k = 0; 1821 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f; 1822 ++j, ++k) { 1823 ShuffleVec[k] = j; 1824 FinalIndices.push_back(IntermedVals[i].second[j]); 1825 } 1826 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f; 1827 ++j, ++k) { 1828 ShuffleVec[k] = NumElems + j; 1829 FinalIndices.push_back(IntermedVals[i+1].second[j]); 1830 } 1831 1832 SDValue Shuffle; 1833 if (Phase) 1834 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first, 1835 IntermedVals[i+1].first, 1836 ShuffleVec); 1837 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1838 return false; 1839 NewIntermedVals.push_back( 1840 std::make_pair(Shuffle, std::move(FinalIndices))); 1841 } 1842 1843 // If we had an odd number of defined values, then append the last 1844 // element to the array of new vectors. 1845 if ((IntermedVals.size() & 1) != 0) 1846 NewIntermedVals.push_back(IntermedVals.back()); 1847 1848 IntermedVals.swap(NewIntermedVals); 1849 } 1850 1851 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 && 1852 "Invalid number of intermediate vectors"); 1853 SDValue Vec1 = IntermedVals[0].first; 1854 SDValue Vec2; 1855 if (IntermedVals.size() > 1) 1856 Vec2 = IntermedVals[1].first; 1857 else if (Phase) 1858 Vec2 = DAG.getUNDEF(VT); 1859 1860 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1861 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i) 1862 ShuffleVec[IntermedVals[0].second[i]] = i; 1863 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i) 1864 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i; 1865 1866 if (Phase) 1867 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1868 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1869 return false; 1870 } 1871 1872 return true; 1873 } 1874 1875 /// Expand a BUILD_VECTOR node on targets that don't 1876 /// support the operation, but do support the resultant vector type. 1877 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) { 1878 unsigned NumElems = Node->getNumOperands(); 1879 SDValue Value1, Value2; 1880 SDLoc dl(Node); 1881 EVT VT = Node->getValueType(0); 1882 EVT OpVT = Node->getOperand(0).getValueType(); 1883 EVT EltVT = VT.getVectorElementType(); 1884 1885 // If the only non-undef value is the low element, turn this into a 1886 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X. 1887 bool isOnlyLowElement = true; 1888 bool MoreThanTwoValues = false; 1889 bool isConstant = true; 1890 for (unsigned i = 0; i < NumElems; ++i) { 1891 SDValue V = Node->getOperand(i); 1892 if (V.isUndef()) 1893 continue; 1894 if (i > 0) 1895 isOnlyLowElement = false; 1896 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 1897 isConstant = false; 1898 1899 if (!Value1.getNode()) { 1900 Value1 = V; 1901 } else if (!Value2.getNode()) { 1902 if (V != Value1) 1903 Value2 = V; 1904 } else if (V != Value1 && V != Value2) { 1905 MoreThanTwoValues = true; 1906 } 1907 } 1908 1909 if (!Value1.getNode()) 1910 return DAG.getUNDEF(VT); 1911 1912 if (isOnlyLowElement) 1913 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0)); 1914 1915 // If all elements are constants, create a load from the constant pool. 1916 if (isConstant) { 1917 SmallVector<Constant*, 16> CV; 1918 for (unsigned i = 0, e = NumElems; i != e; ++i) { 1919 if (ConstantFPSDNode *V = 1920 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) { 1921 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue())); 1922 } else if (ConstantSDNode *V = 1923 dyn_cast<ConstantSDNode>(Node->getOperand(i))) { 1924 if (OpVT==EltVT) 1925 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue())); 1926 else { 1927 // If OpVT and EltVT don't match, EltVT is not legal and the 1928 // element values have been promoted/truncated earlier. Undo this; 1929 // we don't want a v16i8 to become a v16i32 for example. 1930 const ConstantInt *CI = V->getConstantIntValue(); 1931 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()), 1932 CI->getZExtValue())); 1933 } 1934 } else { 1935 assert(Node->getOperand(i).isUndef()); 1936 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext()); 1937 CV.push_back(UndefValue::get(OpNTy)); 1938 } 1939 } 1940 Constant *CP = ConstantVector::get(CV); 1941 SDValue CPIdx = 1942 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout())); 1943 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 1944 return DAG.getLoad( 1945 VT, dl, DAG.getEntryNode(), CPIdx, 1946 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 1947 Alignment); 1948 } 1949 1950 SmallSet<SDValue, 16> DefinedValues; 1951 for (unsigned i = 0; i < NumElems; ++i) { 1952 if (Node->getOperand(i).isUndef()) 1953 continue; 1954 DefinedValues.insert(Node->getOperand(i)); 1955 } 1956 1957 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) { 1958 if (!MoreThanTwoValues) { 1959 SmallVector<int, 8> ShuffleVec(NumElems, -1); 1960 for (unsigned i = 0; i < NumElems; ++i) { 1961 SDValue V = Node->getOperand(i); 1962 if (V.isUndef()) 1963 continue; 1964 ShuffleVec[i] = V == Value1 ? 0 : NumElems; 1965 } 1966 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) { 1967 // Get the splatted value into the low element of a vector register. 1968 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1); 1969 SDValue Vec2; 1970 if (Value2.getNode()) 1971 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2); 1972 else 1973 Vec2 = DAG.getUNDEF(VT); 1974 1975 // Return shuffle(LowValVec, undef, <0,0,0,0>) 1976 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1977 } 1978 } else { 1979 SDValue Res; 1980 if (ExpandBVWithShuffles(Node, DAG, TLI, Res)) 1981 return Res; 1982 } 1983 } 1984 1985 // Otherwise, we can't handle this case efficiently. 1986 return ExpandVectorBuildThroughStack(Node); 1987 } 1988 1989 // Expand a node into a call to a libcall. If the result value 1990 // does not fit into a register, return the lo part and set the hi part to the 1991 // by-reg argument. If it does fit into a single register, return the result 1992 // and leave the Hi part unset. 1993 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, 1994 bool isSigned) { 1995 TargetLowering::ArgListTy Args; 1996 TargetLowering::ArgListEntry Entry; 1997 for (const SDValue &Op : Node->op_values()) { 1998 EVT ArgVT = Op.getValueType(); 1999 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2000 Entry.Node = Op; 2001 Entry.Ty = ArgTy; 2002 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2003 Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2004 Args.push_back(Entry); 2005 } 2006 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2007 TLI.getPointerTy(DAG.getDataLayout())); 2008 2009 EVT RetVT = Node->getValueType(0); 2010 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2011 2012 // By default, the input chain to this libcall is the entry node of the 2013 // function. If the libcall is going to be emitted as a tail call then 2014 // TLI.isUsedByReturnOnly will change it to the right chain if the return 2015 // node which is being folded has a non-entry input chain. 2016 SDValue InChain = DAG.getEntryNode(); 2017 2018 // isTailCall may be true since the callee does not reference caller stack 2019 // frame. Check if it's in the right position and that the return types match. 2020 SDValue TCChain = InChain; 2021 const Function &F = DAG.getMachineFunction().getFunction(); 2022 bool isTailCall = 2023 TLI.isInTailCallPosition(DAG, Node, TCChain) && 2024 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()); 2025 if (isTailCall) 2026 InChain = TCChain; 2027 2028 TargetLowering::CallLoweringInfo CLI(DAG); 2029 bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned); 2030 CLI.setDebugLoc(SDLoc(Node)) 2031 .setChain(InChain) 2032 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2033 std::move(Args)) 2034 .setTailCall(isTailCall) 2035 .setSExtResult(signExtend) 2036 .setZExtResult(!signExtend) 2037 .setIsPostTypeLegalization(true); 2038 2039 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2040 2041 if (!CallInfo.second.getNode()) { 2042 LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump()); 2043 // It's a tailcall, return the chain (which is the DAG root). 2044 return DAG.getRoot(); 2045 } 2046 2047 LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump()); 2048 return CallInfo.first; 2049 } 2050 2051 /// Generate a libcall taking the given operands as arguments 2052 /// and returning a result of type RetVT. 2053 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, 2054 const SDValue *Ops, unsigned NumOps, 2055 bool isSigned, const SDLoc &dl) { 2056 TargetLowering::ArgListTy Args; 2057 Args.reserve(NumOps); 2058 2059 TargetLowering::ArgListEntry Entry; 2060 for (unsigned i = 0; i != NumOps; ++i) { 2061 Entry.Node = Ops[i]; 2062 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 2063 Entry.IsSExt = isSigned; 2064 Entry.IsZExt = !isSigned; 2065 Args.push_back(Entry); 2066 } 2067 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2068 TLI.getPointerTy(DAG.getDataLayout())); 2069 2070 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2071 2072 TargetLowering::CallLoweringInfo CLI(DAG); 2073 CLI.setDebugLoc(dl) 2074 .setChain(DAG.getEntryNode()) 2075 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2076 std::move(Args)) 2077 .setSExtResult(isSigned) 2078 .setZExtResult(!isSigned) 2079 .setIsPostTypeLegalization(true); 2080 2081 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI); 2082 2083 return CallInfo.first; 2084 } 2085 2086 // Expand a node into a call to a libcall. Similar to 2087 // ExpandLibCall except that the first operand is the in-chain. 2088 std::pair<SDValue, SDValue> 2089 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC, 2090 SDNode *Node, 2091 bool isSigned) { 2092 SDValue InChain = Node->getOperand(0); 2093 2094 TargetLowering::ArgListTy Args; 2095 TargetLowering::ArgListEntry Entry; 2096 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) { 2097 EVT ArgVT = Node->getOperand(i).getValueType(); 2098 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2099 Entry.Node = Node->getOperand(i); 2100 Entry.Ty = ArgTy; 2101 Entry.IsSExt = isSigned; 2102 Entry.IsZExt = !isSigned; 2103 Args.push_back(Entry); 2104 } 2105 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2106 TLI.getPointerTy(DAG.getDataLayout())); 2107 2108 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext()); 2109 2110 TargetLowering::CallLoweringInfo CLI(DAG); 2111 CLI.setDebugLoc(SDLoc(Node)) 2112 .setChain(InChain) 2113 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2114 std::move(Args)) 2115 .setSExtResult(isSigned) 2116 .setZExtResult(!isSigned); 2117 2118 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2119 2120 return CallInfo; 2121 } 2122 2123 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node, 2124 RTLIB::Libcall Call_F32, 2125 RTLIB::Libcall Call_F64, 2126 RTLIB::Libcall Call_F80, 2127 RTLIB::Libcall Call_F128, 2128 RTLIB::Libcall Call_PPCF128) { 2129 if (Node->isStrictFPOpcode()) 2130 Node = DAG.mutateStrictFPToFP(Node); 2131 2132 RTLIB::Libcall LC; 2133 switch (Node->getSimpleValueType(0).SimpleTy) { 2134 default: llvm_unreachable("Unexpected request for libcall!"); 2135 case MVT::f32: LC = Call_F32; break; 2136 case MVT::f64: LC = Call_F64; break; 2137 case MVT::f80: LC = Call_F80; break; 2138 case MVT::f128: LC = Call_F128; break; 2139 case MVT::ppcf128: LC = Call_PPCF128; break; 2140 } 2141 return ExpandLibCall(LC, Node, false); 2142 } 2143 2144 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned, 2145 RTLIB::Libcall Call_I8, 2146 RTLIB::Libcall Call_I16, 2147 RTLIB::Libcall Call_I32, 2148 RTLIB::Libcall Call_I64, 2149 RTLIB::Libcall Call_I128) { 2150 RTLIB::Libcall LC; 2151 switch (Node->getSimpleValueType(0).SimpleTy) { 2152 default: llvm_unreachable("Unexpected request for libcall!"); 2153 case MVT::i8: LC = Call_I8; break; 2154 case MVT::i16: LC = Call_I16; break; 2155 case MVT::i32: LC = Call_I32; break; 2156 case MVT::i64: LC = Call_I64; break; 2157 case MVT::i128: LC = Call_I128; break; 2158 } 2159 return ExpandLibCall(LC, Node, isSigned); 2160 } 2161 2162 /// Issue libcalls to __{u}divmod to compute div / rem pairs. 2163 void 2164 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node, 2165 SmallVectorImpl<SDValue> &Results) { 2166 unsigned Opcode = Node->getOpcode(); 2167 bool isSigned = Opcode == ISD::SDIVREM; 2168 2169 RTLIB::Libcall LC; 2170 switch (Node->getSimpleValueType(0).SimpleTy) { 2171 default: llvm_unreachable("Unexpected request for libcall!"); 2172 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2173 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2174 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2175 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2176 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2177 } 2178 2179 // The input chain to this libcall is the entry node of the function. 2180 // Legalizing the call will automatically add the previous call to the 2181 // dependence. 2182 SDValue InChain = DAG.getEntryNode(); 2183 2184 EVT RetVT = Node->getValueType(0); 2185 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2186 2187 TargetLowering::ArgListTy Args; 2188 TargetLowering::ArgListEntry Entry; 2189 for (const SDValue &Op : Node->op_values()) { 2190 EVT ArgVT = Op.getValueType(); 2191 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2192 Entry.Node = Op; 2193 Entry.Ty = ArgTy; 2194 Entry.IsSExt = isSigned; 2195 Entry.IsZExt = !isSigned; 2196 Args.push_back(Entry); 2197 } 2198 2199 // Also pass the return address of the remainder. 2200 SDValue FIPtr = DAG.CreateStackTemporary(RetVT); 2201 Entry.Node = FIPtr; 2202 Entry.Ty = RetTy->getPointerTo(); 2203 Entry.IsSExt = isSigned; 2204 Entry.IsZExt = !isSigned; 2205 Args.push_back(Entry); 2206 2207 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2208 TLI.getPointerTy(DAG.getDataLayout())); 2209 2210 SDLoc dl(Node); 2211 TargetLowering::CallLoweringInfo CLI(DAG); 2212 CLI.setDebugLoc(dl) 2213 .setChain(InChain) 2214 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2215 std::move(Args)) 2216 .setSExtResult(isSigned) 2217 .setZExtResult(!isSigned); 2218 2219 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2220 2221 // Remainder is loaded back from the stack frame. 2222 SDValue Rem = 2223 DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo()); 2224 Results.push_back(CallInfo.first); 2225 Results.push_back(Rem); 2226 } 2227 2228 /// Return true if sincos libcall is available. 2229 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) { 2230 RTLIB::Libcall LC; 2231 switch (Node->getSimpleValueType(0).SimpleTy) { 2232 default: llvm_unreachable("Unexpected request for libcall!"); 2233 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2234 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2235 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2236 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2237 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2238 } 2239 return TLI.getLibcallName(LC) != nullptr; 2240 } 2241 2242 /// Only issue sincos libcall if both sin and cos are needed. 2243 static bool useSinCos(SDNode *Node) { 2244 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN 2245 ? ISD::FCOS : ISD::FSIN; 2246 2247 SDValue Op0 = Node->getOperand(0); 2248 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2249 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2250 SDNode *User = *UI; 2251 if (User == Node) 2252 continue; 2253 // The other user might have been turned into sincos already. 2254 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS) 2255 return true; 2256 } 2257 return false; 2258 } 2259 2260 /// Issue libcalls to sincos to compute sin / cos pairs. 2261 void 2262 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node, 2263 SmallVectorImpl<SDValue> &Results) { 2264 RTLIB::Libcall LC; 2265 switch (Node->getSimpleValueType(0).SimpleTy) { 2266 default: llvm_unreachable("Unexpected request for libcall!"); 2267 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2268 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2269 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2270 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2271 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2272 } 2273 2274 // The input chain to this libcall is the entry node of the function. 2275 // Legalizing the call will automatically add the previous call to the 2276 // dependence. 2277 SDValue InChain = DAG.getEntryNode(); 2278 2279 EVT RetVT = Node->getValueType(0); 2280 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2281 2282 TargetLowering::ArgListTy Args; 2283 TargetLowering::ArgListEntry Entry; 2284 2285 // Pass the argument. 2286 Entry.Node = Node->getOperand(0); 2287 Entry.Ty = RetTy; 2288 Entry.IsSExt = false; 2289 Entry.IsZExt = false; 2290 Args.push_back(Entry); 2291 2292 // Pass the return address of sin. 2293 SDValue SinPtr = DAG.CreateStackTemporary(RetVT); 2294 Entry.Node = SinPtr; 2295 Entry.Ty = RetTy->getPointerTo(); 2296 Entry.IsSExt = false; 2297 Entry.IsZExt = false; 2298 Args.push_back(Entry); 2299 2300 // Also pass the return address of the cos. 2301 SDValue CosPtr = DAG.CreateStackTemporary(RetVT); 2302 Entry.Node = CosPtr; 2303 Entry.Ty = RetTy->getPointerTo(); 2304 Entry.IsSExt = false; 2305 Entry.IsZExt = false; 2306 Args.push_back(Entry); 2307 2308 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2309 TLI.getPointerTy(DAG.getDataLayout())); 2310 2311 SDLoc dl(Node); 2312 TargetLowering::CallLoweringInfo CLI(DAG); 2313 CLI.setDebugLoc(dl).setChain(InChain).setLibCallee( 2314 TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee, 2315 std::move(Args)); 2316 2317 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2318 2319 Results.push_back( 2320 DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo())); 2321 Results.push_back( 2322 DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo())); 2323 } 2324 2325 /// This function is responsible for legalizing a 2326 /// INT_TO_FP operation of the specified operand when the target requests that 2327 /// we expand it. At this point, we know that the result and operand types are 2328 /// legal for the target. 2329 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0, 2330 EVT DestVT, 2331 const SDLoc &dl) { 2332 EVT SrcVT = Op0.getValueType(); 2333 2334 // TODO: Should any fast-math-flags be set for the created nodes? 2335 LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n"); 2336 if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64)) { 2337 LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double " 2338 "expansion\n"); 2339 2340 // Get the stack frame index of a 8 byte buffer. 2341 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64); 2342 2343 // word offset constant for Hi/Lo address computation 2344 SDValue WordOff = DAG.getConstant(sizeof(int), dl, 2345 StackSlot.getValueType()); 2346 // set up Hi and Lo (into buffer) address based on endian 2347 SDValue Hi = StackSlot; 2348 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(), 2349 StackSlot, WordOff); 2350 if (DAG.getDataLayout().isLittleEndian()) 2351 std::swap(Hi, Lo); 2352 2353 // if signed map to unsigned space 2354 SDValue Op0Mapped; 2355 if (isSigned) { 2356 // constant used to invert sign bit (signed to unsigned mapping) 2357 SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32); 2358 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit); 2359 } else { 2360 Op0Mapped = Op0; 2361 } 2362 // store the lo of the constructed double - based on integer input 2363 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op0Mapped, Lo, 2364 MachinePointerInfo()); 2365 // initial hi portion of constructed double 2366 SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32); 2367 // store the hi of the constructed double - biased exponent 2368 SDValue Store2 = 2369 DAG.getStore(Store1, dl, InitialHi, Hi, MachinePointerInfo()); 2370 // load the constructed double 2371 SDValue Load = 2372 DAG.getLoad(MVT::f64, dl, Store2, StackSlot, MachinePointerInfo()); 2373 // FP constant to bias correct the final result 2374 SDValue Bias = DAG.getConstantFP(isSigned ? 2375 BitsToDouble(0x4330000080000000ULL) : 2376 BitsToDouble(0x4330000000000000ULL), 2377 dl, MVT::f64); 2378 // subtract the bias 2379 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias); 2380 // final result 2381 SDValue Result = DAG.getFPExtendOrRound(Sub, dl, DestVT); 2382 return Result; 2383 } 2384 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet"); 2385 // Code below here assumes !isSigned without checking again. 2386 2387 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0); 2388 2389 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0, 2390 DAG.getConstant(0, dl, SrcVT), ISD::SETLT); 2391 SDValue Zero = DAG.getIntPtrConstant(0, dl), 2392 Four = DAG.getIntPtrConstant(4, dl); 2393 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(), 2394 SignSet, Four, Zero); 2395 2396 // If the sign bit of the integer is set, the large number will be treated 2397 // as a negative number. To counteract this, the dynamic code adds an 2398 // offset depending on the data type. 2399 uint64_t FF; 2400 switch (SrcVT.getSimpleVT().SimpleTy) { 2401 default: llvm_unreachable("Unsupported integer type!"); 2402 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float) 2403 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float) 2404 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float) 2405 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float) 2406 } 2407 if (DAG.getDataLayout().isLittleEndian()) 2408 FF <<= 32; 2409 Constant *FudgeFactor = ConstantInt::get( 2410 Type::getInt64Ty(*DAG.getContext()), FF); 2411 2412 SDValue CPIdx = 2413 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout())); 2414 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 2415 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset); 2416 Alignment = std::min(Alignment, 4u); 2417 SDValue FudgeInReg; 2418 if (DestVT == MVT::f32) 2419 FudgeInReg = DAG.getLoad( 2420 MVT::f32, dl, DAG.getEntryNode(), CPIdx, 2421 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2422 Alignment); 2423 else { 2424 SDValue Load = DAG.getExtLoad( 2425 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx, 2426 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32, 2427 Alignment); 2428 HandleSDNode Handle(Load); 2429 LegalizeOp(Load.getNode()); 2430 FudgeInReg = Handle.getValue(); 2431 } 2432 2433 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg); 2434 } 2435 2436 /// This function is responsible for legalizing a 2437 /// *INT_TO_FP operation of the specified operand when the target requests that 2438 /// we promote it. At this point, we know that the result and operand types are 2439 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP 2440 /// operation that takes a larger input. 2441 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, 2442 bool isSigned, 2443 const SDLoc &dl) { 2444 // First step, figure out the appropriate *INT_TO_FP operation to use. 2445 EVT NewInTy = LegalOp.getValueType(); 2446 2447 unsigned OpToUse = 0; 2448 2449 // Scan for the appropriate larger type to use. 2450 while (true) { 2451 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1); 2452 assert(NewInTy.isInteger() && "Ran out of possibilities!"); 2453 2454 // If the target supports SINT_TO_FP of this type, use it. 2455 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) { 2456 OpToUse = ISD::SINT_TO_FP; 2457 break; 2458 } 2459 if (isSigned) continue; 2460 2461 // If the target supports UINT_TO_FP of this type, use it. 2462 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) { 2463 OpToUse = ISD::UINT_TO_FP; 2464 break; 2465 } 2466 2467 // Otherwise, try a larger type. 2468 } 2469 2470 // Okay, we found the operation and type to use. Zero extend our input to the 2471 // desired type then run the operation on it. 2472 return DAG.getNode(OpToUse, dl, DestVT, 2473 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 2474 dl, NewInTy, LegalOp)); 2475 } 2476 2477 /// This function is responsible for legalizing a 2478 /// FP_TO_*INT operation of the specified operand when the target requests that 2479 /// we promote it. At this point, we know that the result and operand types are 2480 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT 2481 /// operation that returns a larger result. 2482 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, 2483 bool isSigned, 2484 const SDLoc &dl) { 2485 // First step, figure out the appropriate FP_TO*INT operation to use. 2486 EVT NewOutTy = DestVT; 2487 2488 unsigned OpToUse = 0; 2489 2490 // Scan for the appropriate larger type to use. 2491 while (true) { 2492 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1); 2493 assert(NewOutTy.isInteger() && "Ran out of possibilities!"); 2494 2495 // A larger signed type can hold all unsigned values of the requested type, 2496 // so using FP_TO_SINT is valid 2497 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) { 2498 OpToUse = ISD::FP_TO_SINT; 2499 break; 2500 } 2501 2502 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT. 2503 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) { 2504 OpToUse = ISD::FP_TO_UINT; 2505 break; 2506 } 2507 2508 // Otherwise, try a larger type. 2509 } 2510 2511 // Okay, we found the operation and type to use. 2512 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp); 2513 2514 // Truncate the result of the extended FP_TO_*INT operation to the desired 2515 // size. 2516 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation); 2517 } 2518 2519 /// Legalize a BITREVERSE scalar/vector operation as a series of mask + shifts. 2520 SDValue SelectionDAGLegalize::ExpandBITREVERSE(SDValue Op, const SDLoc &dl) { 2521 EVT VT = Op.getValueType(); 2522 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2523 unsigned Sz = VT.getScalarSizeInBits(); 2524 2525 SDValue Tmp, Tmp2, Tmp3; 2526 2527 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 2528 // and finally the i1 pairs. 2529 // TODO: We can easily support i4/i2 legal types if any target ever does. 2530 if (Sz >= 8 && isPowerOf2_32(Sz)) { 2531 // Create the masks - repeating the pattern every byte. 2532 APInt MaskHi4(Sz, 0), MaskHi2(Sz, 0), MaskHi1(Sz, 0); 2533 APInt MaskLo4(Sz, 0), MaskLo2(Sz, 0), MaskLo1(Sz, 0); 2534 for (unsigned J = 0; J != Sz; J += 8) { 2535 MaskHi4 = MaskHi4 | (0xF0ull << J); 2536 MaskLo4 = MaskLo4 | (0x0Full << J); 2537 MaskHi2 = MaskHi2 | (0xCCull << J); 2538 MaskLo2 = MaskLo2 | (0x33ull << J); 2539 MaskHi1 = MaskHi1 | (0xAAull << J); 2540 MaskLo1 = MaskLo1 | (0x55ull << J); 2541 } 2542 2543 // BSWAP if the type is wider than a single byte. 2544 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 2545 2546 // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4) 2547 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT)); 2548 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT)); 2549 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, SHVT)); 2550 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT)); 2551 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 2552 2553 // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2) 2554 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT)); 2555 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT)); 2556 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, SHVT)); 2557 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT)); 2558 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 2559 2560 // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1) 2561 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT)); 2562 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT)); 2563 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, SHVT)); 2564 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT)); 2565 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 2566 return Tmp; 2567 } 2568 2569 Tmp = DAG.getConstant(0, dl, VT); 2570 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 2571 if (I < J) 2572 Tmp2 = 2573 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 2574 else 2575 Tmp2 = 2576 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 2577 2578 APInt Shift(Sz, 1); 2579 Shift <<= J; 2580 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 2581 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 2582 } 2583 2584 return Tmp; 2585 } 2586 2587 /// Open code the operations for BSWAP of the specified operation. 2588 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, const SDLoc &dl) { 2589 EVT VT = Op.getValueType(); 2590 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2591 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 2592 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 2593 default: llvm_unreachable("Unhandled Expand type in BSWAP!"); 2594 case MVT::i16: 2595 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2596 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2597 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 2598 case MVT::i32: 2599 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2600 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2601 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2602 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2603 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 2604 DAG.getConstant(0xFF0000, dl, VT)); 2605 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 2606 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 2607 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 2608 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 2609 case MVT::i64: 2610 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 2611 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 2612 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2613 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2614 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2615 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2616 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 2617 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 2618 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 2619 DAG.getConstant(255ULL<<48, dl, VT)); 2620 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 2621 DAG.getConstant(255ULL<<40, dl, VT)); 2622 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 2623 DAG.getConstant(255ULL<<32, dl, VT)); 2624 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 2625 DAG.getConstant(255ULL<<24, dl, VT)); 2626 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 2627 DAG.getConstant(255ULL<<16, dl, VT)); 2628 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 2629 DAG.getConstant(255ULL<<8 , dl, VT)); 2630 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 2631 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 2632 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 2633 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 2634 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 2635 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 2636 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 2637 } 2638 } 2639 2640 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) { 2641 LLVM_DEBUG(dbgs() << "Trying to expand node\n"); 2642 SmallVector<SDValue, 8> Results; 2643 SDLoc dl(Node); 2644 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 2645 bool NeedInvert; 2646 switch (Node->getOpcode()) { 2647 case ISD::ABS: 2648 if (TLI.expandABS(Node, Tmp1, DAG)) 2649 Results.push_back(Tmp1); 2650 break; 2651 case ISD::CTPOP: 2652 if (TLI.expandCTPOP(Node, Tmp1, DAG)) 2653 Results.push_back(Tmp1); 2654 break; 2655 case ISD::CTLZ: 2656 case ISD::CTLZ_ZERO_UNDEF: 2657 if (TLI.expandCTLZ(Node, Tmp1, DAG)) 2658 Results.push_back(Tmp1); 2659 break; 2660 case ISD::CTTZ: 2661 case ISD::CTTZ_ZERO_UNDEF: 2662 if (TLI.expandCTTZ(Node, Tmp1, DAG)) 2663 Results.push_back(Tmp1); 2664 break; 2665 case ISD::BITREVERSE: 2666 Results.push_back(ExpandBITREVERSE(Node->getOperand(0), dl)); 2667 break; 2668 case ISD::BSWAP: 2669 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl)); 2670 break; 2671 case ISD::FRAMEADDR: 2672 case ISD::RETURNADDR: 2673 case ISD::FRAME_TO_ARGS_OFFSET: 2674 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 2675 break; 2676 case ISD::EH_DWARF_CFA: { 2677 SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl, 2678 TLI.getPointerTy(DAG.getDataLayout())); 2679 SDValue Offset = DAG.getNode(ISD::ADD, dl, 2680 CfaArg.getValueType(), 2681 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 2682 CfaArg.getValueType()), 2683 CfaArg); 2684 SDValue FA = DAG.getNode( 2685 ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()), 2686 DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()))); 2687 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(), 2688 FA, Offset)); 2689 break; 2690 } 2691 case ISD::FLT_ROUNDS_: 2692 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0))); 2693 break; 2694 case ISD::EH_RETURN: 2695 case ISD::EH_LABEL: 2696 case ISD::PREFETCH: 2697 case ISD::VAEND: 2698 case ISD::EH_SJLJ_LONGJMP: 2699 // If the target didn't expand these, there's nothing to do, so just 2700 // preserve the chain and be done. 2701 Results.push_back(Node->getOperand(0)); 2702 break; 2703 case ISD::READCYCLECOUNTER: 2704 // If the target didn't expand this, just return 'zero' and preserve the 2705 // chain. 2706 Results.append(Node->getNumValues() - 1, 2707 DAG.getConstant(0, dl, Node->getValueType(0))); 2708 Results.push_back(Node->getOperand(0)); 2709 break; 2710 case ISD::EH_SJLJ_SETJMP: 2711 // If the target didn't expand this, just return 'zero' and preserve the 2712 // chain. 2713 Results.push_back(DAG.getConstant(0, dl, MVT::i32)); 2714 Results.push_back(Node->getOperand(0)); 2715 break; 2716 case ISD::ATOMIC_LOAD: { 2717 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP. 2718 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0)); 2719 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2720 SDValue Swap = DAG.getAtomicCmpSwap( 2721 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2722 Node->getOperand(0), Node->getOperand(1), Zero, Zero, 2723 cast<AtomicSDNode>(Node)->getMemOperand()); 2724 Results.push_back(Swap.getValue(0)); 2725 Results.push_back(Swap.getValue(1)); 2726 break; 2727 } 2728 case ISD::ATOMIC_STORE: { 2729 // There is no libcall for atomic store; fake it with ATOMIC_SWAP. 2730 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 2731 cast<AtomicSDNode>(Node)->getMemoryVT(), 2732 Node->getOperand(0), 2733 Node->getOperand(1), Node->getOperand(2), 2734 cast<AtomicSDNode>(Node)->getMemOperand()); 2735 Results.push_back(Swap.getValue(1)); 2736 break; 2737 } 2738 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: { 2739 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and 2740 // splits out the success value as a comparison. Expanding the resulting 2741 // ATOMIC_CMP_SWAP will produce a libcall. 2742 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2743 SDValue Res = DAG.getAtomicCmpSwap( 2744 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2745 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2), 2746 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand()); 2747 2748 SDValue ExtRes = Res; 2749 SDValue LHS = Res; 2750 SDValue RHS = Node->getOperand(1); 2751 2752 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT(); 2753 EVT OuterType = Node->getValueType(0); 2754 switch (TLI.getExtendForAtomicOps()) { 2755 case ISD::SIGN_EXTEND: 2756 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res, 2757 DAG.getValueType(AtomicType)); 2758 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType, 2759 Node->getOperand(2), DAG.getValueType(AtomicType)); 2760 ExtRes = LHS; 2761 break; 2762 case ISD::ZERO_EXTEND: 2763 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res, 2764 DAG.getValueType(AtomicType)); 2765 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2766 ExtRes = LHS; 2767 break; 2768 case ISD::ANY_EXTEND: 2769 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType); 2770 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2771 break; 2772 default: 2773 llvm_unreachable("Invalid atomic op extension"); 2774 } 2775 2776 SDValue Success = 2777 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ); 2778 2779 Results.push_back(ExtRes.getValue(0)); 2780 Results.push_back(Success); 2781 Results.push_back(Res.getValue(1)); 2782 break; 2783 } 2784 case ISD::DYNAMIC_STACKALLOC: 2785 ExpandDYNAMIC_STACKALLOC(Node, Results); 2786 break; 2787 case ISD::MERGE_VALUES: 2788 for (unsigned i = 0; i < Node->getNumValues(); i++) 2789 Results.push_back(Node->getOperand(i)); 2790 break; 2791 case ISD::UNDEF: { 2792 EVT VT = Node->getValueType(0); 2793 if (VT.isInteger()) 2794 Results.push_back(DAG.getConstant(0, dl, VT)); 2795 else { 2796 assert(VT.isFloatingPoint() && "Unknown value type!"); 2797 Results.push_back(DAG.getConstantFP(0, dl, VT)); 2798 } 2799 break; 2800 } 2801 case ISD::FP_ROUND: 2802 case ISD::BITCAST: 2803 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0), 2804 Node->getValueType(0), dl); 2805 Results.push_back(Tmp1); 2806 break; 2807 case ISD::FP_EXTEND: 2808 Tmp1 = EmitStackConvert(Node->getOperand(0), 2809 Node->getOperand(0).getValueType(), 2810 Node->getValueType(0), dl); 2811 Results.push_back(Tmp1); 2812 break; 2813 case ISD::SIGN_EXTEND_INREG: { 2814 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 2815 EVT VT = Node->getValueType(0); 2816 2817 // An in-register sign-extend of a boolean is a negation: 2818 // 'true' (1) sign-extended is -1. 2819 // 'false' (0) sign-extended is 0. 2820 // However, we must mask the high bits of the source operand because the 2821 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero. 2822 2823 // TODO: Do this for vectors too? 2824 if (ExtraVT.getSizeInBits() == 1) { 2825 SDValue One = DAG.getConstant(1, dl, VT); 2826 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One); 2827 SDValue Zero = DAG.getConstant(0, dl, VT); 2828 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And); 2829 Results.push_back(Neg); 2830 break; 2831 } 2832 2833 // NOTE: we could fall back on load/store here too for targets without 2834 // SRA. However, it is doubtful that any exist. 2835 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2836 unsigned BitsDiff = VT.getScalarSizeInBits() - 2837 ExtraVT.getScalarSizeInBits(); 2838 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy); 2839 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0), 2840 Node->getOperand(0), ShiftCst); 2841 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst); 2842 Results.push_back(Tmp1); 2843 break; 2844 } 2845 case ISD::FP_ROUND_INREG: { 2846 // The only way we can lower this is to turn it into a TRUNCSTORE, 2847 // EXTLOAD pair, targeting a temporary location (a stack slot). 2848 2849 // NOTE: there is a choice here between constantly creating new stack 2850 // slots and always reusing the same one. We currently always create 2851 // new ones, as reuse may inhibit scheduling. 2852 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 2853 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT, 2854 Node->getValueType(0), dl); 2855 Results.push_back(Tmp1); 2856 break; 2857 } 2858 case ISD::UINT_TO_FP: 2859 if (TLI.expandUINT_TO_FP(Node, Tmp1, DAG)) { 2860 Results.push_back(Tmp1); 2861 break; 2862 } 2863 LLVM_FALLTHROUGH; 2864 case ISD::SINT_TO_FP: 2865 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP, 2866 Node->getOperand(0), Node->getValueType(0), dl); 2867 Results.push_back(Tmp1); 2868 break; 2869 case ISD::FP_TO_SINT: 2870 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) 2871 Results.push_back(Tmp1); 2872 break; 2873 case ISD::FP_TO_UINT: 2874 if (TLI.expandFP_TO_UINT(Node, Tmp1, DAG)) 2875 Results.push_back(Tmp1); 2876 break; 2877 case ISD::VAARG: 2878 Results.push_back(DAG.expandVAArg(Node)); 2879 Results.push_back(Results[0].getValue(1)); 2880 break; 2881 case ISD::VACOPY: 2882 Results.push_back(DAG.expandVACopy(Node)); 2883 break; 2884 case ISD::EXTRACT_VECTOR_ELT: 2885 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1) 2886 // This must be an access of the only element. Return it. 2887 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), 2888 Node->getOperand(0)); 2889 else 2890 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0)); 2891 Results.push_back(Tmp1); 2892 break; 2893 case ISD::EXTRACT_SUBVECTOR: 2894 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0))); 2895 break; 2896 case ISD::INSERT_SUBVECTOR: 2897 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0))); 2898 break; 2899 case ISD::CONCAT_VECTORS: 2900 Results.push_back(ExpandVectorBuildThroughStack(Node)); 2901 break; 2902 case ISD::SCALAR_TO_VECTOR: 2903 Results.push_back(ExpandSCALAR_TO_VECTOR(Node)); 2904 break; 2905 case ISD::INSERT_VECTOR_ELT: 2906 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0), 2907 Node->getOperand(1), 2908 Node->getOperand(2), dl)); 2909 break; 2910 case ISD::VECTOR_SHUFFLE: { 2911 SmallVector<int, 32> NewMask; 2912 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 2913 2914 EVT VT = Node->getValueType(0); 2915 EVT EltVT = VT.getVectorElementType(); 2916 SDValue Op0 = Node->getOperand(0); 2917 SDValue Op1 = Node->getOperand(1); 2918 if (!TLI.isTypeLegal(EltVT)) { 2919 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT); 2920 2921 // BUILD_VECTOR operands are allowed to be wider than the element type. 2922 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept 2923 // it. 2924 if (NewEltVT.bitsLT(EltVT)) { 2925 // Convert shuffle node. 2926 // If original node was v4i64 and the new EltVT is i32, 2927 // cast operands to v8i32 and re-build the mask. 2928 2929 // Calculate new VT, the size of the new VT should be equal to original. 2930 EVT NewVT = 2931 EVT::getVectorVT(*DAG.getContext(), NewEltVT, 2932 VT.getSizeInBits() / NewEltVT.getSizeInBits()); 2933 assert(NewVT.bitsEq(VT)); 2934 2935 // cast operands to new VT 2936 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0); 2937 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1); 2938 2939 // Convert the shuffle mask 2940 unsigned int factor = 2941 NewVT.getVectorNumElements()/VT.getVectorNumElements(); 2942 2943 // EltVT gets smaller 2944 assert(factor > 0); 2945 2946 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 2947 if (Mask[i] < 0) { 2948 for (unsigned fi = 0; fi < factor; ++fi) 2949 NewMask.push_back(Mask[i]); 2950 } 2951 else { 2952 for (unsigned fi = 0; fi < factor; ++fi) 2953 NewMask.push_back(Mask[i]*factor+fi); 2954 } 2955 } 2956 Mask = NewMask; 2957 VT = NewVT; 2958 } 2959 EltVT = NewEltVT; 2960 } 2961 unsigned NumElems = VT.getVectorNumElements(); 2962 SmallVector<SDValue, 16> Ops; 2963 for (unsigned i = 0; i != NumElems; ++i) { 2964 if (Mask[i] < 0) { 2965 Ops.push_back(DAG.getUNDEF(EltVT)); 2966 continue; 2967 } 2968 unsigned Idx = Mask[i]; 2969 if (Idx < NumElems) 2970 Ops.push_back(DAG.getNode( 2971 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 2972 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())))); 2973 else 2974 Ops.push_back(DAG.getNode( 2975 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1, 2976 DAG.getConstant(Idx - NumElems, dl, 2977 TLI.getVectorIdxTy(DAG.getDataLayout())))); 2978 } 2979 2980 Tmp1 = DAG.getBuildVector(VT, dl, Ops); 2981 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type. 2982 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1); 2983 Results.push_back(Tmp1); 2984 break; 2985 } 2986 case ISD::EXTRACT_ELEMENT: { 2987 EVT OpTy = Node->getOperand(0).getValueType(); 2988 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) { 2989 // 1 -> Hi 2990 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0), 2991 DAG.getConstant(OpTy.getSizeInBits() / 2, dl, 2992 TLI.getShiftAmountTy( 2993 Node->getOperand(0).getValueType(), 2994 DAG.getDataLayout()))); 2995 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1); 2996 } else { 2997 // 0 -> Lo 2998 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), 2999 Node->getOperand(0)); 3000 } 3001 Results.push_back(Tmp1); 3002 break; 3003 } 3004 case ISD::STACKSAVE: 3005 // Expand to CopyFromReg if the target set 3006 // StackPointerRegisterToSaveRestore. 3007 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) { 3008 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP, 3009 Node->getValueType(0))); 3010 Results.push_back(Results[0].getValue(1)); 3011 } else { 3012 Results.push_back(DAG.getUNDEF(Node->getValueType(0))); 3013 Results.push_back(Node->getOperand(0)); 3014 } 3015 break; 3016 case ISD::STACKRESTORE: 3017 // Expand to CopyToReg if the target set 3018 // StackPointerRegisterToSaveRestore. 3019 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) { 3020 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP, 3021 Node->getOperand(1))); 3022 } else { 3023 Results.push_back(Node->getOperand(0)); 3024 } 3025 break; 3026 case ISD::GET_DYNAMIC_AREA_OFFSET: 3027 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 3028 Results.push_back(Results[0].getValue(0)); 3029 break; 3030 case ISD::FCOPYSIGN: 3031 Results.push_back(ExpandFCOPYSIGN(Node)); 3032 break; 3033 case ISD::FNEG: 3034 // Expand Y = FNEG(X) -> Y = SUB -0.0, X 3035 Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0)); 3036 // TODO: If FNEG has fast-math-flags, propagate them to the FSUB. 3037 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1, 3038 Node->getOperand(0)); 3039 Results.push_back(Tmp1); 3040 break; 3041 case ISD::FABS: 3042 Results.push_back(ExpandFABS(Node)); 3043 break; 3044 case ISD::SMIN: 3045 case ISD::SMAX: 3046 case ISD::UMIN: 3047 case ISD::UMAX: { 3048 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 3049 ISD::CondCode Pred; 3050 switch (Node->getOpcode()) { 3051 default: llvm_unreachable("How did we get here?"); 3052 case ISD::SMAX: Pred = ISD::SETGT; break; 3053 case ISD::SMIN: Pred = ISD::SETLT; break; 3054 case ISD::UMAX: Pred = ISD::SETUGT; break; 3055 case ISD::UMIN: Pred = ISD::SETULT; break; 3056 } 3057 Tmp1 = Node->getOperand(0); 3058 Tmp2 = Node->getOperand(1); 3059 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred); 3060 Results.push_back(Tmp1); 3061 break; 3062 } 3063 case ISD::FMINNUM: 3064 case ISD::FMAXNUM: { 3065 if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG)) 3066 Results.push_back(Expanded); 3067 break; 3068 } 3069 case ISD::FSIN: 3070 case ISD::FCOS: { 3071 EVT VT = Node->getValueType(0); 3072 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin / 3073 // fcos which share the same operand and both are used. 3074 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) || 3075 isSinCosLibcallAvailable(Node, TLI)) 3076 && useSinCos(Node)) { 3077 SDVTList VTs = DAG.getVTList(VT, VT); 3078 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0)); 3079 if (Node->getOpcode() == ISD::FCOS) 3080 Tmp1 = Tmp1.getValue(1); 3081 Results.push_back(Tmp1); 3082 } 3083 break; 3084 } 3085 case ISD::FMAD: 3086 llvm_unreachable("Illegal fmad should never be formed"); 3087 3088 case ISD::FP16_TO_FP: 3089 if (Node->getValueType(0) != MVT::f32) { 3090 // We can extend to types bigger than f32 in two steps without changing 3091 // the result. Since "f16 -> f32" is much more commonly available, give 3092 // CodeGen the option of emitting that before resorting to a libcall. 3093 SDValue Res = 3094 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0)); 3095 Results.push_back( 3096 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res)); 3097 } 3098 break; 3099 case ISD::FP_TO_FP16: 3100 LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n"); 3101 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) { 3102 SDValue Op = Node->getOperand(0); 3103 MVT SVT = Op.getSimpleValueType(); 3104 if ((SVT == MVT::f64 || SVT == MVT::f80) && 3105 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) { 3106 // Under fastmath, we can expand this node into a fround followed by 3107 // a float-half conversion. 3108 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op, 3109 DAG.getIntPtrConstant(0, dl)); 3110 Results.push_back( 3111 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal)); 3112 } 3113 } 3114 break; 3115 case ISD::ConstantFP: { 3116 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node); 3117 // Check to see if this FP immediate is already legal. 3118 // If this is a legal constant, turn it into a TargetConstantFP node. 3119 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0))) 3120 Results.push_back(ExpandConstantFP(CFP, true)); 3121 break; 3122 } 3123 case ISD::Constant: { 3124 ConstantSDNode *CP = cast<ConstantSDNode>(Node); 3125 Results.push_back(ExpandConstant(CP)); 3126 break; 3127 } 3128 case ISD::FSUB: { 3129 EVT VT = Node->getValueType(0); 3130 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) && 3131 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) { 3132 const SDNodeFlags Flags = Node->getFlags(); 3133 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1)); 3134 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags); 3135 Results.push_back(Tmp1); 3136 } 3137 break; 3138 } 3139 case ISD::SUB: { 3140 EVT VT = Node->getValueType(0); 3141 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 3142 TLI.isOperationLegalOrCustom(ISD::XOR, VT) && 3143 "Don't know how to expand this subtraction!"); 3144 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1), 3145 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 3146 VT)); 3147 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT)); 3148 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1)); 3149 break; 3150 } 3151 case ISD::UREM: 3152 case ISD::SREM: { 3153 EVT VT = Node->getValueType(0); 3154 bool isSigned = Node->getOpcode() == ISD::SREM; 3155 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 3156 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3157 Tmp2 = Node->getOperand(0); 3158 Tmp3 = Node->getOperand(1); 3159 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3160 SDVTList VTs = DAG.getVTList(VT, VT); 3161 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1); 3162 Results.push_back(Tmp1); 3163 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) { 3164 // X % Y -> X-X/Y*Y 3165 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3); 3166 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3); 3167 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1); 3168 Results.push_back(Tmp1); 3169 } 3170 break; 3171 } 3172 case ISD::UDIV: 3173 case ISD::SDIV: { 3174 bool isSigned = Node->getOpcode() == ISD::SDIV; 3175 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3176 EVT VT = Node->getValueType(0); 3177 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3178 SDVTList VTs = DAG.getVTList(VT, VT); 3179 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0), 3180 Node->getOperand(1)); 3181 Results.push_back(Tmp1); 3182 } 3183 break; 3184 } 3185 case ISD::MULHU: 3186 case ISD::MULHS: { 3187 unsigned ExpandOpcode = 3188 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI; 3189 EVT VT = Node->getValueType(0); 3190 SDVTList VTs = DAG.getVTList(VT, VT); 3191 3192 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0), 3193 Node->getOperand(1)); 3194 Results.push_back(Tmp1.getValue(1)); 3195 break; 3196 } 3197 case ISD::UMUL_LOHI: 3198 case ISD::SMUL_LOHI: { 3199 SDValue LHS = Node->getOperand(0); 3200 SDValue RHS = Node->getOperand(1); 3201 MVT VT = LHS.getSimpleValueType(); 3202 unsigned MULHOpcode = 3203 Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS; 3204 3205 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) { 3206 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS)); 3207 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS)); 3208 break; 3209 } 3210 3211 SmallVector<SDValue, 4> Halves; 3212 EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext()); 3213 assert(TLI.isTypeLegal(HalfType)); 3214 if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, Node, LHS, RHS, Halves, 3215 HalfType, DAG, 3216 TargetLowering::MulExpansionKind::Always)) { 3217 for (unsigned i = 0; i < 2; ++i) { 3218 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]); 3219 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]); 3220 SDValue Shift = DAG.getConstant( 3221 HalfType.getScalarSizeInBits(), dl, 3222 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3223 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3224 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3225 } 3226 break; 3227 } 3228 break; 3229 } 3230 case ISD::MUL: { 3231 EVT VT = Node->getValueType(0); 3232 SDVTList VTs = DAG.getVTList(VT, VT); 3233 // See if multiply or divide can be lowered using two-result operations. 3234 // We just need the low half of the multiply; try both the signed 3235 // and unsigned forms. If the target supports both SMUL_LOHI and 3236 // UMUL_LOHI, form a preference by checking which forms of plain 3237 // MULH it supports. 3238 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT); 3239 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT); 3240 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT); 3241 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT); 3242 unsigned OpToUse = 0; 3243 if (HasSMUL_LOHI && !HasMULHS) { 3244 OpToUse = ISD::SMUL_LOHI; 3245 } else if (HasUMUL_LOHI && !HasMULHU) { 3246 OpToUse = ISD::UMUL_LOHI; 3247 } else if (HasSMUL_LOHI) { 3248 OpToUse = ISD::SMUL_LOHI; 3249 } else if (HasUMUL_LOHI) { 3250 OpToUse = ISD::UMUL_LOHI; 3251 } 3252 if (OpToUse) { 3253 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0), 3254 Node->getOperand(1))); 3255 break; 3256 } 3257 3258 SDValue Lo, Hi; 3259 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext()); 3260 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) && 3261 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) && 3262 TLI.isOperationLegalOrCustom(ISD::SHL, VT) && 3263 TLI.isOperationLegalOrCustom(ISD::OR, VT) && 3264 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG, 3265 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) { 3266 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 3267 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi); 3268 SDValue Shift = 3269 DAG.getConstant(HalfType.getSizeInBits(), dl, 3270 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3271 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3272 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3273 } 3274 break; 3275 } 3276 case ISD::FSHL: 3277 case ISD::FSHR: 3278 if (TLI.expandFunnelShift(Node, Tmp1, DAG)) 3279 Results.push_back(Tmp1); 3280 break; 3281 case ISD::ROTL: 3282 case ISD::ROTR: 3283 if (TLI.expandROT(Node, Tmp1, DAG)) 3284 Results.push_back(Tmp1); 3285 break; 3286 case ISD::SADDSAT: 3287 case ISD::UADDSAT: 3288 case ISD::SSUBSAT: 3289 case ISD::USUBSAT: 3290 Results.push_back(TLI.expandAddSubSat(Node, DAG)); 3291 break; 3292 case ISD::SMULFIX: 3293 Results.push_back(TLI.expandFixedPointMul(Node, DAG)); 3294 break; 3295 case ISD::SADDO: 3296 case ISD::SSUBO: { 3297 SDValue LHS = Node->getOperand(0); 3298 SDValue RHS = Node->getOperand(1); 3299 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ? 3300 ISD::ADD : ISD::SUB, dl, LHS.getValueType(), 3301 LHS, RHS); 3302 Results.push_back(Sum); 3303 EVT ResultType = Node->getValueType(1); 3304 EVT OType = getSetCCResultType(Node->getValueType(0)); 3305 3306 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 3307 3308 // LHSSign -> LHS >= 0 3309 // RHSSign -> RHS >= 0 3310 // SumSign -> Sum >= 0 3311 // 3312 // Add: 3313 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign) 3314 // Sub: 3315 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign) 3316 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE); 3317 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE); 3318 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign, 3319 Node->getOpcode() == ISD::SADDO ? 3320 ISD::SETEQ : ISD::SETNE); 3321 3322 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE); 3323 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE); 3324 3325 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE); 3326 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType)); 3327 break; 3328 } 3329 case ISD::UADDO: 3330 case ISD::USUBO: { 3331 SDValue LHS = Node->getOperand(0); 3332 SDValue RHS = Node->getOperand(1); 3333 bool IsAdd = Node->getOpcode() == ISD::UADDO; 3334 // If ADD/SUBCARRY is legal, use that instead. 3335 unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY; 3336 if (TLI.isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) { 3337 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1)); 3338 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(), 3339 { LHS, RHS, CarryIn }); 3340 Results.push_back(SDValue(NodeCarry.getNode(), 0)); 3341 Results.push_back(SDValue(NodeCarry.getNode(), 1)); 3342 break; 3343 } 3344 3345 SDValue Sum = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl, 3346 LHS.getValueType(), LHS, RHS); 3347 Results.push_back(Sum); 3348 3349 EVT ResultType = Node->getValueType(1); 3350 EVT SetCCType = getSetCCResultType(Node->getValueType(0)); 3351 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT; 3352 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC); 3353 3354 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType)); 3355 break; 3356 } 3357 case ISD::UMULO: 3358 case ISD::SMULO: { 3359 EVT VT = Node->getValueType(0); 3360 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2); 3361 SDValue LHS = Node->getOperand(0); 3362 SDValue RHS = Node->getOperand(1); 3363 SDValue BottomHalf; 3364 SDValue TopHalf; 3365 static const unsigned Ops[2][3] = 3366 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 3367 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 3368 bool isSigned = Node->getOpcode() == ISD::SMULO; 3369 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 3370 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 3371 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 3372 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 3373 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 3374 RHS); 3375 TopHalf = BottomHalf.getValue(1); 3376 } else if (TLI.isTypeLegal(WideVT)) { 3377 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 3378 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 3379 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 3380 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1, 3381 DAG.getIntPtrConstant(0, dl)); 3382 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1, 3383 DAG.getIntPtrConstant(1, dl)); 3384 } else { 3385 // We can fall back to a libcall with an illegal type for the MUL if we 3386 // have a libcall big enough. 3387 // Also, we can fall back to a division in some cases, but that's a big 3388 // performance hit in the general case. 3389 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 3390 if (WideVT == MVT::i16) 3391 LC = RTLIB::MUL_I16; 3392 else if (WideVT == MVT::i32) 3393 LC = RTLIB::MUL_I32; 3394 else if (WideVT == MVT::i64) 3395 LC = RTLIB::MUL_I64; 3396 else if (WideVT == MVT::i128) 3397 LC = RTLIB::MUL_I128; 3398 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 3399 3400 SDValue HiLHS; 3401 SDValue HiRHS; 3402 if (isSigned) { 3403 // The high part is obtained by SRA'ing all but one of the bits of low 3404 // part. 3405 unsigned LoSize = VT.getSizeInBits(); 3406 HiLHS = 3407 DAG.getNode(ISD::SRA, dl, VT, LHS, 3408 DAG.getConstant(LoSize - 1, dl, 3409 TLI.getPointerTy(DAG.getDataLayout()))); 3410 HiRHS = 3411 DAG.getNode(ISD::SRA, dl, VT, RHS, 3412 DAG.getConstant(LoSize - 1, dl, 3413 TLI.getPointerTy(DAG.getDataLayout()))); 3414 } else { 3415 HiLHS = DAG.getConstant(0, dl, VT); 3416 HiRHS = DAG.getConstant(0, dl, VT); 3417 } 3418 3419 // Here we're passing the 2 arguments explicitly as 4 arguments that are 3420 // pre-lowered to the correct types. This all depends upon WideVT not 3421 // being a legal type for the architecture and thus has to be split to 3422 // two arguments. 3423 SDValue Ret; 3424 if(DAG.getDataLayout().isLittleEndian()) { 3425 // Halves of WideVT are packed into registers in different order 3426 // depending on platform endianness. This is usually handled by 3427 // the C calling convention, but we can't defer to it in 3428 // the legalizer. 3429 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 3430 Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl); 3431 } else { 3432 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 3433 Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl); 3434 } 3435 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 3436 "Ret value is a collection of constituent nodes holding result."); 3437 BottomHalf = Ret.getOperand(0); 3438 TopHalf = Ret.getOperand(1); 3439 } 3440 3441 if (isSigned) { 3442 Tmp1 = DAG.getConstant( 3443 VT.getSizeInBits() - 1, dl, 3444 TLI.getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 3445 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1); 3446 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1, 3447 ISD::SETNE); 3448 } else { 3449 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, 3450 DAG.getConstant(0, dl, VT), ISD::SETNE); 3451 } 3452 3453 // Truncate the result if SetCC returns a larger type than needed. 3454 EVT RType = Node->getValueType(1); 3455 if (RType.getSizeInBits() < TopHalf.getValueSizeInBits()) 3456 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, RType, TopHalf); 3457 3458 assert(RType.getSizeInBits() == TopHalf.getValueSizeInBits() && 3459 "Unexpected result type for S/UMULO legalization"); 3460 3461 Results.push_back(BottomHalf); 3462 Results.push_back(TopHalf); 3463 break; 3464 } 3465 case ISD::BUILD_PAIR: { 3466 EVT PairTy = Node->getValueType(0); 3467 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0)); 3468 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1)); 3469 Tmp2 = DAG.getNode( 3470 ISD::SHL, dl, PairTy, Tmp2, 3471 DAG.getConstant(PairTy.getSizeInBits() / 2, dl, 3472 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout()))); 3473 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2)); 3474 break; 3475 } 3476 case ISD::SELECT: 3477 Tmp1 = Node->getOperand(0); 3478 Tmp2 = Node->getOperand(1); 3479 Tmp3 = Node->getOperand(2); 3480 if (Tmp1.getOpcode() == ISD::SETCC) { 3481 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1), 3482 Tmp2, Tmp3, 3483 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get()); 3484 } else { 3485 Tmp1 = DAG.getSelectCC(dl, Tmp1, 3486 DAG.getConstant(0, dl, Tmp1.getValueType()), 3487 Tmp2, Tmp3, ISD::SETNE); 3488 } 3489 Results.push_back(Tmp1); 3490 break; 3491 case ISD::BR_JT: { 3492 SDValue Chain = Node->getOperand(0); 3493 SDValue Table = Node->getOperand(1); 3494 SDValue Index = Node->getOperand(2); 3495 3496 const DataLayout &TD = DAG.getDataLayout(); 3497 EVT PTy = TLI.getPointerTy(TD); 3498 3499 unsigned EntrySize = 3500 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD); 3501 3502 // For power-of-two jumptable entry sizes convert multiplication to a shift. 3503 // This transformation needs to be done here since otherwise the MIPS 3504 // backend will end up emitting a three instruction multiply sequence 3505 // instead of a single shift and MSP430 will call a runtime function. 3506 if (llvm::isPowerOf2_32(EntrySize)) 3507 Index = DAG.getNode( 3508 ISD::SHL, dl, Index.getValueType(), Index, 3509 DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType())); 3510 else 3511 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index, 3512 DAG.getConstant(EntrySize, dl, Index.getValueType())); 3513 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(), 3514 Index, Table); 3515 3516 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8); 3517 SDValue LD = DAG.getExtLoad( 3518 ISD::SEXTLOAD, dl, PTy, Chain, Addr, 3519 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT); 3520 Addr = LD; 3521 if (TLI.isJumpTableRelative()) { 3522 // For PIC, the sequence is: 3523 // BRIND(load(Jumptable + index) + RelocBase) 3524 // RelocBase can be JumpTable, GOT or some sort of global base. 3525 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, 3526 TLI.getPICJumpTableRelocBase(Table, DAG)); 3527 } 3528 3529 Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG); 3530 Results.push_back(Tmp1); 3531 break; 3532 } 3533 case ISD::BRCOND: 3534 // Expand brcond's setcc into its constituent parts and create a BR_CC 3535 // Node. 3536 Tmp1 = Node->getOperand(0); 3537 Tmp2 = Node->getOperand(1); 3538 if (Tmp2.getOpcode() == ISD::SETCC) { 3539 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, 3540 Tmp1, Tmp2.getOperand(2), 3541 Tmp2.getOperand(0), Tmp2.getOperand(1), 3542 Node->getOperand(2)); 3543 } else { 3544 // We test only the i1 bit. Skip the AND if UNDEF or another AND. 3545 if (Tmp2.isUndef() || 3546 (Tmp2.getOpcode() == ISD::AND && 3547 isa<ConstantSDNode>(Tmp2.getOperand(1)) && 3548 cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1)) 3549 Tmp3 = Tmp2; 3550 else 3551 Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2, 3552 DAG.getConstant(1, dl, Tmp2.getValueType())); 3553 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, 3554 DAG.getCondCode(ISD::SETNE), Tmp3, 3555 DAG.getConstant(0, dl, Tmp3.getValueType()), 3556 Node->getOperand(2)); 3557 } 3558 Results.push_back(Tmp1); 3559 break; 3560 case ISD::SETCC: { 3561 Tmp1 = Node->getOperand(0); 3562 Tmp2 = Node->getOperand(1); 3563 Tmp3 = Node->getOperand(2); 3564 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, 3565 Tmp3, NeedInvert, dl); 3566 3567 if (Legalized) { 3568 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3569 // condition code, create a new SETCC node. 3570 if (Tmp3.getNode()) 3571 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), 3572 Tmp1, Tmp2, Tmp3); 3573 3574 // If we expanded the SETCC by inverting the condition code, then wrap 3575 // the existing SETCC in a NOT to restore the intended condition. 3576 if (NeedInvert) 3577 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0)); 3578 3579 Results.push_back(Tmp1); 3580 break; 3581 } 3582 3583 // Otherwise, SETCC for the given comparison type must be completely 3584 // illegal; expand it into a SELECT_CC. 3585 EVT VT = Node->getValueType(0); 3586 int TrueValue; 3587 switch (TLI.getBooleanContents(Tmp1.getValueType())) { 3588 case TargetLowering::ZeroOrOneBooleanContent: 3589 case TargetLowering::UndefinedBooleanContent: 3590 TrueValue = 1; 3591 break; 3592 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3593 TrueValue = -1; 3594 break; 3595 } 3596 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2, 3597 DAG.getConstant(TrueValue, dl, VT), 3598 DAG.getConstant(0, dl, VT), 3599 Tmp3); 3600 Results.push_back(Tmp1); 3601 break; 3602 } 3603 case ISD::SELECT_CC: { 3604 Tmp1 = Node->getOperand(0); // LHS 3605 Tmp2 = Node->getOperand(1); // RHS 3606 Tmp3 = Node->getOperand(2); // True 3607 Tmp4 = Node->getOperand(3); // False 3608 EVT VT = Node->getValueType(0); 3609 SDValue CC = Node->getOperand(4); 3610 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get(); 3611 3612 if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) { 3613 // If the condition code is legal, then we need to expand this 3614 // node using SETCC and SELECT. 3615 EVT CmpVT = Tmp1.getValueType(); 3616 assert(!TLI.isOperationExpand(ISD::SELECT, VT) && 3617 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be " 3618 "expanded."); 3619 EVT CCVT = 3620 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT); 3621 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC); 3622 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4)); 3623 break; 3624 } 3625 3626 // SELECT_CC is legal, so the condition code must not be. 3627 bool Legalized = false; 3628 // Try to legalize by inverting the condition. This is for targets that 3629 // might support an ordered version of a condition, but not the unordered 3630 // version (or vice versa). 3631 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, 3632 Tmp1.getValueType().isInteger()); 3633 if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) { 3634 // Use the new condition code and swap true and false 3635 Legalized = true; 3636 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC); 3637 } else { 3638 // If The inverse is not legal, then try to swap the arguments using 3639 // the inverse condition code. 3640 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC); 3641 if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) { 3642 // The swapped inverse condition is legal, so swap true and false, 3643 // lhs and rhs. 3644 Legalized = true; 3645 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC); 3646 } 3647 } 3648 3649 if (!Legalized) { 3650 Legalized = LegalizeSetCCCondCode( 3651 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert, 3652 dl); 3653 3654 assert(Legalized && "Can't legalize SELECT_CC with legal condition!"); 3655 3656 // If we expanded the SETCC by inverting the condition code, then swap 3657 // the True/False operands to match. 3658 if (NeedInvert) 3659 std::swap(Tmp3, Tmp4); 3660 3661 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3662 // condition code, create a new SELECT_CC node. 3663 if (CC.getNode()) { 3664 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), 3665 Tmp1, Tmp2, Tmp3, Tmp4, CC); 3666 } else { 3667 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType()); 3668 CC = DAG.getCondCode(ISD::SETNE); 3669 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, 3670 Tmp2, Tmp3, Tmp4, CC); 3671 } 3672 } 3673 Results.push_back(Tmp1); 3674 break; 3675 } 3676 case ISD::BR_CC: { 3677 Tmp1 = Node->getOperand(0); // Chain 3678 Tmp2 = Node->getOperand(2); // LHS 3679 Tmp3 = Node->getOperand(3); // RHS 3680 Tmp4 = Node->getOperand(1); // CC 3681 3682 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType( 3683 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl); 3684 (void)Legalized; 3685 assert(Legalized && "Can't legalize BR_CC with legal condition!"); 3686 3687 assert(!NeedInvert && "Don't know how to invert BR_CC!"); 3688 3689 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC 3690 // node. 3691 if (Tmp4.getNode()) { 3692 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, 3693 Tmp4, Tmp2, Tmp3, Node->getOperand(4)); 3694 } else { 3695 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType()); 3696 Tmp4 = DAG.getCondCode(ISD::SETNE); 3697 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, 3698 Tmp2, Tmp3, Node->getOperand(4)); 3699 } 3700 Results.push_back(Tmp1); 3701 break; 3702 } 3703 case ISD::BUILD_VECTOR: 3704 Results.push_back(ExpandBUILD_VECTOR(Node)); 3705 break; 3706 case ISD::SRA: 3707 case ISD::SRL: 3708 case ISD::SHL: { 3709 // Scalarize vector SRA/SRL/SHL. 3710 EVT VT = Node->getValueType(0); 3711 assert(VT.isVector() && "Unable to legalize non-vector shift"); 3712 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal"); 3713 unsigned NumElem = VT.getVectorNumElements(); 3714 3715 SmallVector<SDValue, 8> Scalars; 3716 for (unsigned Idx = 0; Idx < NumElem; Idx++) { 3717 SDValue Ex = DAG.getNode( 3718 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0), 3719 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3720 SDValue Sh = DAG.getNode( 3721 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1), 3722 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3723 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl, 3724 VT.getScalarType(), Ex, Sh)); 3725 } 3726 3727 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars); 3728 ReplaceNode(SDValue(Node, 0), Result); 3729 break; 3730 } 3731 case ISD::GLOBAL_OFFSET_TABLE: 3732 case ISD::GlobalAddress: 3733 case ISD::GlobalTLSAddress: 3734 case ISD::ExternalSymbol: 3735 case ISD::ConstantPool: 3736 case ISD::JumpTable: 3737 case ISD::INTRINSIC_W_CHAIN: 3738 case ISD::INTRINSIC_WO_CHAIN: 3739 case ISD::INTRINSIC_VOID: 3740 // FIXME: Custom lowering for these operations shouldn't return null! 3741 break; 3742 } 3743 3744 // Replace the original node with the legalized result. 3745 if (Results.empty()) { 3746 LLVM_DEBUG(dbgs() << "Cannot expand node\n"); 3747 return false; 3748 } 3749 3750 LLVM_DEBUG(dbgs() << "Successfully expanded node\n"); 3751 ReplaceNode(Node, Results.data()); 3752 return true; 3753 } 3754 3755 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) { 3756 LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n"); 3757 SmallVector<SDValue, 8> Results; 3758 SDLoc dl(Node); 3759 // FIXME: Check flags on the node to see if we can use a finite call. 3760 bool CanUseFiniteLibCall = TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath; 3761 unsigned Opc = Node->getOpcode(); 3762 switch (Opc) { 3763 case ISD::ATOMIC_FENCE: { 3764 // If the target didn't lower this, lower it to '__sync_synchronize()' call 3765 // FIXME: handle "fence singlethread" more efficiently. 3766 TargetLowering::ArgListTy Args; 3767 3768 TargetLowering::CallLoweringInfo CLI(DAG); 3769 CLI.setDebugLoc(dl) 3770 .setChain(Node->getOperand(0)) 3771 .setLibCallee( 3772 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3773 DAG.getExternalSymbol("__sync_synchronize", 3774 TLI.getPointerTy(DAG.getDataLayout())), 3775 std::move(Args)); 3776 3777 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3778 3779 Results.push_back(CallResult.second); 3780 break; 3781 } 3782 // By default, atomic intrinsics are marked Legal and lowered. Targets 3783 // which don't support them directly, however, may want libcalls, in which 3784 // case they mark them Expand, and we get here. 3785 case ISD::ATOMIC_SWAP: 3786 case ISD::ATOMIC_LOAD_ADD: 3787 case ISD::ATOMIC_LOAD_SUB: 3788 case ISD::ATOMIC_LOAD_AND: 3789 case ISD::ATOMIC_LOAD_CLR: 3790 case ISD::ATOMIC_LOAD_OR: 3791 case ISD::ATOMIC_LOAD_XOR: 3792 case ISD::ATOMIC_LOAD_NAND: 3793 case ISD::ATOMIC_LOAD_MIN: 3794 case ISD::ATOMIC_LOAD_MAX: 3795 case ISD::ATOMIC_LOAD_UMIN: 3796 case ISD::ATOMIC_LOAD_UMAX: 3797 case ISD::ATOMIC_CMP_SWAP: { 3798 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT(); 3799 RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT); 3800 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!"); 3801 3802 std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false); 3803 Results.push_back(Tmp.first); 3804 Results.push_back(Tmp.second); 3805 break; 3806 } 3807 case ISD::TRAP: { 3808 // If this operation is not supported, lower it to 'abort()' call 3809 TargetLowering::ArgListTy Args; 3810 TargetLowering::CallLoweringInfo CLI(DAG); 3811 CLI.setDebugLoc(dl) 3812 .setChain(Node->getOperand(0)) 3813 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3814 DAG.getExternalSymbol( 3815 "abort", TLI.getPointerTy(DAG.getDataLayout())), 3816 std::move(Args)); 3817 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3818 3819 Results.push_back(CallResult.second); 3820 break; 3821 } 3822 case ISD::FMINNUM: 3823 case ISD::STRICT_FMINNUM: 3824 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64, 3825 RTLIB::FMIN_F80, RTLIB::FMIN_F128, 3826 RTLIB::FMIN_PPCF128)); 3827 break; 3828 case ISD::FMAXNUM: 3829 case ISD::STRICT_FMAXNUM: 3830 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64, 3831 RTLIB::FMAX_F80, RTLIB::FMAX_F128, 3832 RTLIB::FMAX_PPCF128)); 3833 break; 3834 case ISD::FSQRT: 3835 case ISD::STRICT_FSQRT: 3836 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64, 3837 RTLIB::SQRT_F80, RTLIB::SQRT_F128, 3838 RTLIB::SQRT_PPCF128)); 3839 break; 3840 case ISD::FCBRT: 3841 Results.push_back(ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64, 3842 RTLIB::CBRT_F80, RTLIB::CBRT_F128, 3843 RTLIB::CBRT_PPCF128)); 3844 break; 3845 case ISD::FSIN: 3846 case ISD::STRICT_FSIN: 3847 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64, 3848 RTLIB::SIN_F80, RTLIB::SIN_F128, 3849 RTLIB::SIN_PPCF128)); 3850 break; 3851 case ISD::FCOS: 3852 case ISD::STRICT_FCOS: 3853 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64, 3854 RTLIB::COS_F80, RTLIB::COS_F128, 3855 RTLIB::COS_PPCF128)); 3856 break; 3857 case ISD::FSINCOS: 3858 // Expand into sincos libcall. 3859 ExpandSinCosLibCall(Node, Results); 3860 break; 3861 case ISD::FLOG: 3862 case ISD::STRICT_FLOG: 3863 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log_finite)) 3864 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_FINITE_F32, 3865 RTLIB::LOG_FINITE_F64, 3866 RTLIB::LOG_FINITE_F80, 3867 RTLIB::LOG_FINITE_F128, 3868 RTLIB::LOG_FINITE_PPCF128)); 3869 else 3870 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, 3871 RTLIB::LOG_F80, RTLIB::LOG_F128, 3872 RTLIB::LOG_PPCF128)); 3873 break; 3874 case ISD::FLOG2: 3875 case ISD::STRICT_FLOG2: 3876 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log2_finite)) 3877 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_FINITE_F32, 3878 RTLIB::LOG2_FINITE_F64, 3879 RTLIB::LOG2_FINITE_F80, 3880 RTLIB::LOG2_FINITE_F128, 3881 RTLIB::LOG2_FINITE_PPCF128)); 3882 else 3883 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, 3884 RTLIB::LOG2_F80, RTLIB::LOG2_F128, 3885 RTLIB::LOG2_PPCF128)); 3886 break; 3887 case ISD::FLOG10: 3888 case ISD::STRICT_FLOG10: 3889 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log10_finite)) 3890 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_FINITE_F32, 3891 RTLIB::LOG10_FINITE_F64, 3892 RTLIB::LOG10_FINITE_F80, 3893 RTLIB::LOG10_FINITE_F128, 3894 RTLIB::LOG10_FINITE_PPCF128)); 3895 else 3896 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, 3897 RTLIB::LOG10_F80, RTLIB::LOG10_F128, 3898 RTLIB::LOG10_PPCF128)); 3899 break; 3900 case ISD::FEXP: 3901 case ISD::STRICT_FEXP: 3902 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp_finite)) 3903 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_FINITE_F32, 3904 RTLIB::EXP_FINITE_F64, 3905 RTLIB::EXP_FINITE_F80, 3906 RTLIB::EXP_FINITE_F128, 3907 RTLIB::EXP_FINITE_PPCF128)); 3908 else 3909 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, 3910 RTLIB::EXP_F80, RTLIB::EXP_F128, 3911 RTLIB::EXP_PPCF128)); 3912 break; 3913 case ISD::FEXP2: 3914 case ISD::STRICT_FEXP2: 3915 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp2_finite)) 3916 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_FINITE_F32, 3917 RTLIB::EXP2_FINITE_F64, 3918 RTLIB::EXP2_FINITE_F80, 3919 RTLIB::EXP2_FINITE_F128, 3920 RTLIB::EXP2_FINITE_PPCF128)); 3921 else 3922 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, 3923 RTLIB::EXP2_F80, RTLIB::EXP2_F128, 3924 RTLIB::EXP2_PPCF128)); 3925 break; 3926 case ISD::FTRUNC: 3927 case ISD::STRICT_FTRUNC: 3928 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64, 3929 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128, 3930 RTLIB::TRUNC_PPCF128)); 3931 break; 3932 case ISD::FFLOOR: 3933 case ISD::STRICT_FFLOOR: 3934 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64, 3935 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128, 3936 RTLIB::FLOOR_PPCF128)); 3937 break; 3938 case ISD::FCEIL: 3939 case ISD::STRICT_FCEIL: 3940 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64, 3941 RTLIB::CEIL_F80, RTLIB::CEIL_F128, 3942 RTLIB::CEIL_PPCF128)); 3943 break; 3944 case ISD::FRINT: 3945 case ISD::STRICT_FRINT: 3946 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64, 3947 RTLIB::RINT_F80, RTLIB::RINT_F128, 3948 RTLIB::RINT_PPCF128)); 3949 break; 3950 case ISD::FNEARBYINT: 3951 case ISD::STRICT_FNEARBYINT: 3952 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32, 3953 RTLIB::NEARBYINT_F64, 3954 RTLIB::NEARBYINT_F80, 3955 RTLIB::NEARBYINT_F128, 3956 RTLIB::NEARBYINT_PPCF128)); 3957 break; 3958 case ISD::FROUND: 3959 case ISD::STRICT_FROUND: 3960 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32, 3961 RTLIB::ROUND_F64, 3962 RTLIB::ROUND_F80, 3963 RTLIB::ROUND_F128, 3964 RTLIB::ROUND_PPCF128)); 3965 break; 3966 case ISD::FPOWI: 3967 case ISD::STRICT_FPOWI: 3968 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64, 3969 RTLIB::POWI_F80, RTLIB::POWI_F128, 3970 RTLIB::POWI_PPCF128)); 3971 break; 3972 case ISD::FPOW: 3973 case ISD::STRICT_FPOW: 3974 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_pow_finite)) 3975 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_FINITE_F32, 3976 RTLIB::POW_FINITE_F64, 3977 RTLIB::POW_FINITE_F80, 3978 RTLIB::POW_FINITE_F128, 3979 RTLIB::POW_FINITE_PPCF128)); 3980 else 3981 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, 3982 RTLIB::POW_F80, RTLIB::POW_F128, 3983 RTLIB::POW_PPCF128)); 3984 break; 3985 case ISD::FDIV: 3986 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64, 3987 RTLIB::DIV_F80, RTLIB::DIV_F128, 3988 RTLIB::DIV_PPCF128)); 3989 break; 3990 case ISD::FREM: 3991 case ISD::STRICT_FREM: 3992 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64, 3993 RTLIB::REM_F80, RTLIB::REM_F128, 3994 RTLIB::REM_PPCF128)); 3995 break; 3996 case ISD::FMA: 3997 case ISD::STRICT_FMA: 3998 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64, 3999 RTLIB::FMA_F80, RTLIB::FMA_F128, 4000 RTLIB::FMA_PPCF128)); 4001 break; 4002 case ISD::FADD: 4003 Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64, 4004 RTLIB::ADD_F80, RTLIB::ADD_F128, 4005 RTLIB::ADD_PPCF128)); 4006 break; 4007 case ISD::FMUL: 4008 Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64, 4009 RTLIB::MUL_F80, RTLIB::MUL_F128, 4010 RTLIB::MUL_PPCF128)); 4011 break; 4012 case ISD::FP16_TO_FP: 4013 if (Node->getValueType(0) == MVT::f32) { 4014 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false)); 4015 } 4016 break; 4017 case ISD::FP_TO_FP16: { 4018 RTLIB::Libcall LC = 4019 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16); 4020 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16"); 4021 Results.push_back(ExpandLibCall(LC, Node, false)); 4022 break; 4023 } 4024 case ISD::FSUB: 4025 Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64, 4026 RTLIB::SUB_F80, RTLIB::SUB_F128, 4027 RTLIB::SUB_PPCF128)); 4028 break; 4029 case ISD::SREM: 4030 Results.push_back(ExpandIntLibCall(Node, true, 4031 RTLIB::SREM_I8, 4032 RTLIB::SREM_I16, RTLIB::SREM_I32, 4033 RTLIB::SREM_I64, RTLIB::SREM_I128)); 4034 break; 4035 case ISD::UREM: 4036 Results.push_back(ExpandIntLibCall(Node, false, 4037 RTLIB::UREM_I8, 4038 RTLIB::UREM_I16, RTLIB::UREM_I32, 4039 RTLIB::UREM_I64, RTLIB::UREM_I128)); 4040 break; 4041 case ISD::SDIV: 4042 Results.push_back(ExpandIntLibCall(Node, true, 4043 RTLIB::SDIV_I8, 4044 RTLIB::SDIV_I16, RTLIB::SDIV_I32, 4045 RTLIB::SDIV_I64, RTLIB::SDIV_I128)); 4046 break; 4047 case ISD::UDIV: 4048 Results.push_back(ExpandIntLibCall(Node, false, 4049 RTLIB::UDIV_I8, 4050 RTLIB::UDIV_I16, RTLIB::UDIV_I32, 4051 RTLIB::UDIV_I64, RTLIB::UDIV_I128)); 4052 break; 4053 case ISD::SDIVREM: 4054 case ISD::UDIVREM: 4055 // Expand into divrem libcall 4056 ExpandDivRemLibCall(Node, Results); 4057 break; 4058 case ISD::MUL: 4059 Results.push_back(ExpandIntLibCall(Node, false, 4060 RTLIB::MUL_I8, 4061 RTLIB::MUL_I16, RTLIB::MUL_I32, 4062 RTLIB::MUL_I64, RTLIB::MUL_I128)); 4063 break; 4064 case ISD::CTLZ_ZERO_UNDEF: 4065 switch (Node->getSimpleValueType(0).SimpleTy) { 4066 default: 4067 llvm_unreachable("LibCall explicitly requested, but not available"); 4068 case MVT::i32: 4069 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false)); 4070 break; 4071 case MVT::i64: 4072 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false)); 4073 break; 4074 case MVT::i128: 4075 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false)); 4076 break; 4077 } 4078 break; 4079 } 4080 4081 // Replace the original node with the legalized result. 4082 if (!Results.empty()) { 4083 LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n"); 4084 ReplaceNode(Node, Results.data()); 4085 } else 4086 LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n"); 4087 } 4088 4089 // Determine the vector type to use in place of an original scalar element when 4090 // promoting equally sized vectors. 4091 static MVT getPromotedVectorElementType(const TargetLowering &TLI, 4092 MVT EltVT, MVT NewEltVT) { 4093 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits(); 4094 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt); 4095 assert(TLI.isTypeLegal(MidVT) && "unexpected"); 4096 return MidVT; 4097 } 4098 4099 void SelectionDAGLegalize::PromoteNode(SDNode *Node) { 4100 LLVM_DEBUG(dbgs() << "Trying to promote node\n"); 4101 SmallVector<SDValue, 8> Results; 4102 MVT OVT = Node->getSimpleValueType(0); 4103 if (Node->getOpcode() == ISD::UINT_TO_FP || 4104 Node->getOpcode() == ISD::SINT_TO_FP || 4105 Node->getOpcode() == ISD::SETCC || 4106 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT || 4107 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) { 4108 OVT = Node->getOperand(0).getSimpleValueType(); 4109 } 4110 if (Node->getOpcode() == ISD::BR_CC) 4111 OVT = Node->getOperand(2).getSimpleValueType(); 4112 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT); 4113 SDLoc dl(Node); 4114 SDValue Tmp1, Tmp2, Tmp3; 4115 switch (Node->getOpcode()) { 4116 case ISD::CTTZ: 4117 case ISD::CTTZ_ZERO_UNDEF: 4118 case ISD::CTLZ: 4119 case ISD::CTLZ_ZERO_UNDEF: 4120 case ISD::CTPOP: 4121 // Zero extend the argument. 4122 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4123 if (Node->getOpcode() == ISD::CTTZ) { 4124 // The count is the same in the promoted type except if the original 4125 // value was zero. This can be handled by setting the bit just off 4126 // the top of the original type. 4127 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(), 4128 OVT.getSizeInBits()); 4129 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1, 4130 DAG.getConstant(TopBit, dl, NVT)); 4131 } 4132 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is 4133 // already the correct result. 4134 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4135 if (Node->getOpcode() == ISD::CTLZ || 4136 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) { 4137 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT)) 4138 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1, 4139 DAG.getConstant(NVT.getSizeInBits() - 4140 OVT.getSizeInBits(), dl, NVT)); 4141 } 4142 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4143 break; 4144 case ISD::BITREVERSE: 4145 case ISD::BSWAP: { 4146 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits(); 4147 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4148 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4149 Tmp1 = DAG.getNode( 4150 ISD::SRL, dl, NVT, Tmp1, 4151 DAG.getConstant(DiffBits, dl, 4152 TLI.getShiftAmountTy(NVT, DAG.getDataLayout()))); 4153 4154 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4155 break; 4156 } 4157 case ISD::FP_TO_UINT: 4158 case ISD::FP_TO_SINT: 4159 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0), 4160 Node->getOpcode() == ISD::FP_TO_SINT, dl); 4161 Results.push_back(Tmp1); 4162 break; 4163 case ISD::UINT_TO_FP: 4164 case ISD::SINT_TO_FP: 4165 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0), 4166 Node->getOpcode() == ISD::SINT_TO_FP, dl); 4167 Results.push_back(Tmp1); 4168 break; 4169 case ISD::VAARG: { 4170 SDValue Chain = Node->getOperand(0); // Get the chain. 4171 SDValue Ptr = Node->getOperand(1); // Get the pointer. 4172 4173 unsigned TruncOp; 4174 if (OVT.isVector()) { 4175 TruncOp = ISD::BITCAST; 4176 } else { 4177 assert(OVT.isInteger() 4178 && "VAARG promotion is supported only for vectors or integer types"); 4179 TruncOp = ISD::TRUNCATE; 4180 } 4181 4182 // Perform the larger operation, then convert back 4183 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2), 4184 Node->getConstantOperandVal(3)); 4185 Chain = Tmp1.getValue(1); 4186 4187 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1); 4188 4189 // Modified the chain result - switch anything that used the old chain to 4190 // use the new one. 4191 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2); 4192 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 4193 if (UpdatedNodes) { 4194 UpdatedNodes->insert(Tmp2.getNode()); 4195 UpdatedNodes->insert(Chain.getNode()); 4196 } 4197 ReplacedNode(Node); 4198 break; 4199 } 4200 case ISD::MUL: 4201 case ISD::SDIV: 4202 case ISD::SREM: 4203 case ISD::UDIV: 4204 case ISD::UREM: 4205 case ISD::AND: 4206 case ISD::OR: 4207 case ISD::XOR: { 4208 unsigned ExtOp, TruncOp; 4209 if (OVT.isVector()) { 4210 ExtOp = ISD::BITCAST; 4211 TruncOp = ISD::BITCAST; 4212 } else { 4213 assert(OVT.isInteger() && "Cannot promote logic operation"); 4214 4215 switch (Node->getOpcode()) { 4216 default: 4217 ExtOp = ISD::ANY_EXTEND; 4218 break; 4219 case ISD::SDIV: 4220 case ISD::SREM: 4221 ExtOp = ISD::SIGN_EXTEND; 4222 break; 4223 case ISD::UDIV: 4224 case ISD::UREM: 4225 ExtOp = ISD::ZERO_EXTEND; 4226 break; 4227 } 4228 TruncOp = ISD::TRUNCATE; 4229 } 4230 // Promote each of the values to the new type. 4231 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4232 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4233 // Perform the larger operation, then convert back 4234 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4235 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1)); 4236 break; 4237 } 4238 case ISD::UMUL_LOHI: 4239 case ISD::SMUL_LOHI: { 4240 // Promote to a multiply in a wider integer type. 4241 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND 4242 : ISD::SIGN_EXTEND; 4243 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4244 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4245 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2); 4246 4247 auto &DL = DAG.getDataLayout(); 4248 unsigned OriginalSize = OVT.getScalarSizeInBits(); 4249 Tmp2 = DAG.getNode( 4250 ISD::SRL, dl, NVT, Tmp1, 4251 DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT))); 4252 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4253 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2)); 4254 break; 4255 } 4256 case ISD::SELECT: { 4257 unsigned ExtOp, TruncOp; 4258 if (Node->getValueType(0).isVector() || 4259 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) { 4260 ExtOp = ISD::BITCAST; 4261 TruncOp = ISD::BITCAST; 4262 } else if (Node->getValueType(0).isInteger()) { 4263 ExtOp = ISD::ANY_EXTEND; 4264 TruncOp = ISD::TRUNCATE; 4265 } else { 4266 ExtOp = ISD::FP_EXTEND; 4267 TruncOp = ISD::FP_ROUND; 4268 } 4269 Tmp1 = Node->getOperand(0); 4270 // Promote each of the values to the new type. 4271 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4272 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4273 // Perform the larger operation, then round down. 4274 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3); 4275 if (TruncOp != ISD::FP_ROUND) 4276 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1); 4277 else 4278 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1, 4279 DAG.getIntPtrConstant(0, dl)); 4280 Results.push_back(Tmp1); 4281 break; 4282 } 4283 case ISD::VECTOR_SHUFFLE: { 4284 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 4285 4286 // Cast the two input vectors. 4287 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0)); 4288 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1)); 4289 4290 // Convert the shuffle mask to the right # elements. 4291 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask); 4292 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1); 4293 Results.push_back(Tmp1); 4294 break; 4295 } 4296 case ISD::SETCC: { 4297 unsigned ExtOp = ISD::FP_EXTEND; 4298 if (NVT.isInteger()) { 4299 ISD::CondCode CCCode = 4300 cast<CondCodeSDNode>(Node->getOperand(2))->get(); 4301 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4302 } 4303 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4304 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4305 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), 4306 Tmp1, Tmp2, Node->getOperand(2))); 4307 break; 4308 } 4309 case ISD::BR_CC: { 4310 unsigned ExtOp = ISD::FP_EXTEND; 4311 if (NVT.isInteger()) { 4312 ISD::CondCode CCCode = 4313 cast<CondCodeSDNode>(Node->getOperand(1))->get(); 4314 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4315 } 4316 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4317 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3)); 4318 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), 4319 Node->getOperand(0), Node->getOperand(1), 4320 Tmp1, Tmp2, Node->getOperand(4))); 4321 break; 4322 } 4323 case ISD::FADD: 4324 case ISD::FSUB: 4325 case ISD::FMUL: 4326 case ISD::FDIV: 4327 case ISD::FREM: 4328 case ISD::FMINNUM: 4329 case ISD::FMAXNUM: 4330 case ISD::FPOW: 4331 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4332 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4333 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, 4334 Node->getFlags()); 4335 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4336 Tmp3, DAG.getIntPtrConstant(0, dl))); 4337 break; 4338 case ISD::FMA: 4339 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4340 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4341 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2)); 4342 Results.push_back( 4343 DAG.getNode(ISD::FP_ROUND, dl, OVT, 4344 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3), 4345 DAG.getIntPtrConstant(0, dl))); 4346 break; 4347 case ISD::FCOPYSIGN: 4348 case ISD::FPOWI: { 4349 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4350 Tmp2 = Node->getOperand(1); 4351 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4352 4353 // fcopysign doesn't change anything but the sign bit, so 4354 // (fp_round (fcopysign (fpext a), b)) 4355 // is as precise as 4356 // (fp_round (fpext a)) 4357 // which is a no-op. Mark it as a TRUNCating FP_ROUND. 4358 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN); 4359 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4360 Tmp3, DAG.getIntPtrConstant(isTrunc, dl))); 4361 break; 4362 } 4363 case ISD::FFLOOR: 4364 case ISD::FCEIL: 4365 case ISD::FRINT: 4366 case ISD::FNEARBYINT: 4367 case ISD::FROUND: 4368 case ISD::FTRUNC: 4369 case ISD::FNEG: 4370 case ISD::FSQRT: 4371 case ISD::FSIN: 4372 case ISD::FCOS: 4373 case ISD::FLOG: 4374 case ISD::FLOG2: 4375 case ISD::FLOG10: 4376 case ISD::FABS: 4377 case ISD::FEXP: 4378 case ISD::FEXP2: 4379 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4380 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4381 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4382 Tmp2, DAG.getIntPtrConstant(0, dl))); 4383 break; 4384 case ISD::BUILD_VECTOR: { 4385 MVT EltVT = OVT.getVectorElementType(); 4386 MVT NewEltVT = NVT.getVectorElementType(); 4387 4388 // Handle bitcasts to a different vector type with the same total bit size 4389 // 4390 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32 4391 // => 4392 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y)) 4393 4394 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4395 "Invalid promote type for build_vector"); 4396 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4397 4398 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4399 4400 SmallVector<SDValue, 8> NewOps; 4401 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) { 4402 SDValue Op = Node->getOperand(I); 4403 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op)); 4404 } 4405 4406 SDLoc SL(Node); 4407 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps); 4408 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4409 Results.push_back(CvtVec); 4410 break; 4411 } 4412 case ISD::EXTRACT_VECTOR_ELT: { 4413 MVT EltVT = OVT.getVectorElementType(); 4414 MVT NewEltVT = NVT.getVectorElementType(); 4415 4416 // Handle bitcasts to a different vector type with the same total bit size. 4417 // 4418 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32 4419 // => 4420 // v4i32:castx = bitcast x:v2i64 4421 // 4422 // i64 = bitcast 4423 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))), 4424 // (i32 (extract_vector_elt castx, (2 * y + 1))) 4425 // 4426 4427 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4428 "Invalid promote type for extract_vector_elt"); 4429 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4430 4431 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4432 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4433 4434 SDValue Idx = Node->getOperand(1); 4435 EVT IdxVT = Idx.getValueType(); 4436 SDLoc SL(Node); 4437 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT); 4438 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4439 4440 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4441 4442 SmallVector<SDValue, 8> NewOps; 4443 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4444 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4445 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4446 4447 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4448 CastVec, TmpIdx); 4449 NewOps.push_back(Elt); 4450 } 4451 4452 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps); 4453 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec)); 4454 break; 4455 } 4456 case ISD::INSERT_VECTOR_ELT: { 4457 MVT EltVT = OVT.getVectorElementType(); 4458 MVT NewEltVT = NVT.getVectorElementType(); 4459 4460 // Handle bitcasts to a different vector type with the same total bit size 4461 // 4462 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32 4463 // => 4464 // v4i32:castx = bitcast x:v2i64 4465 // v2i32:casty = bitcast y:i64 4466 // 4467 // v2i64 = bitcast 4468 // (v4i32 insert_vector_elt 4469 // (v4i32 insert_vector_elt v4i32:castx, 4470 // (extract_vector_elt casty, 0), 2 * z), 4471 // (extract_vector_elt casty, 1), (2 * z + 1)) 4472 4473 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4474 "Invalid promote type for insert_vector_elt"); 4475 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4476 4477 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4478 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4479 4480 SDValue Val = Node->getOperand(1); 4481 SDValue Idx = Node->getOperand(2); 4482 EVT IdxVT = Idx.getValueType(); 4483 SDLoc SL(Node); 4484 4485 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT); 4486 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4487 4488 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4489 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4490 4491 SDValue NewVec = CastVec; 4492 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4493 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4494 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4495 4496 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4497 CastVal, IdxOffset); 4498 4499 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT, 4500 NewVec, Elt, InEltIdx); 4501 } 4502 4503 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec)); 4504 break; 4505 } 4506 case ISD::SCALAR_TO_VECTOR: { 4507 MVT EltVT = OVT.getVectorElementType(); 4508 MVT NewEltVT = NVT.getVectorElementType(); 4509 4510 // Handle bitcasts to different vector type with the same total bit size. 4511 // 4512 // e.g. v2i64 = scalar_to_vector x:i64 4513 // => 4514 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef) 4515 // 4516 4517 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4518 SDValue Val = Node->getOperand(0); 4519 SDLoc SL(Node); 4520 4521 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4522 SDValue Undef = DAG.getUNDEF(MidVT); 4523 4524 SmallVector<SDValue, 8> NewElts; 4525 NewElts.push_back(CastVal); 4526 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I) 4527 NewElts.push_back(Undef); 4528 4529 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts); 4530 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4531 Results.push_back(CvtVec); 4532 break; 4533 } 4534 case ISD::ATOMIC_SWAP: { 4535 AtomicSDNode *AM = cast<AtomicSDNode>(Node); 4536 SDLoc SL(Node); 4537 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal()); 4538 assert(NVT.getSizeInBits() == OVT.getSizeInBits() && 4539 "unexpected promotion type"); 4540 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() && 4541 "unexpected atomic_swap with illegal type"); 4542 4543 SDValue NewAtomic 4544 = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT, 4545 DAG.getVTList(NVT, MVT::Other), 4546 { AM->getChain(), AM->getBasePtr(), CastVal }, 4547 AM->getMemOperand()); 4548 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic)); 4549 Results.push_back(NewAtomic.getValue(1)); 4550 break; 4551 } 4552 } 4553 4554 // Replace the original node with the legalized result. 4555 if (!Results.empty()) { 4556 LLVM_DEBUG(dbgs() << "Successfully promoted node\n"); 4557 ReplaceNode(Node, Results.data()); 4558 } else 4559 LLVM_DEBUG(dbgs() << "Could not promote node\n"); 4560 } 4561 4562 /// This is the entry point for the file. 4563 void SelectionDAG::Legalize() { 4564 AssignTopologicalOrder(); 4565 4566 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4567 // Use a delete listener to remove nodes which were deleted during 4568 // legalization from LegalizeNodes. This is needed to handle the situation 4569 // where a new node is allocated by the object pool to the same address of a 4570 // previously deleted node. 4571 DAGNodeDeletedListener DeleteListener( 4572 *this, 4573 [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); }); 4574 4575 SelectionDAGLegalize Legalizer(*this, LegalizedNodes); 4576 4577 // Visit all the nodes. We start in topological order, so that we see 4578 // nodes with their original operands intact. Legalization can produce 4579 // new nodes which may themselves need to be legalized. Iterate until all 4580 // nodes have been legalized. 4581 while (true) { 4582 bool AnyLegalized = false; 4583 for (auto NI = allnodes_end(); NI != allnodes_begin();) { 4584 --NI; 4585 4586 SDNode *N = &*NI; 4587 if (N->use_empty() && N != getRoot().getNode()) { 4588 ++NI; 4589 DeleteNode(N); 4590 continue; 4591 } 4592 4593 if (LegalizedNodes.insert(N).second) { 4594 AnyLegalized = true; 4595 Legalizer.LegalizeOp(N); 4596 4597 if (N->use_empty() && N != getRoot().getNode()) { 4598 ++NI; 4599 DeleteNode(N); 4600 } 4601 } 4602 } 4603 if (!AnyLegalized) 4604 break; 4605 4606 } 4607 4608 // Remove dead nodes now. 4609 RemoveDeadNodes(); 4610 } 4611 4612 bool SelectionDAG::LegalizeOp(SDNode *N, 4613 SmallSetVector<SDNode *, 16> &UpdatedNodes) { 4614 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4615 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes); 4616 4617 // Directly insert the node in question, and legalize it. This will recurse 4618 // as needed through operands. 4619 LegalizedNodes.insert(N); 4620 Legalizer.LegalizeOp(N); 4621 4622 return LegalizedNodes.count(N); 4623 } 4624