1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements routines for translating functions from LLVM IR into 11 // Machine IR. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/FunctionLoweringInfo.h" 16 #include "llvm/ADT/PostOrderIterator.h" 17 #include "llvm/CodeGen/Analysis.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineInstrBuilder.h" 21 #include "llvm/CodeGen/MachineModuleInfo.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DebugInfo.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/Instructions.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Target/TargetFrameLowering.h" 35 #include "llvm/Target/TargetInstrInfo.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "function-lowering-info" 44 45 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by 46 /// PHI nodes or outside of the basic block that defines it, or used by a 47 /// switch or atomic instruction, which may expand to multiple basic blocks. 48 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) { 49 if (I->use_empty()) return false; 50 if (isa<PHINode>(I)) return true; 51 const BasicBlock *BB = I->getParent(); 52 for (const User *U : I->users()) 53 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U)) 54 return true; 55 56 return false; 57 } 58 59 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf, 60 SelectionDAG *DAG) { 61 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering(); 62 63 Fn = &fn; 64 MF = &mf; 65 RegInfo = &MF->getRegInfo(); 66 67 // Check whether the function can return without sret-demotion. 68 SmallVector<ISD::OutputArg, 4> Outs; 69 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI); 70 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF, 71 Fn->isVarArg(), 72 Outs, Fn->getContext()); 73 74 // Initialize the mapping of values to registers. This is only set up for 75 // instruction values that are used outside of the block that defines 76 // them. 77 Function::const_iterator BB = Fn->begin(), EB = Fn->end(); 78 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 79 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 80 // Don't fold inalloca allocas or other dynamic allocas into the initial 81 // stack frame allocation, even if they are in the entry block. 82 if (!AI->isStaticAlloca()) 83 continue; 84 85 if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) { 86 Type *Ty = AI->getAllocatedType(); 87 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty); 88 unsigned Align = 89 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty), 90 AI->getAlignment()); 91 92 TySize *= CUI->getZExtValue(); // Get total allocated size. 93 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects. 94 95 StaticAllocaMap[AI] = 96 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI); 97 } 98 } 99 100 for (; BB != EB; ++BB) 101 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 102 I != E; ++I) { 103 // Look for dynamic allocas. 104 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 105 if (!AI->isStaticAlloca()) { 106 unsigned Align = std::max( 107 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment( 108 AI->getAllocatedType()), 109 AI->getAlignment()); 110 unsigned StackAlign = 111 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment(); 112 if (Align <= StackAlign) 113 Align = 0; 114 // Inform the Frame Information that we have variable-sized objects. 115 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI); 116 } 117 } 118 119 // Look for inline asm that clobbers the SP register. 120 if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 121 ImmutableCallSite CS(I); 122 if (isa<InlineAsm>(CS.getCalledValue())) { 123 unsigned SP = TLI->getStackPointerRegisterToSaveRestore(); 124 std::vector<TargetLowering::AsmOperandInfo> Ops = 125 TLI->ParseConstraints(CS); 126 for (size_t I = 0, E = Ops.size(); I != E; ++I) { 127 TargetLowering::AsmOperandInfo &Op = Ops[I]; 128 if (Op.Type == InlineAsm::isClobber) { 129 // Clobbers don't have SDValue operands, hence SDValue(). 130 TLI->ComputeConstraintToUse(Op, SDValue(), DAG); 131 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 132 TLI->getRegForInlineAsmConstraint(Op.ConstraintCode, 133 Op.ConstraintVT); 134 if (PhysReg.first == SP) 135 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true); 136 } 137 } 138 } 139 } 140 141 // Look for calls to the @llvm.va_start intrinsic. We can omit some 142 // prologue boilerplate for variadic functions that don't examine their 143 // arguments. 144 if (const auto *II = dyn_cast<IntrinsicInst>(I)) { 145 if (II->getIntrinsicID() == Intrinsic::vastart) 146 MF->getFrameInfo()->setHasVAStart(true); 147 } 148 149 // Mark values used outside their block as exported, by allocating 150 // a virtual register for them. 151 if (isUsedOutsideOfDefiningBlock(I)) 152 if (!isa<AllocaInst>(I) || 153 !StaticAllocaMap.count(cast<AllocaInst>(I))) 154 InitializeRegForValue(I); 155 156 // Collect llvm.dbg.declare information. This is done now instead of 157 // during the initial isel pass through the IR so that it is done 158 // in a predictable order. 159 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) { 160 MachineModuleInfo &MMI = MF->getMMI(); 161 DIVariable DIVar(DI->getVariable()); 162 assert((!DIVar || DIVar.isVariable()) && 163 "Variable in DbgDeclareInst should be either null or a DIVariable."); 164 if (MMI.hasDebugInfo() && 165 DIVar && 166 !DI->getDebugLoc().isUnknown()) { 167 // Don't handle byval struct arguments or VLAs, for example. 168 // Non-byval arguments are handled here (they refer to the stack 169 // temporary alloca at this point). 170 const Value *Address = DI->getAddress(); 171 if (Address) { 172 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 173 Address = BCI->getOperand(0); 174 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 175 DenseMap<const AllocaInst *, int>::iterator SI = 176 StaticAllocaMap.find(AI); 177 if (SI != StaticAllocaMap.end()) { // Check for VLAs. 178 int FI = SI->second; 179 MMI.setVariableDbgInfo(DI->getVariable(), 180 FI, DI->getDebugLoc()); 181 } 182 } 183 } 184 } 185 } 186 } 187 188 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This 189 // also creates the initial PHI MachineInstrs, though none of the input 190 // operands are populated. 191 for (BB = Fn->begin(); BB != EB; ++BB) { 192 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB); 193 MBBMap[BB] = MBB; 194 MF->push_back(MBB); 195 196 // Transfer the address-taken flag. This is necessary because there could 197 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only 198 // the first one should be marked. 199 if (BB->hasAddressTaken()) 200 MBB->setHasAddressTaken(); 201 202 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as 203 // appropriate. 204 for (BasicBlock::const_iterator I = BB->begin(); 205 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 206 if (PN->use_empty()) continue; 207 208 // Skip empty types 209 if (PN->getType()->isEmptyTy()) 210 continue; 211 212 DebugLoc DL = PN->getDebugLoc(); 213 unsigned PHIReg = ValueMap[PN]; 214 assert(PHIReg && "PHI node does not have an assigned virtual register!"); 215 216 SmallVector<EVT, 4> ValueVTs; 217 ComputeValueVTs(*TLI, PN->getType(), ValueVTs); 218 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 219 EVT VT = ValueVTs[vti]; 220 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT); 221 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 222 for (unsigned i = 0; i != NumRegisters; ++i) 223 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i); 224 PHIReg += NumRegisters; 225 } 226 } 227 } 228 229 // Mark landing pad blocks. 230 for (BB = Fn->begin(); BB != EB; ++BB) 231 if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator())) 232 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad(); 233 } 234 235 /// clear - Clear out all the function-specific state. This returns this 236 /// FunctionLoweringInfo to an empty state, ready to be used for a 237 /// different function. 238 void FunctionLoweringInfo::clear() { 239 assert(CatchInfoFound.size() == CatchInfoLost.size() && 240 "Not all catch info was assigned to a landing pad!"); 241 242 MBBMap.clear(); 243 ValueMap.clear(); 244 StaticAllocaMap.clear(); 245 #ifndef NDEBUG 246 CatchInfoLost.clear(); 247 CatchInfoFound.clear(); 248 #endif 249 LiveOutRegInfo.clear(); 250 VisitedBBs.clear(); 251 ArgDbgValues.clear(); 252 ByValArgFrameIndexMap.clear(); 253 RegFixups.clear(); 254 } 255 256 /// CreateReg - Allocate a single virtual register for the given type. 257 unsigned FunctionLoweringInfo::CreateReg(MVT VT) { 258 return RegInfo->createVirtualRegister( 259 TM.getSubtargetImpl()->getTargetLowering()->getRegClassFor(VT)); 260 } 261 262 /// CreateRegs - Allocate the appropriate number of virtual registers of 263 /// the correctly promoted or expanded types. Assign these registers 264 /// consecutive vreg numbers and return the first assigned number. 265 /// 266 /// In the case that the given value has struct or array type, this function 267 /// will assign registers for each member or element. 268 /// 269 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) { 270 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering(); 271 272 SmallVector<EVT, 4> ValueVTs; 273 ComputeValueVTs(*TLI, Ty, ValueVTs); 274 275 unsigned FirstReg = 0; 276 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 277 EVT ValueVT = ValueVTs[Value]; 278 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT); 279 280 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT); 281 for (unsigned i = 0; i != NumRegs; ++i) { 282 unsigned R = CreateReg(RegisterVT); 283 if (!FirstReg) FirstReg = R; 284 } 285 } 286 return FirstReg; 287 } 288 289 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the 290 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If 291 /// the register's LiveOutInfo is for a smaller bit width, it is extended to 292 /// the larger bit width by zero extension. The bit width must be no smaller 293 /// than the LiveOutInfo's existing bit width. 294 const FunctionLoweringInfo::LiveOutInfo * 295 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) { 296 if (!LiveOutRegInfo.inBounds(Reg)) 297 return nullptr; 298 299 LiveOutInfo *LOI = &LiveOutRegInfo[Reg]; 300 if (!LOI->IsValid) 301 return nullptr; 302 303 if (BitWidth > LOI->KnownZero.getBitWidth()) { 304 LOI->NumSignBits = 1; 305 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth); 306 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth); 307 } 308 309 return LOI; 310 } 311 312 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination 313 /// register based on the LiveOutInfo of its operands. 314 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) { 315 Type *Ty = PN->getType(); 316 if (!Ty->isIntegerTy() || Ty->isVectorTy()) 317 return; 318 319 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering(); 320 321 SmallVector<EVT, 1> ValueVTs; 322 ComputeValueVTs(*TLI, Ty, ValueVTs); 323 assert(ValueVTs.size() == 1 && 324 "PHIs with non-vector integer types should have a single VT."); 325 EVT IntVT = ValueVTs[0]; 326 327 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1) 328 return; 329 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT); 330 unsigned BitWidth = IntVT.getSizeInBits(); 331 332 unsigned DestReg = ValueMap[PN]; 333 if (!TargetRegisterInfo::isVirtualRegister(DestReg)) 334 return; 335 LiveOutRegInfo.grow(DestReg); 336 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg]; 337 338 Value *V = PN->getIncomingValue(0); 339 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) { 340 DestLOI.NumSignBits = 1; 341 APInt Zero(BitWidth, 0); 342 DestLOI.KnownZero = Zero; 343 DestLOI.KnownOne = Zero; 344 return; 345 } 346 347 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 348 APInt Val = CI->getValue().zextOrTrunc(BitWidth); 349 DestLOI.NumSignBits = Val.getNumSignBits(); 350 DestLOI.KnownZero = ~Val; 351 DestLOI.KnownOne = Val; 352 } else { 353 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its" 354 "CopyToReg node was created."); 355 unsigned SrcReg = ValueMap[V]; 356 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) { 357 DestLOI.IsValid = false; 358 return; 359 } 360 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth); 361 if (!SrcLOI) { 362 DestLOI.IsValid = false; 363 return; 364 } 365 DestLOI = *SrcLOI; 366 } 367 368 assert(DestLOI.KnownZero.getBitWidth() == BitWidth && 369 DestLOI.KnownOne.getBitWidth() == BitWidth && 370 "Masks should have the same bit width as the type."); 371 372 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) { 373 Value *V = PN->getIncomingValue(i); 374 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) { 375 DestLOI.NumSignBits = 1; 376 APInt Zero(BitWidth, 0); 377 DestLOI.KnownZero = Zero; 378 DestLOI.KnownOne = Zero; 379 return; 380 } 381 382 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 383 APInt Val = CI->getValue().zextOrTrunc(BitWidth); 384 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits()); 385 DestLOI.KnownZero &= ~Val; 386 DestLOI.KnownOne &= Val; 387 continue; 388 } 389 390 assert(ValueMap.count(V) && "V should have been placed in ValueMap when " 391 "its CopyToReg node was created."); 392 unsigned SrcReg = ValueMap[V]; 393 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) { 394 DestLOI.IsValid = false; 395 return; 396 } 397 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth); 398 if (!SrcLOI) { 399 DestLOI.IsValid = false; 400 return; 401 } 402 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits); 403 DestLOI.KnownZero &= SrcLOI->KnownZero; 404 DestLOI.KnownOne &= SrcLOI->KnownOne; 405 } 406 } 407 408 /// setArgumentFrameIndex - Record frame index for the byval 409 /// argument. This overrides previous frame index entry for this argument, 410 /// if any. 411 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A, 412 int FI) { 413 ByValArgFrameIndexMap[A] = FI; 414 } 415 416 /// getArgumentFrameIndex - Get frame index for the byval argument. 417 /// If the argument does not have any assigned frame index then 0 is 418 /// returned. 419 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) { 420 DenseMap<const Argument *, int>::iterator I = 421 ByValArgFrameIndexMap.find(A); 422 if (I != ByValArgFrameIndexMap.end()) 423 return I->second; 424 DEBUG(dbgs() << "Argument does not have assigned frame index!\n"); 425 return 0; 426 } 427 428 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are 429 /// being passed to this variadic function, and set the MachineModuleInfo's 430 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined 431 /// reference to _fltused on Windows, which will link in MSVCRT's 432 /// floating-point support. 433 void llvm::ComputeUsesVAFloatArgument(const CallInst &I, 434 MachineModuleInfo *MMI) 435 { 436 FunctionType *FT = cast<FunctionType>( 437 I.getCalledValue()->getType()->getContainedType(0)); 438 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) { 439 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 440 Type* T = I.getArgOperand(i)->getType(); 441 for (po_iterator<Type*> i = po_begin(T), e = po_end(T); 442 i != e; ++i) { 443 if (i->isFloatingPointTy()) { 444 MMI->setUsesVAFloatArgument(true); 445 return; 446 } 447 } 448 } 449 } 450 } 451 452 /// AddCatchInfo - Extract the personality and type infos from an eh.selector 453 /// call, and add them to the specified machine basic block. 454 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI, 455 MachineBasicBlock *MBB) { 456 // Inform the MachineModuleInfo of the personality for this landing pad. 457 const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1)); 458 assert(CE->getOpcode() == Instruction::BitCast && 459 isa<Function>(CE->getOperand(0)) && 460 "Personality should be a function"); 461 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0))); 462 463 // Gather all the type infos for this landing pad and pass them along to 464 // MachineModuleInfo. 465 std::vector<const GlobalVariable *> TyInfo; 466 unsigned N = I.getNumArgOperands(); 467 468 for (unsigned i = N - 1; i > 1; --i) { 469 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) { 470 unsigned FilterLength = CI->getZExtValue(); 471 unsigned FirstCatch = i + FilterLength + !FilterLength; 472 assert(FirstCatch <= N && "Invalid filter length"); 473 474 if (FirstCatch < N) { 475 TyInfo.reserve(N - FirstCatch); 476 for (unsigned j = FirstCatch; j < N; ++j) 477 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j))); 478 MMI->addCatchTypeInfo(MBB, TyInfo); 479 TyInfo.clear(); 480 } 481 482 if (!FilterLength) { 483 // Cleanup. 484 MMI->addCleanup(MBB); 485 } else { 486 // Filter. 487 TyInfo.reserve(FilterLength - 1); 488 for (unsigned j = i + 1; j < FirstCatch; ++j) 489 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j))); 490 MMI->addFilterTypeInfo(MBB, TyInfo); 491 TyInfo.clear(); 492 } 493 494 N = i; 495 } 496 } 497 498 if (N > 2) { 499 TyInfo.reserve(N - 2); 500 for (unsigned j = 2; j < N; ++j) 501 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j))); 502 MMI->addCatchTypeInfo(MBB, TyInfo); 503 } 504 } 505 506 /// AddLandingPadInfo - Extract the exception handling information from the 507 /// landingpad instruction and add them to the specified machine module info. 508 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI, 509 MachineBasicBlock *MBB) { 510 MMI.addPersonality(MBB, 511 cast<Function>(I.getPersonalityFn()->stripPointerCasts())); 512 513 if (I.isCleanup()) 514 MMI.addCleanup(MBB); 515 516 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct, 517 // but we need to do it this way because of how the DWARF EH emitter 518 // processes the clauses. 519 for (unsigned i = I.getNumClauses(); i != 0; --i) { 520 Value *Val = I.getClause(i - 1); 521 if (I.isCatch(i - 1)) { 522 MMI.addCatchTypeInfo(MBB, 523 dyn_cast<GlobalVariable>(Val->stripPointerCasts())); 524 } else { 525 // Add filters in a list. 526 Constant *CVal = cast<Constant>(Val); 527 SmallVector<const GlobalVariable*, 4> FilterList; 528 for (User::op_iterator 529 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II) 530 FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts())); 531 532 MMI.addFilterTypeInfo(MBB, FilterList); 533 } 534 } 535 } 536