1 //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines several CodeGen-specific LLVM IR analysis utilities. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/Analysis.h" 15 #include "llvm/Analysis/ValueTracking.h" 16 #include "llvm/CodeGen/MachineFunction.h" 17 #include "llvm/CodeGen/SelectionDAG.h" 18 #include "llvm/IR/DataLayout.h" 19 #include "llvm/IR/DerivedTypes.h" 20 #include "llvm/IR/Function.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/LLVMContext.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Target/TargetLowering.h" 28 #include "llvm/Target/TargetSubtargetInfo.h" 29 #include "llvm/Transforms/Utils/GlobalStatus.h" 30 31 using namespace llvm; 32 33 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence 34 /// of insertvalue or extractvalue indices that identify a member, return 35 /// the linearized index of the start of the member. 36 /// 37 unsigned llvm::ComputeLinearIndex(Type *Ty, 38 const unsigned *Indices, 39 const unsigned *IndicesEnd, 40 unsigned CurIndex) { 41 // Base case: We're done. 42 if (Indices && Indices == IndicesEnd) 43 return CurIndex; 44 45 // Given a struct type, recursively traverse the elements. 46 if (StructType *STy = dyn_cast<StructType>(Ty)) { 47 for (StructType::element_iterator EB = STy->element_begin(), 48 EI = EB, 49 EE = STy->element_end(); 50 EI != EE; ++EI) { 51 if (Indices && *Indices == unsigned(EI - EB)) 52 return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex); 53 CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex); 54 } 55 return CurIndex; 56 } 57 // Given an array type, recursively traverse the elements. 58 else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 59 Type *EltTy = ATy->getElementType(); 60 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) { 61 if (Indices && *Indices == i) 62 return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex); 63 CurIndex = ComputeLinearIndex(EltTy, nullptr, nullptr, CurIndex); 64 } 65 return CurIndex; 66 } 67 // We haven't found the type we're looking for, so keep searching. 68 return CurIndex + 1; 69 } 70 71 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of 72 /// EVTs that represent all the individual underlying 73 /// non-aggregate types that comprise it. 74 /// 75 /// If Offsets is non-null, it points to a vector to be filled in 76 /// with the in-memory offsets of each of the individual values. 77 /// 78 void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty, 79 SmallVectorImpl<EVT> &ValueVTs, 80 SmallVectorImpl<uint64_t> *Offsets, 81 uint64_t StartingOffset) { 82 // Given a struct type, recursively traverse the elements. 83 if (StructType *STy = dyn_cast<StructType>(Ty)) { 84 const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy); 85 for (StructType::element_iterator EB = STy->element_begin(), 86 EI = EB, 87 EE = STy->element_end(); 88 EI != EE; ++EI) 89 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets, 90 StartingOffset + SL->getElementOffset(EI - EB)); 91 return; 92 } 93 // Given an array type, recursively traverse the elements. 94 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 95 Type *EltTy = ATy->getElementType(); 96 uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy); 97 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) 98 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets, 99 StartingOffset + i * EltSize); 100 return; 101 } 102 // Interpret void as zero return values. 103 if (Ty->isVoidTy()) 104 return; 105 // Base case: we can get an EVT for this LLVM IR type. 106 ValueVTs.push_back(TLI.getValueType(Ty)); 107 if (Offsets) 108 Offsets->push_back(StartingOffset); 109 } 110 111 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V. 112 GlobalValue *llvm::ExtractTypeInfo(Value *V) { 113 V = V->stripPointerCasts(); 114 GlobalValue *GV = dyn_cast<GlobalValue>(V); 115 GlobalVariable *Var = dyn_cast<GlobalVariable>(V); 116 117 if (Var && Var->getName() == "llvm.eh.catch.all.value") { 118 assert(Var->hasInitializer() && 119 "The EH catch-all value must have an initializer"); 120 Value *Init = Var->getInitializer(); 121 GV = dyn_cast<GlobalValue>(Init); 122 if (!GV) V = cast<ConstantPointerNull>(Init); 123 } 124 125 assert((GV || isa<ConstantPointerNull>(V)) && 126 "TypeInfo must be a global variable or NULL"); 127 return GV; 128 } 129 130 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being 131 /// processed uses a memory 'm' constraint. 132 bool 133 llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos, 134 const TargetLowering &TLI) { 135 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) { 136 InlineAsm::ConstraintInfo &CI = CInfos[i]; 137 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) { 138 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]); 139 if (CType == TargetLowering::C_Memory) 140 return true; 141 } 142 143 // Indirect operand accesses access memory. 144 if (CI.isIndirect) 145 return true; 146 } 147 148 return false; 149 } 150 151 /// getFCmpCondCode - Return the ISD condition code corresponding to 152 /// the given LLVM IR floating-point condition code. This includes 153 /// consideration of global floating-point math flags. 154 /// 155 ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) { 156 switch (Pred) { 157 case FCmpInst::FCMP_FALSE: return ISD::SETFALSE; 158 case FCmpInst::FCMP_OEQ: return ISD::SETOEQ; 159 case FCmpInst::FCMP_OGT: return ISD::SETOGT; 160 case FCmpInst::FCMP_OGE: return ISD::SETOGE; 161 case FCmpInst::FCMP_OLT: return ISD::SETOLT; 162 case FCmpInst::FCMP_OLE: return ISD::SETOLE; 163 case FCmpInst::FCMP_ONE: return ISD::SETONE; 164 case FCmpInst::FCMP_ORD: return ISD::SETO; 165 case FCmpInst::FCMP_UNO: return ISD::SETUO; 166 case FCmpInst::FCMP_UEQ: return ISD::SETUEQ; 167 case FCmpInst::FCMP_UGT: return ISD::SETUGT; 168 case FCmpInst::FCMP_UGE: return ISD::SETUGE; 169 case FCmpInst::FCMP_ULT: return ISD::SETULT; 170 case FCmpInst::FCMP_ULE: return ISD::SETULE; 171 case FCmpInst::FCMP_UNE: return ISD::SETUNE; 172 case FCmpInst::FCMP_TRUE: return ISD::SETTRUE; 173 default: llvm_unreachable("Invalid FCmp predicate opcode!"); 174 } 175 } 176 177 ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) { 178 switch (CC) { 179 case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ; 180 case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE; 181 case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT; 182 case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE; 183 case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT; 184 case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE; 185 default: return CC; 186 } 187 } 188 189 /// getICmpCondCode - Return the ISD condition code corresponding to 190 /// the given LLVM IR integer condition code. 191 /// 192 ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) { 193 switch (Pred) { 194 case ICmpInst::ICMP_EQ: return ISD::SETEQ; 195 case ICmpInst::ICMP_NE: return ISD::SETNE; 196 case ICmpInst::ICMP_SLE: return ISD::SETLE; 197 case ICmpInst::ICMP_ULE: return ISD::SETULE; 198 case ICmpInst::ICMP_SGE: return ISD::SETGE; 199 case ICmpInst::ICMP_UGE: return ISD::SETUGE; 200 case ICmpInst::ICMP_SLT: return ISD::SETLT; 201 case ICmpInst::ICMP_ULT: return ISD::SETULT; 202 case ICmpInst::ICMP_SGT: return ISD::SETGT; 203 case ICmpInst::ICMP_UGT: return ISD::SETUGT; 204 default: 205 llvm_unreachable("Invalid ICmp predicate opcode!"); 206 } 207 } 208 209 static bool isNoopBitcast(Type *T1, Type *T2, 210 const TargetLoweringBase& TLI) { 211 return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) || 212 (isa<VectorType>(T1) && isa<VectorType>(T2) && 213 TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2))); 214 } 215 216 /// Look through operations that will be free to find the earliest source of 217 /// this value. 218 /// 219 /// @param ValLoc If V has aggegate type, we will be interested in a particular 220 /// scalar component. This records its address; the reverse of this list gives a 221 /// sequence of indices appropriate for an extractvalue to locate the important 222 /// value. This value is updated during the function and on exit will indicate 223 /// similar information for the Value returned. 224 /// 225 /// @param DataBits If this function looks through truncate instructions, this 226 /// will record the smallest size attained. 227 static const Value *getNoopInput(const Value *V, 228 SmallVectorImpl<unsigned> &ValLoc, 229 unsigned &DataBits, 230 const TargetLoweringBase &TLI) { 231 while (true) { 232 // Try to look through V1; if V1 is not an instruction, it can't be looked 233 // through. 234 const Instruction *I = dyn_cast<Instruction>(V); 235 if (!I || I->getNumOperands() == 0) return V; 236 const Value *NoopInput = nullptr; 237 238 Value *Op = I->getOperand(0); 239 if (isa<BitCastInst>(I)) { 240 // Look through truly no-op bitcasts. 241 if (isNoopBitcast(Op->getType(), I->getType(), TLI)) 242 NoopInput = Op; 243 } else if (isa<GetElementPtrInst>(I)) { 244 // Look through getelementptr 245 if (cast<GetElementPtrInst>(I)->hasAllZeroIndices()) 246 NoopInput = Op; 247 } else if (isa<IntToPtrInst>(I)) { 248 // Look through inttoptr. 249 // Make sure this isn't a truncating or extending cast. We could 250 // support this eventually, but don't bother for now. 251 if (!isa<VectorType>(I->getType()) && 252 TLI.getPointerTy().getSizeInBits() == 253 cast<IntegerType>(Op->getType())->getBitWidth()) 254 NoopInput = Op; 255 } else if (isa<PtrToIntInst>(I)) { 256 // Look through ptrtoint. 257 // Make sure this isn't a truncating or extending cast. We could 258 // support this eventually, but don't bother for now. 259 if (!isa<VectorType>(I->getType()) && 260 TLI.getPointerTy().getSizeInBits() == 261 cast<IntegerType>(I->getType())->getBitWidth()) 262 NoopInput = Op; 263 } else if (isa<TruncInst>(I) && 264 TLI.allowTruncateForTailCall(Op->getType(), I->getType())) { 265 DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits()); 266 NoopInput = Op; 267 } else if (isa<CallInst>(I)) { 268 // Look through call (skipping callee) 269 for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1; 270 i != e; ++i) { 271 unsigned attrInd = i - I->op_begin() + 1; 272 if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) && 273 isNoopBitcast((*i)->getType(), I->getType(), TLI)) { 274 NoopInput = *i; 275 break; 276 } 277 } 278 } else if (isa<InvokeInst>(I)) { 279 // Look through invoke (skipping BB, BB, Callee) 280 for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3; 281 i != e; ++i) { 282 unsigned attrInd = i - I->op_begin() + 1; 283 if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) && 284 isNoopBitcast((*i)->getType(), I->getType(), TLI)) { 285 NoopInput = *i; 286 break; 287 } 288 } 289 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) { 290 // Value may come from either the aggregate or the scalar 291 ArrayRef<unsigned> InsertLoc = IVI->getIndices(); 292 if (std::equal(InsertLoc.rbegin(), InsertLoc.rend(), 293 ValLoc.rbegin())) { 294 // The type being inserted is a nested sub-type of the aggregate; we 295 // have to remove those initial indices to get the location we're 296 // interested in for the operand. 297 ValLoc.resize(ValLoc.size() - InsertLoc.size()); 298 NoopInput = IVI->getInsertedValueOperand(); 299 } else { 300 // The struct we're inserting into has the value we're interested in, no 301 // change of address. 302 NoopInput = Op; 303 } 304 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) { 305 // The part we're interested in will inevitably be some sub-section of the 306 // previous aggregate. Combine the two paths to obtain the true address of 307 // our element. 308 ArrayRef<unsigned> ExtractLoc = EVI->getIndices(); 309 std::copy(ExtractLoc.rbegin(), ExtractLoc.rend(), 310 std::back_inserter(ValLoc)); 311 NoopInput = Op; 312 } 313 // Terminate if we couldn't find anything to look through. 314 if (!NoopInput) 315 return V; 316 317 V = NoopInput; 318 } 319 } 320 321 /// Return true if this scalar return value only has bits discarded on its path 322 /// from the "tail call" to the "ret". This includes the obvious noop 323 /// instructions handled by getNoopInput above as well as free truncations (or 324 /// extensions prior to the call). 325 static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal, 326 SmallVectorImpl<unsigned> &RetIndices, 327 SmallVectorImpl<unsigned> &CallIndices, 328 bool AllowDifferingSizes, 329 const TargetLoweringBase &TLI) { 330 331 // Trace the sub-value needed by the return value as far back up the graph as 332 // possible, in the hope that it will intersect with the value produced by the 333 // call. In the simple case with no "returned" attribute, the hope is actually 334 // that we end up back at the tail call instruction itself. 335 unsigned BitsRequired = UINT_MAX; 336 RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI); 337 338 // If this slot in the value returned is undef, it doesn't matter what the 339 // call puts there, it'll be fine. 340 if (isa<UndefValue>(RetVal)) 341 return true; 342 343 // Now do a similar search up through the graph to find where the value 344 // actually returned by the "tail call" comes from. In the simple case without 345 // a "returned" attribute, the search will be blocked immediately and the loop 346 // a Noop. 347 unsigned BitsProvided = UINT_MAX; 348 CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI); 349 350 // There's no hope if we can't actually trace them to (the same part of!) the 351 // same value. 352 if (CallVal != RetVal || CallIndices != RetIndices) 353 return false; 354 355 // However, intervening truncates may have made the call non-tail. Make sure 356 // all the bits that are needed by the "ret" have been provided by the "tail 357 // call". FIXME: with sufficiently cunning bit-tracking, we could look through 358 // extensions too. 359 if (BitsProvided < BitsRequired || 360 (!AllowDifferingSizes && BitsProvided != BitsRequired)) 361 return false; 362 363 return true; 364 } 365 366 /// For an aggregate type, determine whether a given index is within bounds or 367 /// not. 368 static bool indexReallyValid(CompositeType *T, unsigned Idx) { 369 if (ArrayType *AT = dyn_cast<ArrayType>(T)) 370 return Idx < AT->getNumElements(); 371 372 return Idx < cast<StructType>(T)->getNumElements(); 373 } 374 375 /// Move the given iterators to the next leaf type in depth first traversal. 376 /// 377 /// Performs a depth-first traversal of the type as specified by its arguments, 378 /// stopping at the next leaf node (which may be a legitimate scalar type or an 379 /// empty struct or array). 380 /// 381 /// @param SubTypes List of the partial components making up the type from 382 /// outermost to innermost non-empty aggregate. The element currently 383 /// represented is SubTypes.back()->getTypeAtIndex(Path.back() - 1). 384 /// 385 /// @param Path Set of extractvalue indices leading from the outermost type 386 /// (SubTypes[0]) to the leaf node currently represented. 387 /// 388 /// @returns true if a new type was found, false otherwise. Calling this 389 /// function again on a finished iterator will repeatedly return 390 /// false. SubTypes.back()->getTypeAtIndex(Path.back()) is either an empty 391 /// aggregate or a non-aggregate 392 static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes, 393 SmallVectorImpl<unsigned> &Path) { 394 // First march back up the tree until we can successfully increment one of the 395 // coordinates in Path. 396 while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) { 397 Path.pop_back(); 398 SubTypes.pop_back(); 399 } 400 401 // If we reached the top, then the iterator is done. 402 if (Path.empty()) 403 return false; 404 405 // We know there's *some* valid leaf now, so march back down the tree picking 406 // out the left-most element at each node. 407 ++Path.back(); 408 Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back()); 409 while (DeeperType->isAggregateType()) { 410 CompositeType *CT = cast<CompositeType>(DeeperType); 411 if (!indexReallyValid(CT, 0)) 412 return true; 413 414 SubTypes.push_back(CT); 415 Path.push_back(0); 416 417 DeeperType = CT->getTypeAtIndex(0U); 418 } 419 420 return true; 421 } 422 423 /// Find the first non-empty, scalar-like type in Next and setup the iterator 424 /// components. 425 /// 426 /// Assuming Next is an aggregate of some kind, this function will traverse the 427 /// tree from left to right (i.e. depth-first) looking for the first 428 /// non-aggregate type which will play a role in function return. 429 /// 430 /// For example, if Next was {[0 x i64], {{}, i32, {}}, i32} then we would setup 431 /// Path as [1, 1] and SubTypes as [Next, {{}, i32, {}}] to represent the first 432 /// i32 in that type. 433 static bool firstRealType(Type *Next, 434 SmallVectorImpl<CompositeType *> &SubTypes, 435 SmallVectorImpl<unsigned> &Path) { 436 // First initialise the iterator components to the first "leaf" node 437 // (i.e. node with no valid sub-type at any index, so {} does count as a leaf 438 // despite nominally being an aggregate). 439 while (Next->isAggregateType() && 440 indexReallyValid(cast<CompositeType>(Next), 0)) { 441 SubTypes.push_back(cast<CompositeType>(Next)); 442 Path.push_back(0); 443 Next = cast<CompositeType>(Next)->getTypeAtIndex(0U); 444 } 445 446 // If there's no Path now, Next was originally scalar already (or empty 447 // leaf). We're done. 448 if (Path.empty()) 449 return true; 450 451 // Otherwise, use normal iteration to keep looking through the tree until we 452 // find a non-aggregate type. 453 while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) { 454 if (!advanceToNextLeafType(SubTypes, Path)) 455 return false; 456 } 457 458 return true; 459 } 460 461 /// Set the iterator data-structures to the next non-empty, non-aggregate 462 /// subtype. 463 static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes, 464 SmallVectorImpl<unsigned> &Path) { 465 do { 466 if (!advanceToNextLeafType(SubTypes, Path)) 467 return false; 468 469 assert(!Path.empty() && "found a leaf but didn't set the path?"); 470 } while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()); 471 472 return true; 473 } 474 475 476 /// Test if the given instruction is in a position to be optimized 477 /// with a tail-call. This roughly means that it's in a block with 478 /// a return and there's nothing that needs to be scheduled 479 /// between it and the return. 480 /// 481 /// This function only tests target-independent requirements. 482 bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) { 483 const Instruction *I = CS.getInstruction(); 484 const BasicBlock *ExitBB = I->getParent(); 485 const TerminatorInst *Term = ExitBB->getTerminator(); 486 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term); 487 488 // The block must end in a return statement or unreachable. 489 // 490 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in 491 // an unreachable, for now. The way tailcall optimization is currently 492 // implemented means it will add an epilogue followed by a jump. That is 493 // not profitable. Also, if the callee is a special function (e.g. 494 // longjmp on x86), it can end up causing miscompilation that has not 495 // been fully understood. 496 if (!Ret && 497 (!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) 498 return false; 499 500 // If I will have a chain, make sure no other instruction that will have a 501 // chain interposes between I and the return. 502 if (I->mayHaveSideEffects() || I->mayReadFromMemory() || 503 !isSafeToSpeculativelyExecute(I)) 504 for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) { 505 if (&*BBI == I) 506 break; 507 // Debug info intrinsics do not get in the way of tail call optimization. 508 if (isa<DbgInfoIntrinsic>(BBI)) 509 continue; 510 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() || 511 !isSafeToSpeculativelyExecute(BBI)) 512 return false; 513 } 514 515 return returnTypeIsEligibleForTailCall( 516 ExitBB->getParent(), I, Ret, *TM.getSubtargetImpl()->getTargetLowering()); 517 } 518 519 bool llvm::returnTypeIsEligibleForTailCall(const Function *F, 520 const Instruction *I, 521 const ReturnInst *Ret, 522 const TargetLoweringBase &TLI) { 523 // If the block ends with a void return or unreachable, it doesn't matter 524 // what the call's return type is. 525 if (!Ret || Ret->getNumOperands() == 0) return true; 526 527 // If the return value is undef, it doesn't matter what the call's 528 // return type is. 529 if (isa<UndefValue>(Ret->getOperand(0))) return true; 530 531 // Make sure the attributes attached to each return are compatible. 532 AttrBuilder CallerAttrs(F->getAttributes(), 533 AttributeSet::ReturnIndex); 534 AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(), 535 AttributeSet::ReturnIndex); 536 537 // Noalias is completely benign as far as calling convention goes, it 538 // shouldn't affect whether the call is a tail call. 539 CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias); 540 CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias); 541 542 bool AllowDifferingSizes = true; 543 if (CallerAttrs.contains(Attribute::ZExt)) { 544 if (!CalleeAttrs.contains(Attribute::ZExt)) 545 return false; 546 547 AllowDifferingSizes = false; 548 CallerAttrs.removeAttribute(Attribute::ZExt); 549 CalleeAttrs.removeAttribute(Attribute::ZExt); 550 } else if (CallerAttrs.contains(Attribute::SExt)) { 551 if (!CalleeAttrs.contains(Attribute::SExt)) 552 return false; 553 554 AllowDifferingSizes = false; 555 CallerAttrs.removeAttribute(Attribute::SExt); 556 CalleeAttrs.removeAttribute(Attribute::SExt); 557 } 558 559 // If they're still different, there's some facet we don't understand 560 // (currently only "inreg", but in future who knows). It may be OK but the 561 // only safe option is to reject the tail call. 562 if (CallerAttrs != CalleeAttrs) 563 return false; 564 565 const Value *RetVal = Ret->getOperand(0), *CallVal = I; 566 SmallVector<unsigned, 4> RetPath, CallPath; 567 SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes; 568 569 bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath); 570 bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath); 571 572 // Nothing's actually returned, it doesn't matter what the callee put there 573 // it's a valid tail call. 574 if (RetEmpty) 575 return true; 576 577 // Iterate pairwise through each of the value types making up the tail call 578 // and the corresponding return. For each one we want to know whether it's 579 // essentially going directly from the tail call to the ret, via operations 580 // that end up not generating any code. 581 // 582 // We allow a certain amount of covariance here. For example it's permitted 583 // for the tail call to define more bits than the ret actually cares about 584 // (e.g. via a truncate). 585 do { 586 if (CallEmpty) { 587 // We've exhausted the values produced by the tail call instruction, the 588 // rest are essentially undef. The type doesn't really matter, but we need 589 // *something*. 590 Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back()); 591 CallVal = UndefValue::get(SlotType); 592 } 593 594 // The manipulations performed when we're looking through an insertvalue or 595 // an extractvalue would happen at the front of the RetPath list, so since 596 // we have to copy it anyway it's more efficient to create a reversed copy. 597 using std::copy; 598 SmallVector<unsigned, 4> TmpRetPath, TmpCallPath; 599 copy(RetPath.rbegin(), RetPath.rend(), std::back_inserter(TmpRetPath)); 600 copy(CallPath.rbegin(), CallPath.rend(), std::back_inserter(TmpCallPath)); 601 602 // Finally, we can check whether the value produced by the tail call at this 603 // index is compatible with the value we return. 604 if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath, 605 AllowDifferingSizes, TLI)) 606 return false; 607 608 CallEmpty = !nextRealType(CallSubTypes, CallPath); 609 } while(nextRealType(RetSubTypes, RetPath)); 610 611 return true; 612 } 613 614 bool llvm::canBeOmittedFromSymbolTable(const GlobalValue *GV) { 615 if (!GV->hasLinkOnceODRLinkage()) 616 return false; 617 618 if (GV->hasUnnamedAddr()) 619 return true; 620 621 // If it is a non constant variable, it needs to be uniqued across shared 622 // objects. 623 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) { 624 if (!Var->isConstant()) 625 return false; 626 } 627 628 // An alias can point to a variable. We could try to resolve the alias to 629 // decide, but for now just don't hide them. 630 if (isa<GlobalAlias>(GV)) 631 return false; 632 633 GlobalStatus GS; 634 if (GlobalStatus::analyzeGlobal(GV, GS)) 635 return false; 636 637 return !GS.IsCompared; 638 } 639