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