[safestack] Layout large allocas first to reduce fragmentation.
llvm-svn: 277544
diff --git a/llvm/lib/CodeGen/SafeStackLayout.cpp b/llvm/lib/CodeGen/SafeStackLayout.cpp
index fb433c1..7d4dbd1 100644
--- a/llvm/lib/CodeGen/SafeStackLayout.cpp
+++ b/llvm/lib/CodeGen/SafeStackLayout.cpp
@@ -132,6 +132,14 @@
// If this is replaced with something smarter, it must preserve the property
// that the first object is always at the offset 0 in the stack frame (for
// StackProtectorSlot), or handle stack protector in some other way.
+
+ // Sort objects by size (largest first) to reduce fragmentation.
+ if (StackObjects.size() > 2)
+ std::stable_sort(StackObjects.begin() + 1, StackObjects.end(),
+ [](const StackObject &a, const StackObject &b) {
+ return a.Size > b.Size;
+ });
+
for (auto &Obj : StackObjects)
layoutObject(Obj);