1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating functions from LLVM IR into
13 //===----------------------------------------------------------------------===//
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/CodeGen/WinEHFuncInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DebugInfo.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/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "function-lowering-info"
47 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
48 /// PHI nodes or outside of the basic block that defines it, or used by a
49 /// switch or atomic instruction, which may expand to multiple basic blocks.
50 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
51 if (I->use_empty()) return false;
52 if (isa<PHINode>(I)) return true;
53 const BasicBlock *BB = I->getParent();
54 for (const User *U : I->users())
55 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
61 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
62 // For the users of the source value being used for compare instruction, if
63 // the number of signed predicate is greater than unsigned predicate, we
64 // prefer to use SIGN_EXTEND.
66 // With this optimization, we would be able to reduce some redundant sign or
67 // zero extension instruction, and eventually more machine CSE opportunities
69 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
70 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
71 for (const User *U : V->users()) {
72 if (const auto *CI = dyn_cast<CmpInst>(U)) {
73 NumOfSigned += CI->isSigned();
74 NumOfUnsigned += CI->isUnsigned();
77 if (NumOfSigned > NumOfUnsigned)
78 ExtendKind = ISD::SIGN_EXTEND;
84 struct WinEHNumbering {
85 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
86 CurrentBaseState(-1), NextState(0) {}
88 WinEHFuncInfo &FuncInfo;
92 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
93 SmallPtrSet<const Function *, 4> VisitedHandlers;
95 int currentEHNumber() const {
96 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
99 void createUnwindMapEntry(int ToState, ActionHandler *AH);
100 void createTryBlockMapEntry(int TryLow, int TryHigh,
101 ArrayRef<CatchHandler *> Handlers);
102 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
103 ImmutableCallSite CS);
104 void calculateStateNumbers(const Function &F);
108 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
112 TLI = MF->getSubtarget().getTargetLowering();
113 RegInfo = &MF->getRegInfo();
114 MachineModuleInfo &MMI = MF->getMMI();
116 // Check whether the function can return without sret-demotion.
117 SmallVector<ISD::OutputArg, 4> Outs;
118 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
119 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
120 Fn->isVarArg(), Outs, Fn->getContext());
122 // Initialize the mapping of values to registers. This is only set up for
123 // instruction values that are used outside of the block that defines
125 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
126 for (; BB != EB; ++BB)
127 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
129 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
130 // Static allocas can be folded into the initial stack frame adjustment.
131 if (AI->isStaticAlloca()) {
132 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
133 Type *Ty = AI->getAllocatedType();
134 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
136 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
139 TySize *= CUI->getZExtValue(); // Get total allocated size.
140 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
142 StaticAllocaMap[AI] =
143 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
146 unsigned Align = std::max(
147 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
148 AI->getAllocatedType()),
150 unsigned StackAlign =
151 MF->getSubtarget().getFrameLowering()->getStackAlignment();
152 if (Align <= StackAlign)
154 // Inform the Frame Information that we have variable-sized objects.
155 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
159 // Look for inline asm that clobbers the SP register.
160 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
161 ImmutableCallSite CS(I);
162 if (isa<InlineAsm>(CS.getCalledValue())) {
163 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
164 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
165 std::vector<TargetLowering::AsmOperandInfo> Ops =
166 TLI->ParseConstraints(TRI, CS);
167 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
168 TargetLowering::AsmOperandInfo &Op = Ops[I];
169 if (Op.Type == InlineAsm::isClobber) {
170 // Clobbers don't have SDValue operands, hence SDValue().
171 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
172 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
173 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
175 if (PhysReg.first == SP)
176 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
182 // Look for calls to the @llvm.va_start intrinsic. We can omit some
183 // prologue boilerplate for variadic functions that don't examine their
185 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
186 if (II->getIntrinsicID() == Intrinsic::vastart)
187 MF->getFrameInfo()->setHasVAStart(true);
190 // If we have a musttail call in a variadic funciton, we need to ensure we
191 // forward implicit register parameters.
192 if (const auto *CI = dyn_cast<CallInst>(I)) {
193 if (CI->isMustTailCall() && Fn->isVarArg())
194 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
197 // Mark values used outside their block as exported, by allocating
198 // a virtual register for them.
199 if (isUsedOutsideOfDefiningBlock(I))
200 if (!isa<AllocaInst>(I) ||
201 !StaticAllocaMap.count(cast<AllocaInst>(I)))
202 InitializeRegForValue(I);
204 // Collect llvm.dbg.declare information. This is done now instead of
205 // during the initial isel pass through the IR so that it is done
206 // in a predictable order.
207 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
208 assert(DI->getVariable() && "Missing variable");
209 assert(DI->getDebugLoc() && "Missing location");
210 if (MMI.hasDebugInfo()) {
211 // Don't handle byval struct arguments or VLAs, for example.
212 // Non-byval arguments are handled here (they refer to the stack
213 // temporary alloca at this point).
214 const Value *Address = DI->getAddress();
216 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
217 Address = BCI->getOperand(0);
218 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
219 DenseMap<const AllocaInst *, int>::iterator SI =
220 StaticAllocaMap.find(AI);
221 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
223 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
224 FI, DI->getDebugLoc());
231 // Decide the preferred extend type for a value.
232 PreferredExtendType[I] = getPreferredExtendForValue(I);
235 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
236 // also creates the initial PHI MachineInstrs, though none of the input
237 // operands are populated.
238 for (BB = Fn->begin(); BB != EB; ++BB) {
239 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
243 // Transfer the address-taken flag. This is necessary because there could
244 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
245 // the first one should be marked.
246 if (BB->hasAddressTaken())
247 MBB->setHasAddressTaken();
249 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
251 for (BasicBlock::const_iterator I = BB->begin();
252 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
253 if (PN->use_empty()) continue;
256 if (PN->getType()->isEmptyTy())
259 DebugLoc DL = PN->getDebugLoc();
260 unsigned PHIReg = ValueMap[PN];
261 assert(PHIReg && "PHI node does not have an assigned virtual register!");
263 SmallVector<EVT, 4> ValueVTs;
264 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
265 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
266 EVT VT = ValueVTs[vti];
267 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
268 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
269 for (unsigned i = 0; i != NumRegisters; ++i)
270 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
271 PHIReg += NumRegisters;
276 // Mark landing pad blocks.
277 SmallVector<const LandingPadInst *, 4> LPads;
278 for (BB = Fn->begin(); BB != EB; ++BB) {
279 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
280 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
281 if (BB->isLandingPad())
282 LPads.push_back(BB->getLandingPadInst());
285 // If this is an MSVC EH personality, we need to do a bit more work.
286 EHPersonality Personality = EHPersonality::Unknown;
288 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
289 if (!isMSVCEHPersonality(Personality))
292 WinEHFuncInfo *EHInfo = nullptr;
293 if (Personality == EHPersonality::MSVC_Win64SEH) {
294 addSEHHandlersForLPads(LPads);
295 } else if (Personality == EHPersonality::MSVC_CXX) {
296 const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
297 EHInfo = &MMI.getWinEHFuncInfo(WinEHParentFn);
298 if (EHInfo->LandingPadStateMap.empty()) {
299 WinEHNumbering Num(*EHInfo);
300 Num.calculateStateNumbers(*WinEHParentFn);
301 // Pop everything on the handler stack.
302 Num.processCallSite(None, ImmutableCallSite());
305 // Copy the state numbers to LandingPadInfo for the current function, which
306 // could be a handler or the parent.
307 for (const LandingPadInst *LP : LPads) {
308 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
309 MMI.addWinEHState(LPadMBB, EHInfo->LandingPadStateMap[LP]);
314 void FunctionLoweringInfo::addSEHHandlersForLPads(
315 ArrayRef<const LandingPadInst *> LPads) {
316 MachineModuleInfo &MMI = MF->getMMI();
318 // Iterate over all landing pads with llvm.eh.actions calls.
319 for (const LandingPadInst *LP : LPads) {
320 const IntrinsicInst *ActionsCall =
321 dyn_cast<IntrinsicInst>(LP->getNextNode());
323 ActionsCall->getIntrinsicID() != Intrinsic::eh_actions)
326 // Parse the llvm.eh.actions call we found.
327 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
328 SmallVector<std::unique_ptr<ActionHandler>, 4> Actions;
329 parseEHActions(ActionsCall, Actions);
331 // Iterate EH actions from most to least precedence, which means
332 // iterating in reverse.
333 for (auto I = Actions.rbegin(), E = Actions.rend(); I != E; ++I) {
334 ActionHandler *Action = I->get();
335 if (auto *CH = dyn_cast<CatchHandler>(Action)) {
337 dyn_cast<Function>(CH->getSelector()->stripPointerCasts());
338 assert((Filter || CH->getSelector()->isNullValue()) &&
339 "expected function or catch-all");
340 const auto *RecoverBA =
341 cast<BlockAddress>(CH->getHandlerBlockOrFunc());
342 MMI.addSEHCatchHandler(LPadMBB, Filter, RecoverBA);
344 assert(isa<CleanupHandler>(Action));
345 const auto *Fini = cast<Function>(Action->getHandlerBlockOrFunc());
346 MMI.addSEHCleanupHandler(LPadMBB, Fini);
352 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
353 WinEHUnwindMapEntry UME;
354 UME.ToState = ToState;
355 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
356 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
358 UME.Cleanup = nullptr;
359 FuncInfo.UnwindMap.push_back(UME);
362 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
363 ArrayRef<CatchHandler *> Handlers) {
364 WinEHTryBlockMapEntry TBME;
365 TBME.TryLow = TryLow;
366 TBME.TryHigh = TryHigh;
367 assert(TBME.TryLow <= TBME.TryHigh);
368 for (CatchHandler *CH : Handlers) {
370 if (CH->getSelector()->isNullValue()) {
371 HT.Adjectives = 0x40;
372 HT.TypeDescriptor = nullptr;
374 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
375 // Selectors are always pointers to GlobalVariables with 'struct' type.
376 // The struct has two fields, adjectives and a type descriptor.
377 auto *CS = cast<ConstantStruct>(GV->getInitializer());
379 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
381 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
383 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
384 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
385 TBME.HandlerArray.push_back(HT);
387 FuncInfo.TryBlockMap.push_back(TBME);
390 static void print_name(const Value *V) {
393 DEBUG(dbgs() << "null");
397 if (const auto *F = dyn_cast<Function>(V))
398 DEBUG(dbgs() << F->getName());
404 void WinEHNumbering::processCallSite(
405 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
406 ImmutableCallSite CS) {
407 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
409 print_name(CS ? CS.getCalledValue() : nullptr);
410 DEBUG(dbgs() << '\n');
412 DEBUG(dbgs() << "HandlerStack: \n");
413 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
414 DEBUG(dbgs() << " ");
415 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
416 DEBUG(dbgs() << '\n');
418 DEBUG(dbgs() << "Actions: \n");
419 for (int I = 0, E = Actions.size(); I < E; ++I) {
420 DEBUG(dbgs() << " ");
421 print_name(Actions[I]->getHandlerBlockOrFunc());
422 DEBUG(dbgs() << '\n');
424 int FirstMismatch = 0;
425 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
427 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
428 Actions[FirstMismatch]->getHandlerBlockOrFunc())
432 // Don't recurse while we are looping over the handler stack. Instead, defer
433 // the numbering of the catch handlers until we are done popping.
434 SmallVector<CatchHandler *, 4> PoppedCatches;
435 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
436 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
437 if (isa<CatchHandler>(Handler.get()))
438 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
441 int TryHigh = NextState - 1;
442 int LastTryLowIdx = 0;
443 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
444 CatchHandler *CH = PoppedCatches[I];
445 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
446 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
447 int TryLow = CH->getEHState();
449 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
450 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
451 for (size_t J = 0; J < Handlers.size(); ++J) {
452 DEBUG(dbgs() << ", ");
453 print_name(Handlers[J]->getHandlerBlockOrFunc());
455 DEBUG(dbgs() << ")\n");
456 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
457 LastTryLowIdx = I + 1;
461 for (CatchHandler *CH : PoppedCatches) {
462 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
463 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
465 DEBUG(dbgs() << '\n');
466 FuncInfo.HandlerBaseState[F] = NextState;
467 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
469 createUnwindMapEntry(currentEHNumber(), nullptr);
471 calculateStateNumbers(*F);
476 // The handler functions may have pushed actions onto the handler stack
477 // that we expected to push here. Compare the handler stack to our
478 // actions again to check for that possibility.
479 if (HandlerStack.size() > (size_t)FirstMismatch) {
480 for (int E = std::min(HandlerStack.size(), Actions.size());
481 FirstMismatch < E; ++FirstMismatch) {
482 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
483 Actions[FirstMismatch]->getHandlerBlockOrFunc())
488 DEBUG(dbgs() << "Pushing actions for CallSite: ");
489 print_name(CS ? CS.getCalledValue() : nullptr);
490 DEBUG(dbgs() << '\n');
492 bool LastActionWasCatch = false;
493 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
494 // We can reuse eh states when pushing two catches for the same invoke.
495 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
496 // FIXME: Reenable this optimization!
497 if (CurrActionIsCatch && LastActionWasCatch && false) {
498 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber()
500 Actions[I]->setEHState(currentEHNumber());
502 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
503 print_name(Actions[I]->getHandlerBlockOrFunc());
504 DEBUG(dbgs() << ")\n");
505 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
506 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
507 Actions[I]->setEHState(NextState);
510 HandlerStack.push_back(std::move(Actions[I]));
511 LastActionWasCatch = CurrActionIsCatch;
514 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
515 print_name(CS ? CS.getCalledValue() : nullptr);
516 DEBUG(dbgs() << '\n');
519 void WinEHNumbering::calculateStateNumbers(const Function &F) {
520 auto I = VisitedHandlers.insert(&F);
522 return; // We've already visited this handler, don't renumber it.
524 int OldBaseState = CurrentBaseState;
525 if (FuncInfo.HandlerBaseState.count(&F)) {
526 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
529 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
530 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
531 for (const BasicBlock &BB : F) {
532 for (const Instruction &I : BB) {
533 const auto *CI = dyn_cast<CallInst>(&I);
534 if (!CI || CI->doesNotThrow())
536 processCallSite(None, CI);
538 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
541 const LandingPadInst *LPI = II->getLandingPadInst();
542 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
545 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
546 parseEHActions(ActionsCall, ActionList);
547 if (ActionList.empty())
549 processCallSite(ActionList, II);
551 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
552 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
553 << " to landing pad at " << LPI->getParent()->getName()
557 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
559 CurrentBaseState = OldBaseState;
562 /// clear - Clear out all the function-specific state. This returns this
563 /// FunctionLoweringInfo to an empty state, ready to be used for a
564 /// different function.
565 void FunctionLoweringInfo::clear() {
566 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
567 "Not all catch info was assigned to a landing pad!");
571 StaticAllocaMap.clear();
573 CatchInfoLost.clear();
574 CatchInfoFound.clear();
576 LiveOutRegInfo.clear();
578 ArgDbgValues.clear();
579 ByValArgFrameIndexMap.clear();
581 StatepointStackSlots.clear();
582 PreferredExtendType.clear();
585 /// CreateReg - Allocate a single virtual register for the given type.
586 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
587 return RegInfo->createVirtualRegister(
588 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
591 /// CreateRegs - Allocate the appropriate number of virtual registers of
592 /// the correctly promoted or expanded types. Assign these registers
593 /// consecutive vreg numbers and return the first assigned number.
595 /// In the case that the given value has struct or array type, this function
596 /// will assign registers for each member or element.
598 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
599 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
601 SmallVector<EVT, 4> ValueVTs;
602 ComputeValueVTs(*TLI, Ty, ValueVTs);
604 unsigned FirstReg = 0;
605 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
606 EVT ValueVT = ValueVTs[Value];
607 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
609 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
610 for (unsigned i = 0; i != NumRegs; ++i) {
611 unsigned R = CreateReg(RegisterVT);
612 if (!FirstReg) FirstReg = R;
618 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
619 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
620 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
621 /// the larger bit width by zero extension. The bit width must be no smaller
622 /// than the LiveOutInfo's existing bit width.
623 const FunctionLoweringInfo::LiveOutInfo *
624 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
625 if (!LiveOutRegInfo.inBounds(Reg))
628 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
632 if (BitWidth > LOI->KnownZero.getBitWidth()) {
633 LOI->NumSignBits = 1;
634 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
635 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
641 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
642 /// register based on the LiveOutInfo of its operands.
643 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
644 Type *Ty = PN->getType();
645 if (!Ty->isIntegerTy() || Ty->isVectorTy())
648 SmallVector<EVT, 1> ValueVTs;
649 ComputeValueVTs(*TLI, Ty, ValueVTs);
650 assert(ValueVTs.size() == 1 &&
651 "PHIs with non-vector integer types should have a single VT.");
652 EVT IntVT = ValueVTs[0];
654 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
656 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
657 unsigned BitWidth = IntVT.getSizeInBits();
659 unsigned DestReg = ValueMap[PN];
660 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
662 LiveOutRegInfo.grow(DestReg);
663 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
665 Value *V = PN->getIncomingValue(0);
666 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
667 DestLOI.NumSignBits = 1;
668 APInt Zero(BitWidth, 0);
669 DestLOI.KnownZero = Zero;
670 DestLOI.KnownOne = Zero;
674 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
675 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
676 DestLOI.NumSignBits = Val.getNumSignBits();
677 DestLOI.KnownZero = ~Val;
678 DestLOI.KnownOne = Val;
680 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
681 "CopyToReg node was created.");
682 unsigned SrcReg = ValueMap[V];
683 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
684 DestLOI.IsValid = false;
687 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
689 DestLOI.IsValid = false;
695 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
696 DestLOI.KnownOne.getBitWidth() == BitWidth &&
697 "Masks should have the same bit width as the type.");
699 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
700 Value *V = PN->getIncomingValue(i);
701 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
702 DestLOI.NumSignBits = 1;
703 APInt Zero(BitWidth, 0);
704 DestLOI.KnownZero = Zero;
705 DestLOI.KnownOne = Zero;
709 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
710 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
711 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
712 DestLOI.KnownZero &= ~Val;
713 DestLOI.KnownOne &= Val;
717 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
718 "its CopyToReg node was created.");
719 unsigned SrcReg = ValueMap[V];
720 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
721 DestLOI.IsValid = false;
724 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
726 DestLOI.IsValid = false;
729 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
730 DestLOI.KnownZero &= SrcLOI->KnownZero;
731 DestLOI.KnownOne &= SrcLOI->KnownOne;
735 /// setArgumentFrameIndex - Record frame index for the byval
736 /// argument. This overrides previous frame index entry for this argument,
738 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
740 ByValArgFrameIndexMap[A] = FI;
743 /// getArgumentFrameIndex - Get frame index for the byval argument.
744 /// If the argument does not have any assigned frame index then 0 is
746 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
747 DenseMap<const Argument *, int>::iterator I =
748 ByValArgFrameIndexMap.find(A);
749 if (I != ByValArgFrameIndexMap.end())
751 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
755 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
756 /// being passed to this variadic function, and set the MachineModuleInfo's
757 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
758 /// reference to _fltused on Windows, which will link in MSVCRT's
759 /// floating-point support.
760 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
761 MachineModuleInfo *MMI)
763 FunctionType *FT = cast<FunctionType>(
764 I.getCalledValue()->getType()->getContainedType(0));
765 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
766 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
767 Type* T = I.getArgOperand(i)->getType();
768 for (auto i : post_order(T)) {
769 if (i->isFloatingPointTy()) {
770 MMI->setUsesVAFloatArgument(true);
778 /// AddLandingPadInfo - Extract the exception handling information from the
779 /// landingpad instruction and add them to the specified machine module info.
780 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
781 MachineBasicBlock *MBB) {
782 MMI.addPersonality(MBB,
783 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
788 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
789 // but we need to do it this way because of how the DWARF EH emitter
790 // processes the clauses.
791 for (unsigned i = I.getNumClauses(); i != 0; --i) {
792 Value *Val = I.getClause(i - 1);
793 if (I.isCatch(i - 1)) {
794 MMI.addCatchTypeInfo(MBB,
795 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
797 // Add filters in a list.
798 Constant *CVal = cast<Constant>(Val);
799 SmallVector<const GlobalValue*, 4> FilterList;
800 for (User::op_iterator
801 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
802 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
804 MMI.addFilterTypeInfo(MBB, FilterList);