本文整理汇总了C++中SILModule::getASTContext方法的典型用法代码示例。如果您正苦于以下问题:C++ SILModule::getASTContext方法的具体用法?C++ SILModule::getASTContext怎么用?C++ SILModule::getASTContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SILModule
的用法示例。
在下文中一共展示了SILModule::getASTContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: canUseScalarCheckedCastInstructions
/// Can the given cast be performed by the scalar checked-cast
/// instructions?
bool swift::canUseScalarCheckedCastInstructions(SILModule &M,
CanType sourceType,
CanType targetType) {
// Look through one level of optionality on the source.
auto objectType = sourceType;
if (auto type = objectType.getOptionalObjectType())
objectType = type;
// Casting to NSError needs to go through the indirect-cast case,
// since it may conform to Error and require Error-to-NSError
// bridging, unless we can statically see that the source type inherits
// NSError.
// A class-constrained archetype may be bound to NSError, unless it has a
// non-NSError superclass constraint. Casts to archetypes thus must always be
// indirect.
if (auto archetype = targetType->getAs<ArchetypeType>()) {
// Only ever permit this if the source type is a reference type.
if (!objectType.isAnyClassReferenceType())
return false;
auto super = archetype->getSuperclass();
if (super.isNull())
return false;
// A base class constraint that isn't NSError rules out the archetype being
// bound to NSError.
if (M.getASTContext().LangOpts.EnableObjCInterop) {
if (auto nserror = M.Types.getNSErrorType())
return !super->isEqual(nserror);
}
// If NSError wasn't loaded, any base class constraint must not be NSError.
return true;
}
if (M.getASTContext().LangOpts.EnableObjCInterop
&& targetType == M.Types.getNSErrorType()) {
// If we statically know the source is an NSError subclass, then the cast
// can go through the scalar path (and it's trivially true so can be
// killed).
return targetType->isExactSuperclassOf(objectType);
}
// Three supported cases:
// - metatype to metatype
// - metatype to object
// - object to object
if ((objectType.isAnyClassReferenceType() || isa<AnyMetatypeType>(objectType))
&& targetType.isAnyClassReferenceType())
return true;
if (isa<AnyMetatypeType>(objectType) && isa<AnyMetatypeType>(targetType))
return true;
// Otherwise, we need to use the general indirect-cast functions.
return false;
}
示例2: Module
Emitter::Emitter(StringRef PassName, SILModule &M)
: Module(M), PassName(PassName),
PassedEnabled(
M.getASTContext().LangOpts.OptimizationRemarkPassedPattern &&
M.getASTContext().LangOpts.OptimizationRemarkPassedPattern->match(
PassName)),
MissedEnabled(
M.getASTContext().LangOpts.OptimizationRemarkMissedPattern &&
M.getASTContext().LangOpts.OptimizationRemarkMissedPattern->match(
PassName)) {}
示例3: getOutlinedFunctionType
/// Returns the outlined function type.
///
/// This depends on the first instruction we matched. Either we matched a load
/// or we started the match at the class method instruction.
///
/// load %30 : *UITextField:
/// (@in_guaranteed InstanceType) -> (@owned Optional<BridgedInstanceType>)
/// objc_method %31 : UITextField
/// (@unowned InstanceType) -> (@owned Optional<BridgedInstanceType>)
///
CanSILFunctionType BridgedProperty::getOutlinedFunctionType(SILModule &M) {
SmallVector<SILParameterInfo, 4> Parameters;
if (auto *Load = dyn_cast<LoadInst>(FirstInst))
Parameters.push_back(
SILParameterInfo(Load->getType().getASTType(),
ParameterConvention::Indirect_In_Guaranteed));
else
Parameters.push_back(SILParameterInfo(cast<ObjCMethodInst>(FirstInst)
->getOperand()
->getType()
.getASTType(),
ParameterConvention::Direct_Unowned));
SmallVector<SILResultInfo, 4> Results;
Results.push_back(SILResultInfo(
switchInfo.Br->getArg(0)->getType().getASTType(),
ResultConvention::Owned));
auto ExtInfo =
SILFunctionType::ExtInfo(SILFunctionType::Representation::Thin,
/*pseudogeneric*/ false, /*noescape*/ false);
auto FunctionType = SILFunctionType::get(
nullptr, ExtInfo, SILCoroutineKind::None,
ParameterConvention::Direct_Unowned, Parameters, /*yields*/ {},
Results, None, M.getASTContext());
return FunctionType;
}
示例4: emitRemark
static void emitRemark(SILModule &Module, const Remark<RemarkT> &R,
Diag<ArgTypes...> ID, bool DiagEnabled) {
if (R.getLocation().isInvalid())
return;
if (auto *Out = Module.getOptRecordStream())
// YAMLTraits takes a non-const reference even when outputting.
*Out << const_cast<Remark<RemarkT> &>(R);
if (DiagEnabled)
Module.getASTContext().Diags.diagnose(R.getLocation(), ID, R.getMsg());
}
示例5: diagnosePoundAssert
/// Emit a diagnostic for `poundAssert` builtins whose condition is
/// false or whose condition cannot be evaluated.
static void diagnosePoundAssert(const SILInstruction *I,
SILModule &M,
ConstExprEvaluator &constantEvaluator) {
auto *builtinInst = dyn_cast<BuiltinInst>(I);
if (!builtinInst ||
builtinInst->getBuiltinKind() != BuiltinValueKind::PoundAssert)
return;
SmallVector<SymbolicValue, 1> values;
constantEvaluator.computeConstantValues({builtinInst->getArguments()[0]},
values);
SymbolicValue value = values[0];
if (!value.isConstant()) {
diagnose(M.getASTContext(), I->getLoc().getSourceLoc(),
diag::pound_assert_condition_not_constant);
// If we have more specific information about what went wrong, emit
// notes.
if (value.getKind() == SymbolicValue::Unknown)
value.emitUnknownDiagnosticNotes(builtinInst->getLoc());
return;
}
assert(value.getKind() == SymbolicValue::Integer &&
"sema prevents non-integer #assert condition");
APInt intValue = value.getIntegerValue();
assert(intValue.getBitWidth() == 1 &&
"sema prevents non-int1 #assert condition");
if (intValue.isNullValue()) {
auto *message = cast<StringLiteralInst>(builtinInst->getArguments()[1]);
StringRef messageValue = message->getValue();
if (messageValue.empty())
messageValue = "assertion failed";
diagnose(M.getASTContext(), I->getLoc().getSourceLoc(),
diag::pound_assert_failure, messageValue);
return;
}
}
示例6:
// Convert the substituted function type into a specialized function type based
// on the ReabstractionInfo.
CanSILFunctionType ReabstractionInfo::
createSpecializedType(CanSILFunctionType SubstFTy, SILModule &M) const {
llvm::SmallVector<SILResultInfo, 8> SpecializedResults;
llvm::SmallVector<SILParameterInfo, 8> SpecializedParams;
unsigned ResultIdx = 0;
for (SILResultInfo RI : SubstFTy->getAllResults()) {
if (RI.isDirect()) {
SpecializedResults.push_back(RI);
} else {
if (isResultConverted(ResultIdx++)) {
// Convert the indirect result to a direct result.
SILType SILResTy = SILType::getPrimitiveObjectType(RI.getType());
// Indirect results are passed as owned, so we also need to pass the
// direct result as owned (except it's a trivial type).
auto C = (SILResTy.isTrivial(M) ? ResultConvention::Unowned :
ResultConvention::Owned);
SpecializedResults.push_back(SILResultInfo(RI.getType(), C));
} else {
// No conversion: re-use the original result info.
SpecializedResults.push_back(RI);
}
}
}
unsigned ParamIdx = 0;
for (SILParameterInfo PI : SubstFTy->getParameters()) {
if (isParamConverted(ParamIdx++)) {
// Convert the indirect parameter to a direct parameter.
SILType SILParamTy = SILType::getPrimitiveObjectType(PI.getType());
// Indirect parameters are passed as owned, so we also need to pass the
// direct parameter as owned (except it's a trivial type).
auto C = (SILParamTy.isTrivial(M) ? ParameterConvention::Direct_Unowned :
ParameterConvention::Direct_Owned);
SpecializedParams.push_back(SILParameterInfo(PI.getType(), C));
} else {
// No conversion: re-use the original parameter info.
SpecializedParams.push_back(PI);
}
}
return
SILFunctionType::get(SubstFTy->getGenericSignature(),
SubstFTy->getExtInfo(),
SubstFTy->getCalleeConvention(), SpecializedParams,
SpecializedResults, SubstFTy->getOptionalErrorResult(),
M.getASTContext());
}
示例7: getPartialApplyResultType
SILType SILBuilder::getPartialApplyResultType(SILType origTy, unsigned argCount,
SILModule &M,
SubstitutionMap subs,
ParameterConvention calleeConvention,
PartialApplyInst::OnStackKind onStack) {
CanSILFunctionType FTI = origTy.castTo<SILFunctionType>();
if (!subs.empty())
FTI = FTI->substGenericArgs(M, subs);
assert(!FTI->isPolymorphic()
&& "must provide substitutions for generic partial_apply");
auto params = FTI->getParameters();
auto newParams = params.slice(0, params.size() - argCount);
auto extInfo = FTI->getExtInfo()
.withRepresentation(SILFunctionType::Representation::Thick)
.withIsPseudogeneric(false);
if (onStack)
extInfo = extInfo.withNoEscape();
// If the original method has an @unowned_inner_pointer return, the partial
// application thunk will lifetime-extend 'self' for us, converting the
// return value to @unowned.
//
// If the original method has an @autoreleased return, the partial application
// thunk will retain it for us, converting the return value to @owned.
SmallVector<SILResultInfo, 4> results;
results.append(FTI->getResults().begin(), FTI->getResults().end());
for (auto &result : results) {
if (result.getConvention() == ResultConvention::UnownedInnerPointer)
result = SILResultInfo(result.getType(), ResultConvention::Unowned);
else if (result.getConvention() == ResultConvention::Autoreleased)
result = SILResultInfo(result.getType(), ResultConvention::Owned);
}
auto appliedFnType = SILFunctionType::get(nullptr, extInfo,
FTI->getCoroutineKind(),
calleeConvention,
newParams,
FTI->getYields(),
results,
FTI->getOptionalErrorResult(),
M.getASTContext());
return SILType::getPrimitiveObjectType(appliedFnType);
}
示例8: diagnoseStaticReports
/// \brief Issue diagnostics whenever we see Builtin.static_report(1, ...).
static void diagnoseStaticReports(const SILInstruction *I,
SILModule &M) {
// Find out if we are dealing with Builtin.staticReport().
if (auto *BI = dyn_cast<BuiltinInst>(I)) {
const BuiltinInfo &B = BI->getBuiltinInfo();
if (B.ID == BuiltinValueKind::StaticReport) {
// Report diagnostic if the first argument has been folded to '1'.
OperandValueArrayRef Args = BI->getArguments();
IntegerLiteralInst *V = dyn_cast<IntegerLiteralInst>(Args[0]);
if (!V || V->getValue() != 1)
return;
diagnose(M.getASTContext(), I->getLoc().getSourceLoc(),
diag::static_report_error);
}
}
}
示例9: isBridgedErrorClass
/// True if the given type value is nonnull, and the represented type is NSError
/// or CFError, the error classes for which we support "toll-free" bridging to
/// Error existentials.
static bool isBridgedErrorClass(SILModule &M,
Type t) {
// There's no bridging if ObjC interop is disabled.
if (!M.getASTContext().LangOpts.EnableObjCInterop)
return false;
if (!t)
return false;
if (auto archetypeType = t->getAs<ArchetypeType>())
t = archetypeType->getSuperclass();
// NSError (TODO: and CFError) can be bridged.
auto nsErrorType = M.Types.getNSErrorType();
if (t && nsErrorType && nsErrorType->isExactSuperclassOf(t)) {
return true;
}
return false;
}
示例10: getEnumElementType
SILType SILType::getEnumElementType(EnumElementDecl *elt, SILModule &M) const {
assert(elt->getDeclContext() == getEnumOrBoundGenericEnum());
assert(elt->hasAssociatedValues());
if (auto objectType = getSwiftRValueType().getAnyOptionalObjectType()) {
assert(elt == M.getASTContext().getOptionalSomeDecl());
return SILType(objectType, getCategory());
}
auto substEltTy =
getSwiftRValueType()->getTypeOfMember(M.getSwiftModule(), elt,
elt->getArgumentInterfaceType());
auto loweredTy =
M.Types.getLoweredType(M.Types.getAbstractionPattern(elt), substEltTy);
// If the case is indirect, then the payload is boxed.
if (elt->isIndirect() || elt->getParentEnum()->isIndirect())
loweredTy = SILType::getPrimitiveObjectType(
SILBoxType::get(loweredTy.getSwiftRValueType()));
return SILType(loweredTy.getSwiftRValueType(), getCategory());
}
示例11: assert
//.........这里部分代码省略.........
// override the Member.
//
// As a result, substitutions provided by AI are for Member, whereas
// substitutions in ClassInstanceType are for D2. And substitutions for D1
// are not available directly in a general case. Therefore, they have to
// be computed.
//
// What we know for sure:
// B is a superclass of D1
// D1 is a superclass of D2.
// D1 can be the same as D2. D1 can be the same as B.
//
// So, substitutions from AI are for class B.
// Substitutions for class D1 by means of bindSuperclass(), which starts
// with a bound type ClassInstanceType and checks its superclasses until it
// finds a bound superclass matching D1 and returns its substitutions.
// Class F belongs to.
CanType FSelfClass = GenCalleeType->getSelfParameter().getType();
SILType FSelfSubstType;
Module *Module = M.getSwiftModule();
ArrayRef<Substitution> ClassSubs;
if (GenCalleeType->isPolymorphic()) {
// Declaration of the class F belongs to.
if (auto *FSelfTypeDecl = FSelfClass.getNominalOrBoundGenericNominal()) {
// Get the unbound generic type F belongs to.
CanType FSelfGenericType =
FSelfTypeDecl->getDeclaredType()->getCanonicalType();
assert((isa<BoundGenericType>(ClassInstanceType.getSwiftRValueType()) ||
isa<NominalType>(ClassInstanceType.getSwiftRValueType())) &&
"Self type should be either a bound generic type"
"or a non-generic type");
assert((isa<UnboundGenericType>(FSelfGenericType) ||
isa<NominalType>(FSelfGenericType)) &&
"Method implementation self type should be generic");
if (isa<BoundGenericType>(ClassInstanceType.getSwiftRValueType())) {
auto BoundBaseType = bindSuperclass(FSelfGenericType,
ClassInstanceType);
if (auto BoundTy = BoundBaseType->getAs<BoundGenericType>()) {
ClassSubs = BoundTy->getSubstitutions(Module, nullptr);
}
}
}
} else {
// If the callee is not polymorphic, no substitutions are required.
return {};
}
if (ClassSubs.empty())
return AI.getSubstitutions();
auto AISubs = AI.getSubstitutions();
CanSILFunctionType AIGenCalleeType =
AI.getCallee().getType().castTo<SILFunctionType>();
CanType AISelfClass = AIGenCalleeType->getSelfParameter().getType();
unsigned NextMethodParamIdx = 0;
unsigned NumMethodParams = 0;
if (AIGenCalleeType->isPolymorphic()) {
NextMethodParamIdx = 0;
// Generic parameters of the method start after generic parameters
// of the instance class.
if (auto AISelfClassSig =
AISelfClass.getClassBound()->getGenericSignature()) {
NextMethodParamIdx = AISelfClassSig->getGenericParams().size();
}
NumMethodParams = AISubs.size() - NextMethodParamIdx;
}
unsigned NumSubs = ClassSubs.size() + NumMethodParams;
if (ClassSubs.size() == NumSubs)
return ClassSubs;
// Mix class subs with method specific subs from the AI substitutions.
// Assumptions: AI substitutions contain first the substitutions for
// a class of the method being invoked and then the substitutions
// for a method being invoked.
auto Subs = M.getASTContext().Allocate<Substitution>(NumSubs);
unsigned i = 0;
for (auto &S : ClassSubs) {
Subs[i++] = S;
}
for (; i < NumSubs; ++i, ++NextMethodParamIdx) {
Subs[i] = AISubs[NextMethodParamIdx];
}
return Subs;
}
示例12: loweredAddresses
SILModuleConventions::SILModuleConventions(const SILModule &M)
: loweredAddresses(!M.getASTContext().LangOpts.EnableSILOpaqueValues) {}
示例13: runSILDiagnosticPasses
bool swift::runSILDiagnosticPasses(SILModule &Module) {
// Verify the module, if required.
if (Module.getOptions().VerifyAll)
Module.verify();
// If we parsed a .sil file that is already in canonical form, don't rerun
// the diagnostic passes.
if (Module.getStage() == SILStage::Canonical)
return false;
auto &Ctx = Module.getASTContext();
SILPassManager PM(&Module);
if (SILViewSILGenCFG) {
PM.resetAndRemoveTransformations();
PM.addCFGPrinter();
PM.runOneIteration();
}
// If we are asked do debug serialization, instead of running all diagnostic
// passes, just run mandatory inlining with dead transparent function cleanup
// disabled.
if (Module.getOptions().DebugSerialization) {
PM.addMandatoryInlining();
PM.run();
return Ctx.hadError();
}
// Otherwise run the rest of diagnostics.
PM.addCapturePromotion();
PM.addAllocBoxToStack();
PM.addInOutDeshadowing();
PM.addNoReturnFolding();
PM.addDefiniteInitialization();
PM.addMandatoryInlining();
PM.addPredictableMemoryOptimizations();
PM.addDiagnosticConstantPropagation();
PM.addDiagnoseUnreachable();
PM.addEmitDFDiagnostics();
// Canonical swift requires all non cond_br critical edges to be split.
PM.addSplitNonCondBrCriticalEdges();
PM.run();
// Generate diagnostics.
Module.setStage(SILStage::Canonical);
if (SILViewGuaranteedCFG) {
PM.resetAndRemoveTransformations();
PM.addCFGPrinter();
PM.runOneIteration();
}
// Verify the module, if required.
if (Module.getOptions().VerifyAll)
Module.verify();
else {
DEBUG(Module.verify());
}
// If errors were produced during SIL analysis, return true.
return Ctx.hadError();
}
示例14: diagnoseUnreachableBlock
/// \brief Issue an "unreachable code" diagnostic if the blocks contains or
/// leads to another block that contains user code.
///
/// Note, we rely on SILLocation information to determine if SILInstructions
/// correspond to user code.
static bool diagnoseUnreachableBlock(const SILBasicBlock &B,
SILModule &M,
const SILBasicBlockSet &Reachable,
UnreachableUserCodeReportingState *State,
const SILBasicBlock *TopLevelB,
llvm::SmallPtrSetImpl<const SILBasicBlock*> &Visited){
if (Visited.count(&B))
return false;
Visited.insert(&B);
assert(State);
for (auto I = B.begin(), E = B.end(); I != E; ++I) {
SILLocation Loc = I->getLoc();
// If we've reached an implicit return, we have not found any user code and
// can stop searching for it.
if (Loc.is<ImplicitReturnLocation>() || Loc.isAutoGenerated())
return false;
// Check if the instruction corresponds to user-written code, also make
// sure we don't report an error twice for the same instruction.
if (isUserCode(&*I) && !State->BlocksWithErrors.count(&B)) {
// Emit the diagnostic.
auto BrInfoIter = State->MetaMap.find(TopLevelB);
assert(BrInfoIter != State->MetaMap.end());
auto BrInfo = BrInfoIter->second;
switch (BrInfo.Kind) {
case (UnreachableKind::FoldedBranch):
// Emit the diagnostic on the unreachable block and emit the
// note on the branch responsible for the unreachable code.
diagnose(M.getASTContext(), Loc.getSourceLoc(), diag::unreachable_code);
diagnose(M.getASTContext(), BrInfo.Loc.getSourceLoc(),
diag::unreachable_code_branch, BrInfo.CondIsAlwaysTrue);
break;
case (UnreachableKind::FoldedSwitchEnum): {
// If we are warning about a switch condition being a constant, the main
// emphasis should be on the condition (to ensure we have a single
// message per switch).
const SwitchStmt *SS = BrInfo.Loc.getAsASTNode<SwitchStmt>();
if (!SS)
break;
assert(SS);
const Expr *SE = SS->getSubjectExpr();
diagnose(M.getASTContext(), SE->getLoc(), diag::switch_on_a_constant);
diagnose(M.getASTContext(), Loc.getSourceLoc(),
diag::unreachable_code_note);
break;
}
case (UnreachableKind::NoreturnCall): {
// Specialcase when we are warning about unreachable code after a call
// to a noreturn function.
if (!BrInfo.Loc.isASTNode<ExplicitCastExpr>()) {
assert(BrInfo.Loc.isASTNode<ApplyExpr>());
diagnose(M.getASTContext(), Loc.getSourceLoc(),
diag::unreachable_code);
diagnose(M.getASTContext(), BrInfo.Loc.getSourceLoc(),
diag::call_to_noreturn_note);
}
break;
}
}
// Record that we've reported this unreachable block to avoid duplicates
// in the future.
State->BlocksWithErrors.insert(&B);
return true;
}
}
// This block could be empty if it's terminator has been folded.
if (B.empty())
return false;
// If we have not found user code in this block, inspect it's successors.
// Check if at least one of the successors contains user code.
for (auto I = B.succ_begin(), E = B.succ_end(); I != E; ++I) {
SILBasicBlock *SB = *I;
bool HasReachablePred = false;
for (auto PI = SB->pred_begin(), PE = SB->pred_end(); PI != PE; ++PI) {
if (Reachable.count(*PI))
HasReachablePred = true;
}
// If all of the predecessors of this successor are unreachable, check if
// it contains user code.
if (!HasReachablePred && diagnoseUnreachableBlock(*SB, M, Reachable,
State, TopLevelB, Visited))
return true;
}
return false;
}
示例15: loweredAddresses
SILModuleConventions::SILModuleConventions(const SILModule &M)
: loweredAddresses(!M.getASTContext().LangOpts.EnableSILOpaqueValues
|| M.getStage() == SILStage::Lowered) {}