Skip to content

Commit

Permalink
Merge pull request #20 from llvm/main
Browse files Browse the repository at this point in the history
[pull] main from llvm:main
  • Loading branch information
devkadirselcuk authored Jul 9, 2021
2 parents 5b87741 + 9a01527 commit 72dfee4
Show file tree
Hide file tree
Showing 424 changed files with 9,550 additions and 3,707 deletions.
4 changes: 2 additions & 2 deletions clang-tools-extra/clang-doc/HTMLGenerator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,8 @@ genHTML(const Index &Index, StringRef InfoPath, bool IsOutermostList) {
if (!Index.JumpToSection)
SpanBody->Children.emplace_back(genReference(Index, InfoPath));
else
SpanBody->Children.emplace_back(genReference(
Index, InfoPath, StringRef{Index.JumpToSection.getValue()}));
SpanBody->Children.emplace_back(
genReference(Index, InfoPath, Index.JumpToSection.getValue().str()));
}
if (Index.Children.empty())
return Out;
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/JSONTransport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ bool JSONTransport::readStandardMessage(std::string &JSON) {
return false;
InMirror << Line;

llvm::StringRef LineRef(Line);
llvm::StringRef LineRef = Line;

// We allow comments in headers. Technically this isn't part

Expand Down Expand Up @@ -298,7 +298,7 @@ bool JSONTransport::readDelimitedMessage(std::string &JSON) {
llvm::SmallString<128> Line;
while (readLine(In, Line)) {
InMirror << Line;
auto LineRef = llvm::StringRef(Line).trim();
auto LineRef = Line.str().trim();
if (LineRef.startswith("#")) // comment
continue;

Expand Down
3 changes: 1 addition & 2 deletions clang-tools-extra/clangd/QueryDriverDatabase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
auto CleanUp = llvm::make_scope_exit(
[&StdErrPath]() { llvm::sys::fs::remove(StdErrPath); });

llvm::Optional<llvm::StringRef> Redirects[] = {
{""}, {""}, llvm::StringRef(StdErrPath)};
llvm::Optional<llvm::StringRef> Redirects[] = {{""}, {""}, StdErrPath.str()};

llvm::SmallVector<llvm::StringRef> Args = {Driver, "-E", "-x",
Lang, "-", "-v"};
Expand Down
3 changes: 1 addition & 2 deletions clang-tools-extra/clangd/Selection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -771,8 +771,7 @@ llvm::SmallString<256> abbreviatedString(DynTypedNode N,
}
auto Pos = Result.find('\n');
if (Pos != llvm::StringRef::npos) {
bool MoreText =
!llvm::all_of(llvm::StringRef(Result).drop_front(Pos), llvm::isSpace);
bool MoreText = !llvm::all_of(Result.str().drop_front(Pos), llvm::isSpace);
Result.resize(Pos);
if (MoreText)
Result.append("");
Expand Down
7 changes: 5 additions & 2 deletions clang-tools-extra/clangd/support/Threading.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "llvm/ADT/ScopeExit.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/thread.h"
#include <atomic>
#include <thread>
#ifdef __USE_POSIX
Expand Down Expand Up @@ -95,8 +96,10 @@ void AsyncTaskRunner::runAsync(const llvm::Twine &Name,
};

// Ensure our worker threads have big enough stacks to run clang.
llvm::llvm_execute_on_thread_async(std::move(Task),
/*clang::DesiredStackSize*/ 8 << 20);
llvm::thread Thread(
/*clang::DesiredStackSize*/ llvm::Optional<unsigned>(8 << 20),
std::move(Task));
Thread.detach();
}

Deadline timeoutSeconds(llvm::Optional<double> Seconds) {
Expand Down
25 changes: 23 additions & 2 deletions clang/docs/AddressSanitizer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ following types of bugs:

* Out-of-bounds accesses to heap, stack and globals
* Use-after-free
* Use-after-return (runtime flag `ASAN_OPTIONS=detect_stack_use_after_return=1`)
* Use-after-scope (clang flag `-fsanitize-address-use-after-scope`)
* Use-after-return (clang flag ``-fsanitize-address-use-after-return=(never|runtime|always)`` default: ``runtime``)
* Enable ``runtime`` with: ``ASAN_OPTIONS=detect_stack_use_after_return=1``
* Use-after-scope (clang flag ``-fsanitize-address-use-after-scope``)
* Double-free, invalid free
* Memory leaks (experimental)

Expand Down Expand Up @@ -136,6 +137,26 @@ you should set environment variable

Note that this option is not supported on macOS.

Stack Use After Return (UAR)
----------------------------

AddressSanitizer can optionally detect stack use after return problems.
This is available by default, or explicitly
(``-fsanitize-address-use-after-return=runtime``).
To enable this check at runtime, set the environment variable
``ASAN_OPTIONS=detect_stack_use_after_return=1``.

Enabling this check (``-fsanitize-address-use-after-return=always``) will
reduce code size. The code size may be reduced further by completely
eliminating this check (``-fsanitize-address-use-after-return=never``).

To summarize: ``-fsanitize-address-use-after-return=<mode>``
* ``never``: Completely disables detection of UAR errors (reduces code size).
* ``runtime``: Adds the code for detection, but must be enabled via the
runtime environment (``ASAN_OPTIONS=detect_stack_use_after_return=1``).
* ``always``: Enables detection of UAR errors in all cases. (reduces code
size, but not as much as ``never``).

Memory leak detection
---------------------

Expand Down
2 changes: 2 additions & 0 deletions clang/docs/UsersManual.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3744,6 +3744,8 @@ Execute ``clang-cl /?`` to see a list of supported options:
Enable linker dead stripping of globals in AddressSanitizer
-fsanitize-address-poison-custom-array-cookie
Enable poisoning array cookies when using custom operator new[] in AddressSanitizer
-fsanitize-address-use-after-return=<mode>
Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always
-fsanitize-address-use-after-scope
Enable use-after-scope detection in AddressSanitizer
-fsanitize-address-use-odr-indicator
Expand Down
4 changes: 2 additions & 2 deletions clang/include/clang/Basic/DiagnosticSemaKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -6744,13 +6744,13 @@ def ext_typecheck_indirection_through_void_pointer : ExtWarn<
"ISO C++ does not allow indirection on operand of type %0">,
InGroup<DiagGroup<"void-ptr-dereference">>;
def warn_indirection_through_null : Warning<
"indirection of non-volatile null pointer will be deleted, not trap">,
"indirection of null pointer will be deleted, not trap">,
InGroup<NullDereference>;
def warn_binding_null_to_reference : Warning<
"binding dereferenced null pointer to reference has undefined behavior">,
InGroup<NullDereference>;
def note_indirection_through_null : Note<
"consider using __builtin_trap() or qualifying pointer with 'volatile'">;
"consider using __builtin_trap()">;
def warn_pointer_indirection_from_incompatible_type : Warning<
"dereference of type %1 that was reinterpret_cast from type %0 has undefined "
"behavior">,
Expand Down
2 changes: 1 addition & 1 deletion clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -1584,7 +1584,7 @@ def sanitize_address_use_after_return_EQ
: Joined<["-"], "fsanitize-address-use-after-return=">,
MetaVarName<"<mode>">,
Flags<[CC1Option]>,
HelpText<"Select the mode of detecting stack use-after-return in AddressSanitizer">,
HelpText<"Select the mode of detecting stack use-after-return in AddressSanitizer: never | runtime (default) | always">,
Group<f_clang_Group>,
Values<"never,runtime,always">,
NormalizedValuesScope<"llvm::AsanDetectStackUseAfterReturnMode">,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class CachedFileSystemEntry {
return MaybeStat.getError();
assert(!MaybeStat->isDirectory() && "not a file");
assert(isValid() && "not initialized");
return StringRef(Contents);
return Contents.str();
}

/// \returns The error or the status of the entry.
Expand Down
1 change: 1 addition & 0 deletions clang/lib/AST/Expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1913,6 +1913,7 @@ Expr *CastExpr::getSubExprAsWritten() {
SubExpr =
skipImplicitTemporary(cast<CXXConstructExpr>(SubExpr->IgnoreImplicit())->getArg(0));
else if (E->getCastKind() == CK_UserDefinedConversion) {
SubExpr = SubExpr->IgnoreImplicit();
assert((isa<CXXMemberCallExpr>(SubExpr) ||
isa<BlockExpr>(SubExpr)) &&
"Unexpected SubExpr for CK_UserDefinedConversion.");
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/AST/MicrosoftMangle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3676,7 +3676,7 @@ void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
assert(VFTableMangling.startswith("??_7") ||
VFTableMangling.startswith("??_S"));

Out << "??_R4" << StringRef(VFTableMangling).drop_front(4);
Out << "??_R4" << VFTableMangling.str().drop_front(4);
}

void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Analysis/MacroExpansionContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ MacroExpansionContext::getExpandedText(SourceLocation MacroExpansionLoc) const {
return StringRef{""};

// Otherwise we have the actual token sequence as string.
return StringRef{It->getSecond()};
return It->getSecond().str();
}

Optional<StringRef>
Expand Down
4 changes: 2 additions & 2 deletions clang/lib/Basic/FileManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) {

SmallString<4096> CanonicalNameBuf;
if (!FS->getRealPath(Dir->getName(), CanonicalNameBuf))
CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);

CanonicalNames.insert({Dir, CanonicalName});
return CanonicalName;
Expand All @@ -627,7 +627,7 @@ StringRef FileManager::getCanonicalName(const FileEntry *File) {

SmallString<4096> CanonicalNameBuf;
if (!FS->getRealPath(File->getName(), CanonicalNameBuf))
CanonicalName = StringRef(CanonicalNameBuf).copy(CanonicalNameStorage);
CanonicalName = CanonicalNameBuf.str().copy(CanonicalNameStorage);

CanonicalNames.insert({File, CanonicalName});
return CanonicalName;
Expand Down
7 changes: 4 additions & 3 deletions clang/lib/CodeGen/CGCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1012,8 +1012,8 @@ static void forConstantArrayExpansion(CodeGenFunction &CGF,
BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);

for (int i = 0, n = CAE->NumElts; i < n; i++) {
llvm::Value *EltAddr =
CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
llvm::Value *EltAddr = CGF.Builder.CreateConstGEP2_32(
BaseAddr.getElementType(), BaseAddr.getPointer(), 0, i);
Fn(Address(EltAddr, EltAlign));
}
}
Expand Down Expand Up @@ -3437,7 +3437,8 @@ void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
--EI;
llvm::Value *ArgStruct = &*EI;
llvm::Value *SRet = Builder.CreateStructGEP(
nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
EI->getType()->getPointerElementType(), ArgStruct,
RetAI.getInAllocaFieldIndex());
llvm::Type *Ty =
cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
Expand Down
11 changes: 6 additions & 5 deletions clang/lib/CodeGen/CGObjCGNU.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -739,9 +739,11 @@ class CGObjCGNUstep : public CGObjCGNU {
/// Function to perform atomic copies of C++ objects with nontrivial copy
/// constructors to Objective-C ivars.
LazyRuntimeFunction CxxAtomicObjectSetFn;
/// Type of an slot structure pointer. This is returned by the various
/// Type of a slot structure pointer. This is returned by the various
/// lookup functions.
llvm::Type *SlotTy;
/// Type of a slot structure.
llvm::Type *SlotStructTy;

public:
llvm::Constant *GetEHType(QualType T) override;
Expand Down Expand Up @@ -780,7 +782,7 @@ class CGObjCGNUstep : public CGObjCGNU {

// Load the imp from the slot
llvm::Value *imp = Builder.CreateAlignedLoad(
IMPTy, Builder.CreateStructGEP(nullptr, slot, 4),
IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
CGF.getPointerAlign());

// The lookup function may have changed the receiver, so make sure we use
Expand All @@ -800,7 +802,7 @@ class CGObjCGNUstep : public CGObjCGNU {
slot->setOnlyReadsMemory();

return Builder.CreateAlignedLoad(
IMPTy, Builder.CreateStructGEP(nullptr, slot, 4),
IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
CGF.getPointerAlign());
}

Expand All @@ -811,8 +813,7 @@ class CGObjCGNUstep : public CGObjCGNU {
CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;

llvm::StructType *SlotStructTy =
llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
// Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
Expand Down
13 changes: 13 additions & 0 deletions clang/lib/CodeGen/CGStmtOpenMP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,9 @@ bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
OMPPrivateScope &PrivateScope) {
if (!HaveInsertPoint())
return false;
bool DeviceConstTarget =
getLangOpts().OpenMPIsDevice &&
isOpenMPTargetExecutionDirective(D.getDirectiveKind());
bool FirstprivateIsLastprivate = false;
llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates;
for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) {
Expand Down Expand Up @@ -818,6 +821,16 @@ bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
++InitsRef;
continue;
}
// Do not emit copy for firstprivate constant variables in target regions,
// captured by reference.
if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) &&
FD && FD->getType()->isReferenceType() &&
(!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) {
EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl());
++IRef;
++InitsRef;
continue;
}
FirstprivateIsLastprivate =
FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate;
if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) {
Expand Down
3 changes: 2 additions & 1 deletion clang/lib/CodeGen/CodeGenFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1084,7 +1084,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
llvm::Function::arg_iterator EI = CurFn->arg_end();
--EI;
llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
llvm::Value *Addr = Builder.CreateStructGEP(
EI->getType()->getPointerElementType(), &*EI, Idx);
llvm::Type *Ty =
cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
ReturnValuePointer = Address(Addr, getPointerAlign());
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/CodeGen/ItaniumCXXABI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1535,7 +1535,7 @@ llvm::Value *ItaniumCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF,

// Get the offset-to-top from the vtable.
OffsetToTop =
CGF.Builder.CreateConstInBoundsGEP1_32(/*Type=*/nullptr, VTable, -2U);
CGF.Builder.CreateConstInBoundsGEP1_32(CGM.Int32Ty, VTable, -2U);
OffsetToTop = CGF.Builder.CreateAlignedLoad(
CGM.Int32Ty, OffsetToTop, CharUnits::fromQuantity(4), "offset.to.top");
} else {
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/CodeGen/MicrosoftCXXABI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4338,7 +4338,7 @@ llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
};
auto *GV = new llvm::GlobalVariable(
CGM.getModule(), TIType, /*isConstant=*/true, getLinkageForRTTI(T),
llvm::ConstantStruct::get(TIType, Fields), StringRef(MangledName));
llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
GV->setSection(".xdata");
if (GV->isWeakForLinker())
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/CrossTU/CrossTranslationUnit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ parseInvocationList(StringRef FileContent, llvm::sys::path::Style PathStyle) {
SmallString<32> NativeSourcePath(SourcePath);
llvm::sys::path::native(NativeSourcePath, PathStyle);

StringRef InvocationKey(NativeSourcePath);
StringRef InvocationKey = NativeSourcePath;

if (InvocationList.find(InvocationKey) != InvocationList.end())
return llvm::make_error<IndexError>(
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Driver/ToolChains/AMDGPU.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ AMDGPUToolChain::detectSystemGPUs(const ArgList &Args,
llvm::FileRemover OutputRemover(OutputFile.c_str());
llvm::Optional<llvm::StringRef> Redirects[] = {
{""},
StringRef(OutputFile),
OutputFile.str(),
{""},
};

Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Lex/HeaderSearch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,7 @@ diagnoseFrameworkInclude(DiagnosticsEngine &Diags, SourceLocation IncludeLoc,
if (!isAngled && !FoundByHeaderMap) {
SmallString<128> NewInclude("<");
if (IsIncludeeInFramework) {
NewInclude += StringRef(ToFramework).drop_back(10); // drop .framework
NewInclude += ToFramework.str().drop_back(10); // drop .framework
NewInclude += "/";
}
NewInclude += IncludeFilename;
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Lex/PPDirectives.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1480,7 +1480,7 @@ void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,

// Find the first non-whitespace character, so that we can make the
// diagnostic more succinct.
StringRef Msg = StringRef(Message).ltrim(' ');
StringRef Msg = Message.str().ltrim(' ');

if (isWarning)
Diag(Tok, diag::pp_hash_warning) << Msg;
Expand Down
19 changes: 7 additions & 12 deletions clang/lib/Sema/SemaExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -533,21 +533,16 @@ ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
}

static void CheckForNullPointerDereference(Sema &S, Expr *E) {
// Check to see if we are dereferencing a null pointer. If so,
// and if not volatile-qualified, this is undefined behavior that the
// optimizer will delete, so warn about it. People sometimes try to use this
// to get a deterministic trap and are surprised by clang's behavior. This
// only handles the pattern "*null", which is a very syntactic check.
// Check to see if we are dereferencing a null pointer.
// If so, this is undefined behavior that the optimizer will delete,
// so warn about it. People sometimes try to use this to get a deterministic
// trap and are surprised by clang's behavior. This only handles the pattern
// "*null", which is a very syntactic check.
const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
if (UO && UO->getOpcode() == UO_Deref &&
UO->getSubExpr()->getType()->isPointerType()) {
const LangAS AS =
UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
if ((!isTargetAddressSpace(AS) ||
(isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
S.Context, Expr::NPC_ValueDependentIsNotNull) &&
!UO->getType().isVolatileQualified()) {
if (UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
S.Context, Expr::NPC_ValueDependentIsNotNull)) {
S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
S.PDiag(diag::warn_indirection_through_null)
<< UO->getSubExpr()->getSourceRange());
Expand Down
3 changes: 2 additions & 1 deletion clang/lib/Sema/SemaExprCXX.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7786,7 +7786,7 @@ ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Method->getType()->castAs<FunctionProtoType>()))
return ExprError();

return CE;
return CheckForImmediateInvocation(CE, CE->getMethodDecl());
}

ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
Expand Down Expand Up @@ -8343,6 +8343,7 @@ class TransformTypos : public TreeTransform<TransformTypos> {

AmbiguousTypoExprs.remove(TE);
SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
TransformCache[TE] = SavedTransformCache[TE];
}
TransformCache = std::move(SavedTransformCache);
}
Expand Down
Loading

0 comments on commit 72dfee4

Please sign in to comment.